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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1443  ! raeburn     4: # $Id: lonnet.pm,v 1.1442 2021/02/08 14:50: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.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1345    raeburn   104: use LONCAPA::LWPReq;
1.1406    raeburn   105: use LONCAPA::transliterate;
1.1117    foxr      106: 
1.1090    raeburn   107: use File::Copy;
1.676     albertel  108: 
1.195     www       109: my $readit;
1.1288    damieng   110: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  111: 
1.619     albertel  112: require Exporter;
                    113: 
                    114: our @ISA = qw (Exporter);
                    115: our @EXPORT = qw(%env);
                    116: 
1.449     matthew   117: 
1.1187    raeburn   118: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       119: {
                    120:     my $logid;
1.1187    raeburn   121:     sub write_log {
1.1188    raeburn   122: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   123:         if ($context eq 'course') {
                    124:             if (($cnum eq '') || ($cdom eq '')) {
                    125:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    126:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    127:             }
1.957     raeburn   128:         }
1.1184    raeburn   129: 	$logid ++;
1.957     raeburn   130:         my $now = time();
                    131: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1434    raeburn   132:         my $ip = &get_requestor_ip();
1.1184    raeburn   133:         my $logentry = { 
                    134:                           $id => {
                    135:                                    'exe_uname' => $env{'user.name'},
                    136:                                    'exe_udom'  => $env{'user.domain'},
                    137:                                    'exe_time'  => $now,
1.1434    raeburn   138:                                    'exe_ip'    => $ip,
1.1184    raeburn   139:                                    'delflag'   => $delflag,
                    140:                                    'logentry'  => $storehash,
                    141:                                    'uname'     => $uname,
                    142:                                    'udom'      => $udom,
                    143:                                   }
                    144:                        };
                    145: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       146:     }
                    147: }
1.1       albertel  148: 
1.163     harris41  149: sub logtouch {
                    150:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  151:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   152: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  153: 	close $fh;
                    154:     }
                    155:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    156:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    157: }
                    158: 
1.1       albertel  159: sub logthis {
                    160:     my $message=shift;
                    161:     my $execdir=$perlvar{'lonDaemons'};
                    162:     my $now=time;
                    163:     my $local=localtime($now);
1.1359    raeburn   164:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      165: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    166: 	print $fh $logstring;
1.448     albertel  167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
                    172: sub logperm {
                    173:     my $message=shift;
                    174:     my $execdir=$perlvar{'lonDaemons'};
                    175:     my $now=time;
                    176:     my $local=localtime($now);
1.1359    raeburn   177:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  178: 	print $fh "$now:$message:$local\n";
                    179: 	close($fh);
                    180:     }
1.1       albertel  181:     return 1;
                    182: }
                    183: 
1.850     albertel  184: sub create_connection {
1.853     albertel  185:     my ($hostname,$lonid) = @_;
1.851     albertel  186:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  187: 				     Type    => SOCK_STREAM,
                    188: 				     Timeout => 10);
                    189:     return 0 if (!$client);
1.1399    raeburn   190:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850     albertel  191:     my $result = <$client>;
                    192:     chomp($result);
                    193:     return 1 if ($result eq 'done');
                    194:     return 0;
                    195: }
                    196: 
1.983     raeburn   197: sub get_server_timezone {
                    198:     my ($cnum,$cdom) = @_;
                    199:     my $home=&homeserver($cnum,$cdom);
                    200:     if ($home ne 'no_host') {
                    201:         my $cachetime = 24*3600;
                    202:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    203:         if (defined($cached)) {
                    204:             return $timezone;
                    205:         } else {
                    206:             my $timezone = &reply('servertimezone',$home);
                    207:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    208:         }
                    209:     }
                    210: }
1.850     albertel  211: 
1.1106    raeburn   212: sub get_server_distarch {
                    213:     my ($lonhost,$ignore_cache) = @_;
                    214:     if (defined($lonhost)) {
                    215:         if (!defined(&hostname($lonhost))) {
                    216:             return;
                    217:         }
                    218:         my $cachetime = 12*3600;
                    219:         if (!$ignore_cache) {
                    220:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    221:             if (defined($cached)) {
                    222:                 return $distarch;
                    223:             }
                    224:         }
                    225:         my $rep = &reply('serverdistarch',$lonhost);
                    226:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    227:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    228:                 $rep eq '') {
                    229:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    230:         }
                    231:     }
                    232:     return;
                    233: }
                    234: 
1.1315    raeburn   235: sub get_servercerts_info {
1.1383    raeburn   236:     my ($lonhost,$hostname,$context) = @_;
                    237:     return if ($lonhost eq '');
                    238:     if ($hostname eq '') {
                    239:         $hostname = &hostname($lonhost);
                    240:     }
                    241:     return if ($hostname eq '');
1.1315    raeburn   242:     my ($rep,$uselocal);
1.1388    raeburn   243:     if ($context eq 'install') {
1.1387    raeburn   244:         $uselocal = 1;
                    245:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   246:         $uselocal = 1;
                    247:     }
1.1387    raeburn   248:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   249:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   250:         if ($distro eq '') {
                    251:             $uselocal = 0;
                    252:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   253:             if ($1 < 6) {
                    254:                 $uselocal = 0;
                    255:             }
1.1346    raeburn   256:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    257:             if ($1 < 12) {
                    258:                 $uselocal = 0;
                    259:             }
1.1315    raeburn   260:         }
                    261:     }
                    262:     if ($uselocal) {
1.1383    raeburn   263:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   264:     } else {
                    265:         $rep=&reply('servercerts',$lonhost);
                    266:     }
                    267:     my ($result,%returnhash);
                    268:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    269:         ($rep eq 'unknown_cmd')) {
                    270:         $result = $rep;
                    271:     } else {
                    272:         $result = 'ok';
                    273:         my @pairs=split(/\&/,$rep);
                    274:         foreach my $item (@pairs) {
                    275:             my ($key,$value)=split(/=/,$item,2);
                    276:             my $what = &unescape($key);
                    277:             $returnhash{$what}=&thaw_unescape($value);
                    278:         }
                    279:     }
                    280:     return ($result,\%returnhash);
                    281: }
                    282: 
1.993     raeburn   283: sub get_server_loncaparev {
1.1073    raeburn   284:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   285:     if (defined($lonhost)) {
                    286:         if (!defined(&hostname($lonhost))) {
                    287:             undef($lonhost);
                    288:         }
                    289:     }
                    290:     if (!defined($lonhost)) {
                    291:         if (defined(&domain($dom,'primary'))) {
                    292:             $lonhost=&domain($dom,'primary');
                    293:             if ($lonhost eq 'no_host') {
                    294:                 undef($lonhost);
                    295:             }
                    296:         }
                    297:     }
                    298:     if (defined($lonhost)) {
1.1073    raeburn   299:         my $cachetime = 12*3600;
                    300:         if (!$ignore_cache) {
                    301:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    302:             if (defined($cached)) {
                    303:                 return $loncaparev;
                    304:             }
                    305:         }
                    306:         my ($answer,$loncaparev);
                    307:         my @ids=&current_machine_ids();
                    308:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    309:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   310:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   311:                 $loncaparev = $1;
                    312:             }
                    313:         } else {
                    314:             $answer = &reply('serverloncaparev',$lonhost);
                    315:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    316:                 if ($caller eq 'loncron') {
1.1397    raeburn   317:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   318:                     my $protocol = $protocol{$lonhost};
                    319:                     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn   320:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   321:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   322:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   323:                     unless ($response->is_error()) {
                    324:                         my $content = $response->content;
1.1081    raeburn   325:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   326:                             $loncaparev = $1;
                    327:                         }
                    328:                     }
                    329:                 } else {
                    330:                     $loncaparev = $loncaparevs{$lonhost};
                    331:                 }
1.1081    raeburn   332:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   333:                 $loncaparev = $1;
                    334:             }
1.993     raeburn   335:         }
1.1073    raeburn   336:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   337:     }
                    338: }
                    339: 
1.1074    raeburn   340: sub get_server_homeID {
                    341:     my ($hostname,$ignore_cache,$caller) = @_;
                    342:     unless ($ignore_cache) {
                    343:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    344:         if (defined($cached)) {
                    345:             return $serverhomeID;
                    346:         }
                    347:     }
                    348:     my $cachetime = 12*3600;
                    349:     my $serverhomeID;
                    350:     if ($caller eq 'loncron') { 
                    351:         my @machine_ids = &machine_ids($hostname);
                    352:         foreach my $id (@machine_ids) {
                    353:             my $response = &reply('serverhomeID',$id);
                    354:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    355:                 $serverhomeID = $response;
                    356:                 last;
                    357:             }
                    358:         }
                    359:         if ($serverhomeID eq '') {
                    360:             $serverhomeID = $machine_ids[-1];
                    361:         }
                    362:     } else {
                    363:         $serverhomeID = $serverhomeIDs{$hostname};
                    364:     }
                    365:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    366: }
                    367: 
1.1121    raeburn   368: sub get_remote_globals {
                    369:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   370:     my ($result,%returnhash,%whatneeded);
                    371:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   372:         foreach my $what (sort(keys(%{$whathash}))) {
                    373:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   374:             my ($response,$cached);
1.1121    raeburn   375:             unless ($ignore_cache) {
1.1125    raeburn   376:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   377:             }
                    378:             if (defined($cached)) {
1.1125    raeburn   379:                 $returnhash{$what} = $response;
1.1121    raeburn   380:             } else {
1.1125    raeburn   381:                 $whatneeded{$what} = 1;
1.1121    raeburn   382:             }
                    383:         }
1.1125    raeburn   384:         if (keys(%whatneeded) == 0) {
                    385:             $result = 'ok';
                    386:         } else {
1.1121    raeburn   387:             my $requested = &freeze_escape(\%whatneeded);
                    388:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   389:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    390:                 ($rep eq 'unknown_cmd')) {
                    391:                 $result = $rep;
                    392:             } else {
                    393:                 $result = 'ok';
1.1121    raeburn   394:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   395:                 foreach my $item (@pairs) {
                    396:                     my ($key,$value)=split(/=/,$item,2);
                    397:                     my $what = &unescape($key);
                    398:                     my $hashid = $lonhost.'-'.$what;
                    399:                     $returnhash{$what}=&thaw_unescape($value);
                    400:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   401:                 }
                    402:             }
                    403:         }
                    404:     }
1.1125    raeburn   405:     return ($result,\%returnhash);
1.1121    raeburn   406: }
                    407: 
1.1124    raeburn   408: sub remote_devalidate_cache {
1.1241    raeburn   409:     my ($lonhost,$cachekeys) = @_;
                    410:     my $items;
                    411:     return unless (ref($cachekeys) eq 'ARRAY');
                    412:     my $cachestr = join('&',@{$cachekeys});
                    413:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   414:     return $response;
                    415: }
                    416: 
1.1       albertel  417: # -------------------------------------------------- Non-critical communication
                    418: sub subreply {
                    419:     my ($cmd,$server)=@_;
1.838     albertel  420:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      421:     #
                    422:     #  With loncnew process trimming, there's a timing hole between lonc server
                    423:     #  process exit and the master server picking up the listen on the AF_UNIX
                    424:     #  socket.  In that time interval, a lock file will exist:
                    425: 
                    426:     my $lockfile=$peerfile.".lock";
                    427:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   428: 	sleep(0.1);
1.549     foxr      429:     }
                    430:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      431:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      432:     #
1.550     foxr      433:     #   We'll give the connection a few tries before abandoning it.  If
                    434:     #   connection is not possible, we'll con_lost back to the client.
                    435:     #   
                    436:     my $client;
                    437:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    438: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    439: 				      Type    => SOCK_STREAM,
                    440: 				      Timeout => 10);
1.869     albertel  441: 	if ($client) {
1.550     foxr      442: 	    last;		# Connected!
1.850     albertel  443: 	} else {
1.853     albertel  444: 	    &create_connection(&hostname($server),$server);
1.550     foxr      445: 	}
1.1289    damieng   446:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      447:     }
                    448:     my $answer;
                    449:     if ($client) {
1.704     albertel  450: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      451: 	$answer=<$client>;
                    452: 	if (!$answer) { $answer="con_lost"; }
                    453: 	chomp($answer);
                    454:     } else {
                    455: 	$answer = 'con_lost';	# Failed connection.
                    456:     }
1.1       albertel  457:     return $answer;
                    458: }
                    459: 
                    460: sub reply {
                    461:     my ($cmd,$server)=@_;
1.838     albertel  462:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  463:     my $answer=subreply($cmd,$server);
1.65      www       464:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   465:         my $logged = $cmd;
                    466:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    467:             my $subcmd = $1;
                    468:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    469:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    470:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    471:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    472:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    473:                     splice(@rest,2,1,'Hidden');
                    474:                 } elsif ($subcmd eq 'passwd') {
                    475:                     splice(@rest,2,2,('Hidden','Hidden'));
                    476:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    477:                          ($subcmd eq 'autoexportgrades')) {
                    478:                     splice(@rest,3,1,'Hidden');
                    479:                 }
                    480:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    481:             }
                    482:         }
                    483:         &logthis("<font color=\"blue\">WARNING:".
                    484:                  " $logged to $server returned $answer</font>");
1.12      www       485:     }
1.1       albertel  486:     return $answer;
                    487: }
                    488: 
                    489: # ----------------------------------------------------------- Send USR1 to lonc
                    490: 
                    491: sub reconlonc {
1.891     albertel  492:     my ($lonid) = @_;
                    493:     if ($lonid) {
1.1295    raeburn   494:         my $hostname = &hostname($lonid);
1.891     albertel  495: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    496: 	if ($hostname && -e $peerfile) {
                    497: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    498: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    499: 					     Type    => SOCK_STREAM,
                    500: 					     Timeout => 10);
                    501: 	    if ($client) {
                    502: 		print $client ("reset_retries\n");
                    503: 		my $answer=<$client>;
                    504: 		#reset just this one.
                    505: 	    }
                    506: 	}
                    507: 	return;
                    508:     }
                    509: 
1.836     www       510:     &logthis("Trying to reconnect lonc");
1.1       albertel  511:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   512:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  513: 	my $loncpid=<$fh>;
                    514:         chomp($loncpid);
                    515:         if (kill 0 => $loncpid) {
                    516: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    517:             kill USR1 => $loncpid;
                    518:             sleep 1;
1.1295    raeburn   519:         } else {
1.12      www       520: 	    &logthis(
1.672     albertel  521:                "<font color=\"blue\">WARNING:".
1.12      www       522:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  523:         }
                    524:     } else {
1.836     www       525: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  526:     }
                    527: }
                    528: 
                    529: # ------------------------------------------------------ Critical communication
1.12      www       530: 
1.1       albertel  531: sub critical {
                    532:     my ($cmd,$server)=@_;
1.838     albertel  533:     unless (&hostname($server)) {
1.672     albertel  534:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       535:                " Critical message to unknown server ($server)</font>");
                    536:         return 'no_such_host';
                    537:     }
1.1       albertel  538:     my $answer=reply($cmd,$server);
                    539:     if ($answer eq 'con_lost') {
1.1295    raeburn   540: 	&reconlonc($server);
1.589     albertel  541: 	my $answer=reply($cmd,$server);
1.1       albertel  542:         if ($answer eq 'con_lost') {
                    543:             my $now=time;
                    544:             my $middlename=$cmd;
1.5       www       545:             $middlename=substr($middlename,0,16);
1.1       albertel  546:             $middlename=~s/\W//g;
                    547:             my $dfilename=
1.305     www       548:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    549:             $dumpcount++;
1.1       albertel  550:             {
1.448     albertel  551: 		my $dfh;
1.1359    raeburn   552: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  553: 		    print $dfh "$cmd\n"; 
                    554: 		    close($dfh);
                    555: 		}
1.1       albertel  556:             }
1.1288    damieng   557:             sleep 1;
1.1       albertel  558:             my $wcmd='';
                    559:             {
1.448     albertel  560: 		my $dfh;
1.1359    raeburn   561: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  562: 		    $wcmd=<$dfh>; 
                    563: 		    close($dfh);
                    564: 		}
1.1       albertel  565:             }
                    566:             chomp($wcmd);
1.7       www       567:             if ($wcmd eq $cmd) {
1.672     albertel  568: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       569:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  570:                 &logperm("D:$server:$cmd");
                    571: 	        return 'con_delayed';
                    572:             } else {
1.672     albertel  573:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       574:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  575:                 &logperm("F:$server:$cmd");
                    576:                 return 'con_failed';
                    577:             }
                    578:         }
                    579:     }
                    580:     return $answer;
1.405     albertel  581: }
                    582: 
1.755     albertel  583: # ------------------------------------------- check if return value is an error
                    584: 
                    585: sub error {
                    586:     my ($result) = @_;
1.756     albertel  587:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  588: 	if ($2 == 2) { return undef; }
                    589: 	return $1;
                    590:     }
                    591:     return undef;
                    592: }
                    593: 
1.783     albertel  594: sub convert_and_load_session_env {
                    595:     my ($lonidsdir,$handle)=@_;
                    596:     my @profile;
                    597:     {
1.917     albertel  598: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    599: 	if (!$opened) {
1.915     albertel  600: 	    return 0;
                    601: 	}
1.783     albertel  602: 	flock($idf,LOCK_SH);
                    603: 	@profile=<$idf>;
                    604: 	close($idf);
                    605:     }
                    606:     my %temp_env;
                    607:     foreach my $line (@profile) {
1.786     albertel  608: 	if ($line !~ m/=/) {
                    609: 	    return 0;
                    610: 	}
1.783     albertel  611: 	chomp($line);
                    612: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    613: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    614:     }
                    615:     unlink("$lonidsdir/$handle.id");
                    616:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    617: 	    0640)) {
                    618: 	%disk_env = %temp_env;
                    619: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    620: 	untie(%disk_env);
                    621:     }
1.786     albertel  622:     return 1;
1.783     albertel  623: }
                    624: 
1.374     www       625: # ------------------------------------------- Transfer profile into environment
1.780     albertel  626: my $env_loaded;
                    627: sub transfer_profile_to_env {
1.788     albertel  628:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    629:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       630: 
1.720     albertel  631:     if (!defined($lonidsdir)) {
                    632: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    633:     }
                    634:     if (!defined($handle)) {
                    635:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    636:     }
                    637: 
1.786     albertel  638:     my $convert;
                    639:     {
1.917     albertel  640:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    641: 	if (!$opened) {
1.915     albertel  642: 	    return;
                    643: 	}
1.786     albertel  644: 	flock($idf,LOCK_SH);
                    645: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    646: 		&GDBM_READER(),0640)) {
                    647: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    648: 	    untie(%disk_env);
                    649: 	} else {
                    650: 	    $convert = 1;
                    651: 	}
                    652:     }
                    653:     if ($convert) {
                    654: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    655: 	    &logthis("Failed to load session, or convert session.");
                    656: 	}
1.374     www       657:     }
1.783     albertel  658: 
1.786     albertel  659:     my %remove;
1.783     albertel  660:     while ( my $envname = each(%env) ) {
1.433     matthew   661:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    662:             if ($time < time-300) {
1.783     albertel  663:                 $remove{$key}++;
1.433     matthew   664:             }
                    665:         }
                    666:     }
1.783     albertel  667: 
1.619     albertel  668:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  669:     $env_loaded=1;
1.783     albertel  670:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   671:         &delenv($expired_key);
1.374     www       672:     }
1.1       albertel  673: }
                    674: 
1.916     albertel  675: # ---------------------------------------------------- Check for valid session 
                    676: sub check_for_valid_session {
1.1355    raeburn   677:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  678:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   679:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    680:     if ($name eq 'lonDAV') {
                    681:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    682:     } else {
                    683:         $lonidsdir=$r->dir_config('lonIDsDir');
                    684:         if ($name eq '') {
                    685:             $name = 'lonID';
                    686:         }
                    687:     }
                    688:     if ($name eq 'lonID') {
                    689:         $secure = 'lonSID';
1.1337    raeburn   690:         $linkname = 'lonLinkID';
                    691:         $pubname = 'lonPubID';
1.1378    raeburn   692:         if (exists($cookies{$secure})) {
                    693:             $lonid=$cookies{$secure};
                    694:         } elsif (exists($cookies{$name})) {
                    695:             $lonid=$cookies{$name};
1.1400    raeburn   696:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337    raeburn   697:             $lonid=$cookies{$linkname};
1.1378    raeburn   698:         } elsif (exists($cookies{$pubname})) {
                    699:             $lonid=$cookies{$pubname};
1.1337    raeburn   700:         }
1.1378    raeburn   701:     } else {
                    702:         $lonid=$cookies{$name};
1.1337    raeburn   703:     }
1.916     albertel  704:     return undef if (!$lonid);
                    705: 
                    706:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   707:     if (-l "$lonidsdir/$handle.id") {
                    708:         my $link = readlink("$lonidsdir/$handle.id");
                    709:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    710:             $handle = $1;
                    711:         }
1.1155    raeburn   712:     }
1.1355    raeburn   713:     if (!-e "$lonidsdir/$handle.id") {
                    714:         if ((ref($domref)) && ($name eq 'lonID') && 
                    715:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    716:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    717:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    718:                 $$domref = $possudom;
                    719:             }
                    720:         }
                    721:         return undef;
                    722:     }
1.916     albertel  723: 
1.917     albertel  724:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    725:     return undef if (!$opened);
1.916     albertel  726: 
                    727:     flock($idf,LOCK_SH);
                    728:     my %disk_env;
                    729:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    730: 	    &GDBM_READER(),0640)) {
                    731: 	return undef;	
                    732:     }
                    733: 
                    734:     if (!defined($disk_env{'user.name'})
                    735: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   736:         untie(%disk_env);
1.916     albertel  737: 	return undef;
                    738:     }
1.1245    raeburn   739: 
                    740:     if (ref($userhashref) eq 'HASH') {
                    741:         $userhashref->{'name'} = $disk_env{'user.name'};
                    742:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   743:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   744:         if ($userhashref->{'lti'}) {
                    745:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    746:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    747:         }
1.1212    raeburn   748:     }
1.1394    raeburn   749:     untie(%disk_env);
1.1245    raeburn   750: 
1.916     albertel  751:     return $handle;
                    752: }
                    753: 
1.830     albertel  754: sub timed_flock {
                    755:     my ($file,$lock_type) = @_;
                    756:     my $failed=0;
                    757:     eval {
                    758: 	local $SIG{__DIE__}='DEFAULT';
                    759: 	local $SIG{ALRM}=sub {
                    760: 	    $failed=1;
                    761: 	    die("failed lock");
                    762: 	};
                    763: 	alarm(13);
                    764: 	flock($file,$lock_type);
                    765: 	alarm(0);
                    766:     };
                    767:     if ($failed) {
                    768: 	return undef;
                    769:     } else {
                    770: 	return 1;
                    771:     }
                    772: }
                    773: 
1.1392    raeburn   774: sub get_sessionfile_vars {
                    775:     my ($handle,$lonidsdir,$storearr) = @_;
                    776:     my %returnhash;
                    777:     unless (ref($storearr) eq 'ARRAY') {
                    778:         return %returnhash;
                    779:     }
                    780:     if (-l "$lonidsdir/$handle.id") {
                    781:         my $link = readlink("$lonidsdir/$handle.id");
                    782:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    783:             $handle = $1;
                    784:         }
                    785:     }
                    786:     if ((-e "$lonidsdir/$handle.id") &&
                    787:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    788:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    789:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    790:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    791:                 flock($idf,LOCK_SH);
                    792:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    793:                         &GDBM_READER(),0640)) {
                    794:                     foreach my $item (@{$storearr}) {
                    795:                         $returnhash{$item} = $disk_env{$item};
                    796:                     }
                    797:                     untie(%disk_env);
                    798:                 }
                    799:             }
                    800:         }
                    801:     }
                    802:     return %returnhash;
                    803: }
                    804: 
1.5       www       805: # ---------------------------------------------------------- Append Environment
                    806: 
                    807: sub appenv {
1.949     raeburn   808:     my ($newenv,$roles) = @_;
                    809:     if (ref($newenv) eq 'HASH') {
                    810:         foreach my $key (keys(%{$newenv})) {
                    811:             my $refused = 0;
                    812: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    813:                 $refused = 1;
                    814:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   815:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   816:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    817:                         $refused = 0;
                    818:                     }
                    819:                 }
                    820:             }
                    821:             if ($refused) {
                    822:                 &logthis("<font color=\"blue\">WARNING: ".
                    823:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    824:                          .'</font>');
                    825: 	        delete($newenv->{$key});
                    826:             } else {
                    827:                 $env{$key}=$newenv->{$key};
                    828:             }
                    829:         }
1.1376    raeburn   830:         my $lonids = $perlvar{'lonIDsDir'};
                    831:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    832:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    833:             if ($opened
                    834: 	        && &timed_flock($env_file,LOCK_EX)
                    835: 	        &&
                    836: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    837: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    838: 	        while (my ($key,$value) = each(%{$newenv})) {
                    839: 	            $disk_env{$key} = $value;
                    840: 	        }
                    841: 	        untie(%disk_env);
                    842:             }
1.35      www       843:         }
1.191     harris41  844:     }
1.56      www       845:     return 'ok';
                    846: }
                    847: # ----------------------------------------------------- Delete from Environment
                    848: 
                    849: sub delenv {
1.1104    raeburn   850:     my ($delthis,$regexp,$roles) = @_;
                    851:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    852:         my $refused = 1;
                    853:         if (ref($roles) eq 'ARRAY') {
                    854:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    855:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    856:                 $refused = 0;
                    857:             }
                    858:         }
                    859:         if ($refused) {
                    860:             &logthis("<font color=\"blue\">WARNING: ".
                    861:                      "Attempt to delete from environment ".$delthis);
                    862:             return 'error';
                    863:         }
1.56      www       864:     }
1.917     albertel  865:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    866:     if ($opened
1.915     albertel  867: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  868: 	&&
                    869: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    870: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  871: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   872: 	    if ($regexp) {
                    873:                 if ($key=~/^$delthis/) {
                    874:                     delete($env{$key});
                    875:                     delete($disk_env{$key});
                    876:                 } 
                    877:             } else {
                    878:                 if ($key=~/^\Q$delthis\E/) {
                    879: 		    delete($env{$key});
                    880: 		    delete($disk_env{$key});
                    881: 	        }
                    882:             }
1.448     albertel  883: 	}
1.783     albertel  884: 	untie(%disk_env);
1.5       www       885:     }
                    886:     return 'ok';
1.369     albertel  887: }
                    888: 
1.790     albertel  889: sub get_env_multiple {
                    890:     my ($name) = @_;
                    891:     my @values;
                    892:     if (defined($env{$name})) {
                    893:         # exists is it an array
                    894:         if (ref($env{$name})) {
                    895:             @values=@{ $env{$name} };
                    896:         } else {
                    897:             $values[0]=$env{$name};
                    898:         }
                    899:     }
                    900:     return(@values);
                    901: }
                    902: 
1.958     www       903: # ------------------------------------------------------------------- Locking
                    904: 
                    905: sub set_lock {
                    906:     my ($text)=@_;
                    907:     $locknum++;
                    908:     my $id=$$.'-'.$locknum;
                    909:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    910:              'session.lock.'.$id => $text});
                    911:     return $id;
                    912: }
                    913: 
                    914: sub get_locks {
                    915:     my $num=0;
                    916:     my %texts=();
                    917:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    918:        if ($lock=~/\w/) {
                    919:           $num++;
                    920:           $texts{$lock}=$env{'session.lock.'.$lock};
                    921:        }
                    922:    }
                    923:    return ($num,%texts);
                    924: }
                    925: 
                    926: sub remove_lock {
                    927:     my ($id)=@_;
                    928:     my $newlocks='';
                    929:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    930:        if (($lock=~/\w/) && ($lock ne $id)) {
                    931:           $newlocks.=','.$lock;
                    932:        }
                    933:     }
                    934:     &appenv({'session.locks' => $newlocks});
                    935:     &delenv('session.lock.'.$id);
                    936: }
                    937: 
                    938: sub remove_all_locks {
                    939:     my $activelocks=$env{'session.locks'};
                    940:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    941:        if ($lock=~/\w/) {
                    942:           &remove_lock($lock);
                    943:        }
                    944:     }
                    945: }
                    946: 
                    947: 
1.369     albertel  948: # ------------------------------------------ Find out current server userload
                    949: sub userload {
                    950:     my $numusers=0;
                    951:     {
                    952: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    953: 	my $filename;
                    954: 	my $curtime=time;
                    955: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  956: 	    next if ($filename eq '.' || $filename eq '..');
                    957: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   958:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  959: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  960: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  961: 	}
                    962: 	closedir(LONIDS);
                    963:     }
                    964:     my $userloadpercent=0;
                    965:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    966:     if ($maxuserload) {
1.371     albertel  967: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  968:     }
1.372     albertel  969:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  970:     return $userloadpercent;
1.283     www       971: }
                    972: 
1.1       albertel  973: # ------------------------------ Find server with least workload from spare.tab
1.11      www       974: 
1.1       albertel  975: sub spareserver {
1.1083    raeburn   976:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  977:     my $spare_server;
1.370     albertel  978:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  979:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    980:                                                      :  $userloadpercent;
1.1083    raeburn   981:     my ($uint_dom,$remotesessions);
                    982:     if (($udom ne '') && (&domain($udom) ne '')) {
                    983:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    984:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    985:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    986:         $remotesessions = $udomdefaults{'remotesessions'};
                    987:     }
1.1123    raeburn   988:     my $spareshash = &this_host_spares($udom);
                    989:     if (ref($spareshash) eq 'HASH') {
                    990:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    991:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   992:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    993:                                              $try_server));
1.1123    raeburn   994: 	        ($spare_server, $lowest_load) =
                    995: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    996:             }
1.1083    raeburn   997:         }
1.784     albertel  998: 
1.1123    raeburn   999:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1000: 
                   1001:         if (!$found_server) {
                   1002:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1003: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1004:                     next unless (&spare_can_host($udom,$uint_dom,
                   1005:                                                  $remotesessions,$try_server));
1.1123    raeburn  1006: 	            ($spare_server, $lowest_load) =
                   1007: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1008:                 }
                   1009: 	    }
                   1010:         }
1.784     albertel 1011:     }
                   1012: 
                   1013:     if (!$want_server_name) {
1.1001    raeburn  1014:         if (defined($spare_server)) {
                   1015:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1016:             if (defined($hostname)) {
1.1397    raeburn  1017:                 my $protocol = 'http';
                   1018:                 if ($protocol{$spare_server} eq 'https') {
                   1019:                     $protocol = $protocol{$spare_server};
                   1020:                 }
1.1001    raeburn  1021: 	        $spare_server = $protocol.'://'.$hostname;
                   1022:             }
                   1023:         }
1.784     albertel 1024:     }
                   1025:     return $spare_server;
                   1026: }
                   1027: 
                   1028: sub compare_server_load {
1.1253    raeburn  1029:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1030: 
                   1031:     if ($required) {
                   1032:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1033:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1034:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1035:         if (($major eq '' && $minor eq '') ||
                   1036:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1037:             return ($spare_server,$lowest_load);
                   1038:         }
                   1039:     }
1.784     albertel 1040: 
                   1041:     my $loadans     = &reply('load',    $try_server);
                   1042:     my $userloadans = &reply('userload',$try_server);
                   1043: 
                   1044:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1045: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1046:     }
                   1047: 
                   1048:     my $load;
                   1049:     if ($loadans =~ /\d/) {
                   1050: 	if ($userloadans =~ /\d/) {
                   1051: 	    #both are numbers, pick the bigger one
                   1052: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1053: 		                              : $userloadans;
1.411     albertel 1054: 	} else {
1.784     albertel 1055: 	    $load = $loadans;
1.411     albertel 1056: 	}
1.784     albertel 1057:     } else {
                   1058: 	$load = $userloadans;
                   1059:     }
                   1060: 
                   1061:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1062: 	$spare_server = $try_server;
                   1063: 	$lowest_load  = $load;
1.370     albertel 1064:     }
1.784     albertel 1065:     return ($spare_server,$lowest_load);
1.202     matthew  1066: }
1.914     albertel 1067: 
                   1068: # --------------------------- ask offload servers if user already has a session
                   1069: sub find_existing_session {
                   1070:     my ($udom,$uname) = @_;
1.1123    raeburn  1071:     my $spareshash = &this_host_spares($udom);
                   1072:     if (ref($spareshash) eq 'HASH') {
                   1073:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1074:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1075:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1076:             }
                   1077:         }
                   1078:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1079:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1080:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1081:             }
                   1082:         }
1.914     albertel 1083:     }
                   1084:     return;
                   1085: }
                   1086: 
1.1411    raeburn  1087: sub delusersession {
                   1088:     my ($lonid,$udom,$uname) = @_;
                   1089:     my $uprimary_id = &domain($udom,'primary');
                   1090:     my $uintdom = &internet_dom($uprimary_id);
                   1091:     my $intdom = &internet_dom($lonid);
                   1092:     my $serverhomedom = &host_domain($lonid);
                   1093:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1094:         return &reply(join(':','delusersession',
                   1095:                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1096:     }
                   1097:     return;
                   1098: }
                   1099: 
1.1389    raeburn  1100: # check if user's browser sent load balancer cookie and server still has session
                   1101: # and is not overloaded.
                   1102: sub check_for_balancer_cookie {
                   1103:     my ($r,$update_mtime) = @_;
                   1104:     my ($otherserver,$cookie);
                   1105:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1106:     if (exists($cookies{'balanceID'})) {
                   1107:         my $balid = $cookies{'balanceID'};
                   1108:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1109:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1110:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1111:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1112:                 my ($possudom,$possuname) = ($1,$2);
                   1113:                 my $has_session = 0;
                   1114:                 if ((&domain($possudom) ne '') &&
                   1115:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1116:                     my $try_server;
                   1117:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1118:                     if ($opened) {
                   1119:                         flock($idf,LOCK_SH);
                   1120:                         while (my $line = <$idf>) {
                   1121:                             chomp($line);
                   1122:                             if (&hostname($line) ne '') {
                   1123:                                 $try_server = $line;
                   1124:                                 last;
                   1125:                             }
                   1126:                         }
                   1127:                         close($idf);
                   1128:                         if (($try_server) &&
                   1129:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1130:                             my $lowest_load = 30000;
                   1131:                             ($otherserver,$lowest_load) =
                   1132:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1133:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1134:                                 $has_session = 1;
                   1135:                             } else {
                   1136:                                 undef($otherserver);
                   1137:                             }
                   1138:                         }
                   1139:                     }
                   1140:                 }
                   1141:                 if ($has_session) {
                   1142:                     if ($update_mtime) {
                   1143:                         my $atime = my $mtime = time;
                   1144:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1145:                     }
                   1146:                 } else {
                   1147:                     unlink("$balancedir/$cookie.id");
                   1148:                 }
                   1149:             }
                   1150:         }
                   1151:     }
                   1152:     return ($otherserver,$cookie);
                   1153: }
                   1154: 
1.1431    raeburn  1155: sub updatebalcookie {
                   1156:     my ($cookie,$balancer,$lastentry)=@_;
                   1157:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1158:         my ($udom,$uname) = ($1,$2);
                   1159:         my $uprimary_id = &domain($udom,'primary');
                   1160:         my $uintdom = &internet_dom($uprimary_id);
                   1161:         my $intdom = &internet_dom($balancer);
                   1162:         my $serverhomedom = &host_domain($balancer);
                   1163:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1164:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1165:         }
                   1166:     }
                   1167:     return;
                   1168: }
                   1169: 
1.1389    raeburn  1170: sub delbalcookie {
                   1171:     my ($cookie,$balancer) =@_;
                   1172:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1173:         my ($udom,$uname) = ($1,$2);
                   1174:         my $uprimary_id = &domain($udom,'primary');
                   1175:         my $uintdom = &internet_dom($uprimary_id);
                   1176:         my $intdom = &internet_dom($balancer);
                   1177:         my $serverhomedom = &host_domain($balancer);
                   1178:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431    raeburn  1179:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389    raeburn  1180:         }
                   1181:     }
                   1182: }
                   1183: 
1.914     albertel 1184: # -------------------------------- ask if server already has a session for user
                   1185: sub has_user_session {
                   1186:     my ($lonid,$udom,$uname) = @_;
                   1187:     my $result = &reply(join(':','userhassession',
                   1188: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1189:     return 1 if ($result eq 'ok');
                   1190: 
                   1191:     return 0;
                   1192: }
                   1193: 
1.1076    raeburn  1194: # --------- determine least loaded server in a user's domain which allows login
                   1195: 
                   1196: sub choose_server {
1.1259    raeburn  1197:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1198:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1199:     my %servers = &get_servers($udom);
1.1076    raeburn  1200:     my $lowest_load = 30000;
1.1259    raeburn  1201:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1202:     if ($skiploadbal) {
                   1203:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1204:         unless (defined($cached)) {
                   1205:             my $cachetime = 60*60*24;
                   1206:             my %domconfig =
                   1207:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1208:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1209:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1210:                                            $cachetime);
                   1211:             }
                   1212:         }
                   1213:     }
1.1076    raeburn  1214:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1215:         if ($skiploadbal) {
                   1216:             if (ref($balancers) eq 'HASH') {
                   1217:                 next if (exists($balancers->{$lonhost}));
                   1218:             }
1.1389    raeburn  1219:         }
1.1115    raeburn  1220:         my $loginvia;
                   1221:         if ($checkloginvia) {
                   1222:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1223:             if ($loginvia) {
                   1224:                 my ($server,$path) = split(/:/,$loginvia);
                   1225:                 ($login_host, $lowest_load) =
1.1253    raeburn  1226:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1227:                 if ($login_host eq $server) {
                   1228:                     $portal_path = $path;
1.1151    raeburn  1229:                     $isredirect = 1;
1.1116    raeburn  1230:                 }
                   1231:             } else {
                   1232:                 ($login_host, $lowest_load) =
1.1253    raeburn  1233:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1234:                 if ($login_host eq $lonhost) {
                   1235:                     $portal_path = '';
1.1151    raeburn  1236:                     $isredirect = ''; 
1.1116    raeburn  1237:                 }
                   1238:             }
                   1239:         } else {
1.1076    raeburn  1240:             ($login_host, $lowest_load) =
1.1253    raeburn  1241:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1242:         }
                   1243:     }
                   1244:     if ($login_host ne '') {
1.1116    raeburn  1245:         $hostname = &hostname($login_host);
1.1076    raeburn  1246:     }
1.1331    raeburn  1247:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1248: }
                   1249: 
1.1420    raeburn  1250: sub get_course_sessions {
                   1251:     my ($cnum,$cdom,$lastactivity) = @_;
                   1252:     my %servers = &internet_dom_servers($cdom);
                   1253:     my %returnhash;
                   1254:     foreach my $server (sort(keys(%servers))) {
                   1255:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1256:         my @pairs=split(/\&/,$rep);
                   1257:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1258:             foreach my $item (@pairs) {
                   1259:                 my ($key,$value)=split(/=/,$item,2);
                   1260:                 $key = &unescape($key);
                   1261:                 next if ($key =~ /^error: 2 /);
                   1262:                 if (exists($returnhash{$key})) {
                   1263:                     next if ($value < $returnhash{$key});
                   1264:                 }
                   1265:                 $returnhash{$key}=$value;
                   1266:             }
                   1267:         }
                   1268:     }
                   1269:     return %returnhash;
                   1270: }
                   1271: 
1.202     matthew  1272: # --------------------------------------------- Try to change a user's password
                   1273: 
                   1274: sub changepass {
1.799     raeburn  1275:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1276:     $currentpass = &escape($currentpass);
                   1277:     $newpass     = &escape($newpass);
1.1030    raeburn  1278:     my $lonhost = $perlvar{'lonHostID'};
                   1279:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1280: 		       $server);
                   1281:     if (! $answer) {
                   1282: 	&logthis("No reply on password change request to $server ".
                   1283: 		 "by $uname in domain $udom.");
                   1284:     } elsif ($answer =~ "^ok") {
                   1285:         &logthis("$uname in $udom successfully changed their password ".
                   1286: 		 "on $server.");
                   1287:     } elsif ($answer =~ "^pwchange_failure") {
                   1288: 	&logthis("$uname in $udom was unable to change their password ".
                   1289: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1290: 		 "or pwchange");
                   1291:     } elsif ($answer =~ "^non_authorized") {
                   1292:         &logthis("$uname in $udom did not get their password correct when ".
                   1293: 		 "attempting to change it on $server.");
                   1294:     } elsif ($answer =~ "^auth_mode_error") {
                   1295:         &logthis("$uname in $udom attempted to change their password despite ".
                   1296: 		 "not being locally or internally authenticated on $server.");
                   1297:     } elsif ($answer =~ "^unknown_user") {
                   1298:         &logthis("$uname in $udom attempted to change their password ".
                   1299: 		 "on $server but were unable to because $server is not ".
                   1300: 		 "their home server.");
                   1301:     } elsif ($answer =~ "^refused") {
                   1302: 	&logthis("$server refused to change $uname in $udom password because ".
                   1303: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1304:     } elsif ($answer =~ "invalid_client") {
                   1305:         &logthis("$server refused to change $uname in $udom password because ".
                   1306:                  "it was a reset by e-mail originating from an invalid server.");
1.1408    raeburn  1307:     } elsif ($answer =~ "^prioruse") {
                   1308:        &logthis("$server refused to change $uname in $udom password because ".
                   1309:                 "the password had been used before");
1.202     matthew  1310:     }
                   1311:     return $answer;
1.1       albertel 1312: }
                   1313: 
1.169     harris41 1314: # ----------------------- Try to determine user's current authentication scheme
                   1315: 
                   1316: sub queryauthenticate {
                   1317:     my ($uname,$udom)=@_;
1.456     albertel 1318:     my $uhome=&homeserver($uname,$udom);
                   1319:     if (!$uhome) {
                   1320: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1321: 	return 'no_host';
                   1322:     }
                   1323:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1324:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1325: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1326:     }
1.456     albertel 1327:     return $answer;
1.169     harris41 1328: }
                   1329: 
1.1       albertel 1330: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1331: 
1.1       albertel 1332: sub authenticate {
1.1073    raeburn  1333:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1334:     $upass=&escape($upass);
                   1335:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1336:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1337:     my $newhome;
1.836     www      1338:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1339: # Maybe the machine was offline and only re-appeared again recently?
                   1340:         &reconlonc();
                   1341: # One more
1.952     raeburn  1342: 	$uhome=&homeserver($uname,$udom,1);
                   1343:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1344:             if (defined(&domain($udom,'primary'))) {
                   1345:                 $newhome=&domain($udom,'primary');
                   1346:             }
                   1347:             if ($newhome ne '') {
                   1348:                 $uhome = $newhome;
                   1349:             }
                   1350:         }
1.836     www      1351: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1352: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1353: 	    return 'no_host';
                   1354:         }
1.1       albertel 1355:     }
1.1073    raeburn  1356:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1357:     if ($answer eq 'authorized') {
1.952     raeburn  1358:         if ($newhome) {
                   1359:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1360:             return 'no_account_on_host'; 
                   1361:         } else {
                   1362:             &logthis("User $uname at $udom authorized by $uhome");
                   1363:             return $uhome;
                   1364:         }
1.471     albertel 1365:     }
                   1366:     if ($answer eq 'non_authorized') {
                   1367: 	&logthis("User $uname at $udom rejected by $uhome");
                   1368: 	return 'no_host'; 
1.9       www      1369:     }
1.471     albertel 1370:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1371:     return 'no_host';
                   1372: }
                   1373: 
1.1073    raeburn  1374: sub can_host_session {
1.1074    raeburn  1375:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1376:     my $canhost = 1;
1.1074    raeburn  1377:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1378:     if (ref($remotesessions) eq 'HASH') {
                   1379:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1380:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1381:                 $canhost = 0;
                   1382:             } else {
                   1383:                 $canhost = 1;
                   1384:             }
                   1385:         }
                   1386:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1387:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1388:                 $canhost = 1;
                   1389:             } else {
                   1390:                 $canhost = 0;
                   1391:             }
                   1392:         }
                   1393:         if ($canhost) {
                   1394:             if ($remotesessions->{'version'} ne '') {
                   1395:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1396:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1397:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1398:                         my $major = $1;
                   1399:                         my $minor = $2;
                   1400:                         if (($major < $reqmajor ) ||
                   1401:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1402:                             $canhost = 0;
                   1403:                         }
                   1404:                     } else {
                   1405:                         $canhost = 0;
                   1406:                     }
                   1407:                 }
                   1408:             }
                   1409:         }
                   1410:     }
                   1411:     if ($canhost) {
                   1412:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1413:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1414:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1415:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1416:                 if (($uint_dom ne '') && 
                   1417:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1418:                     $canhost = 0;
                   1419:                 } else {
                   1420:                     $canhost = 1;
                   1421:                 }
                   1422:             }
                   1423:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1424:                 if (($uint_dom ne '') && 
                   1425:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1426:                     $canhost = 1;
                   1427:                 } else {
                   1428:                     $canhost = 0;
                   1429:                 }
                   1430:             }
                   1431:         }
                   1432:     }
                   1433:     return $canhost;
                   1434: }
                   1435: 
1.1083    raeburn  1436: sub spare_can_host {
                   1437:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1438:     my $canhost=1;
1.1279    raeburn  1439:     my $try_server_hostname = &hostname($try_server);
                   1440:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1441:     my $serverhomedom = &host_domain($serverhomeID);
                   1442:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1443:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1444:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1445:             $canhost = 0;
                   1446:         }
                   1447:     }
1.1439    raeburn  1448:     if ($canhost) {
                   1449:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1450:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1451:                 unless (&shared_institution($udom,$try_server)) {
                   1452:                     $canhost = 0;
                   1453:                 }
                   1454:             }
                   1455:         }
                   1456:     }
1.1279    raeburn  1457:     if (($canhost) && ($uint_dom)) {
                   1458:         my @intdoms;
                   1459:         my $internet_names = &get_internet_names($try_server);
                   1460:         if (ref($internet_names) eq 'ARRAY') {
                   1461:             @intdoms = @{$internet_names};
                   1462:         }
                   1463:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1464:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1465:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1466:                                          $remotesessions,
                   1467:                                          $defdomdefaults{'hostedsessions'});
                   1468:         }
1.1083    raeburn  1469:     }
                   1470:     return $canhost;
                   1471: }
                   1472: 
1.1123    raeburn  1473: sub this_host_spares {
                   1474:     my ($dom) = @_;
1.1126    raeburn  1475:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1476:     my @hosts = &current_machine_ids();
                   1477:     foreach my $lonhost (@hosts) {
                   1478:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1479:             $dom_in_use = $dom;
                   1480:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1481:             last;
                   1482:         }
                   1483:     }
1.1126    raeburn  1484:     if ($dom_in_use ne '') {
                   1485:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1486:     }
                   1487:     if (ref($result) ne 'HASH') {
                   1488:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1489:         $dom_in_use = &host_domain($lonhost_in_use);
                   1490:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1491:         if (ref($result) ne 'HASH') {
                   1492:             $result = \%spareid;
                   1493:         }
                   1494:     }
                   1495:     return $result;
                   1496: }
                   1497: 
                   1498: sub spares_for_offload  {
                   1499:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1500:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1501:     if (defined($cached)) {
                   1502:         return $result;
                   1503:     } else {
1.1126    raeburn  1504:         my $cachetime = 60*60*24;
                   1505:         my %domconfig =
                   1506:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1507:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1508:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1509:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1510:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1511:                 }
                   1512:             }
                   1513:         }
                   1514:     }
1.1126    raeburn  1515:     return;
1.1123    raeburn  1516: }
                   1517: 
1.1129    raeburn  1518: sub get_lonbalancer_config {
                   1519:     my ($servers) = @_;
                   1520:     my ($currbalancer,$currtargets);
                   1521:     if (ref($servers) eq 'HASH') {
                   1522:         foreach my $server (keys(%{$servers})) {
                   1523:             my %what = (
                   1524:                          spareid => 1,
                   1525:                          perlvar => 1,
                   1526:                        );
                   1527:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1528:             if ($result eq 'ok') {
                   1529:                 if (ref($returnhash) eq 'HASH') {
                   1530:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1531:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1532:                             $currbalancer = $server;
                   1533:                             $currtargets = {};
                   1534:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1535:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1536:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1537:                                 }
                   1538:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1539:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1540:                                 }
                   1541:                             }
                   1542:                             last;
                   1543:                         }
                   1544:                     }
                   1545:                 }
                   1546:             }
                   1547:         }
                   1548:     }
                   1549:     return ($currbalancer,$currtargets);
                   1550: }
                   1551: 
                   1552: sub check_loadbalancing {
1.1331    raeburn  1553:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1554:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1555:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1556:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1557:     my @hosts = &current_machine_ids();
1.1129    raeburn  1558:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1559:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1560:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1561:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1562:     my $domneedscache;
1.1129    raeburn  1563:     my $cachetime = 60*60*24;
                   1564: 
                   1565:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1566:         $dom_in_use = $udom;
                   1567:         $homeintdom = 1;
                   1568:     } else {
                   1569:         $dom_in_use = $serverhomedom;
                   1570:     }
                   1571:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1572:     unless (defined($cached)) {
                   1573:         my %domconfig =
                   1574:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1575:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1576:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1577:         } else {
                   1578:             $domneedscache = $dom_in_use;
1.1129    raeburn  1579:         }
                   1580:     }
                   1581:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1582:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1583:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1584:         if ($is_balancer) {
                   1585:             if (ref($currrules) eq 'HASH') {
                   1586:                 if ($homeintdom) {
                   1587:                     if ($uname ne '') {
                   1588:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1589:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1590:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1591:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1592:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1593:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1594:                             }
                   1595:                         }
                   1596:                         if ($rule_in_effect eq '') {
                   1597:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1598:                             if ($userenv{'inststatus'} ne '') {
                   1599:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1600:                                 my ($othertitle,$usertypes,$types) =
                   1601:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1602:                                 if (ref($types) eq 'ARRAY') {
                   1603:                                     foreach my $type (@{$types}) {
                   1604:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1605:                                             if (exists($currrules->{$type})) {
                   1606:                                                 $rule_in_effect = $currrules->{$type};
                   1607:                                             }
                   1608:                                         }
                   1609:                                     }
                   1610:                                 }
                   1611:                             } else {
                   1612:                                 if (exists($currrules->{'default'})) {
                   1613:                                     $rule_in_effect = $currrules->{'default'};
                   1614:                                 }
                   1615:                             }
                   1616:                         }
                   1617:                     } else {
                   1618:                         if (exists($currrules->{'default'})) {
                   1619:                             $rule_in_effect = $currrules->{'default'};
                   1620:                         }
                   1621:                     }
                   1622:                 } else {
                   1623:                     if ($currrules->{'_LC_external'} ne '') {
                   1624:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1625:                     }
                   1626:                 }
                   1627:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1628:                                                        $uname,$udom);
                   1629:             }
                   1630:         }
                   1631:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1632:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1633:         unless (defined($cached)) {
                   1634:             my %domconfig =
                   1635:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1636:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1637:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1638:             } else {
                   1639:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1640:             }
                   1641:         }
                   1642:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1643:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1644:                 &check_balancer_result($result,@hosts);
                   1645:             if ($is_balancer) {
1.1129    raeburn  1646:                 if (ref($currrules) eq 'HASH') {
                   1647:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1648:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1649:                     }
                   1650:                 }
                   1651:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1652:                                                        $uname,$udom);
                   1653:             }
                   1654:         } else {
                   1655:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1656:                 $is_balancer = 1;
                   1657:                 $offloadto = &this_host_spares($dom_in_use);
                   1658:             }
1.1307    raeburn  1659:             unless (defined($cached)) {
                   1660:                 $domneedscache = $serverhomedom;
                   1661:             }
1.1129    raeburn  1662:         }
                   1663:     } else {
                   1664:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1665:             $is_balancer = 1;
                   1666:             $offloadto = &this_host_spares($dom_in_use);
                   1667:         }
1.1307    raeburn  1668:         unless (defined($cached)) {
                   1669:             $domneedscache = $serverhomedom;
                   1670:         }
                   1671:     }
                   1672:     if ($domneedscache) {
                   1673:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1674:     }
1.1430    raeburn  1675:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176    raeburn  1676:         my $lowest_load = 30000;
                   1677:         if (ref($offloadto) eq 'HASH') {
                   1678:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1679:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1680:                     ($otherserver,$lowest_load) =
                   1681:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1682:                 }
1.1129    raeburn  1683:             }
1.1176    raeburn  1684:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1685: 
1.1176    raeburn  1686:             if (!$found_server) {
                   1687:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1688:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1689:                         ($otherserver,$lowest_load) =
                   1690:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1691:                     }
                   1692:                 }
                   1693:             }
                   1694:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1695:             if (@{$offloadto} == 1) {
                   1696:                 $otherserver = $offloadto->[0];
                   1697:             } elsif (@{$offloadto} > 1) {
                   1698:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1699:                     ($otherserver,$lowest_load) =
                   1700:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1701:                 }
                   1702:             }
                   1703:         }
1.1331    raeburn  1704:         unless ($caller eq 'login') {
                   1705:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1706:                 $is_balancer = 0;
                   1707:                 if ($uname ne '' && $udom ne '') {
                   1708:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1709:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1710:                                  'user.loadbalcheck.time' => time});
                   1711:                     }
1.1176    raeburn  1712:                 }
1.1129    raeburn  1713:             }
                   1714:         }
1.1430    raeburn  1715:     }
                   1716:     if (($is_balancer) && (!$homeintdom)) {
                   1717:         undef($setcookie);
1.1129    raeburn  1718:     }
1.1391    raeburn  1719:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1720: }
                   1721: 
1.1191    raeburn  1722: sub check_balancer_result {
                   1723:     my ($result,@hosts) = @_;
1.1391    raeburn  1724:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1725:     if (ref($result) eq 'HASH') {
                   1726:         if ($result->{'lonhost'} ne '') {
                   1727:             my $currbalancer = $result->{'lonhost'};
                   1728:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1729:                 $is_balancer = 1;
                   1730:                 $currtargets = $result->{'targets'};
                   1731:                 $currrules = $result->{'rules'};
                   1732:             }
1.1391    raeburn  1733:             $dom_balancers = $currbalancer;
1.1191    raeburn  1734:         } else {
1.1391    raeburn  1735:             if (keys(%{$result})) {
                   1736:                 foreach my $key (keys(%{$result})) {
                   1737:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1738:                         (ref($result->{$key}) eq 'HASH')) {
                   1739:                         $is_balancer = 1;
                   1740:                         $currrules = $result->{$key}{'rules'};
                   1741:                         $currtargets = $result->{$key}{'targets'};
                   1742:                         $setcookie = $result->{$key}{'cookie'};
                   1743:                         last;
                   1744:                     }
1.1191    raeburn  1745:                 }
1.1391    raeburn  1746:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1747:             }
                   1748:         }
                   1749:     }
1.1391    raeburn  1750:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1751: }
                   1752: 
1.1129    raeburn  1753: sub get_loadbalancer_targets {
                   1754:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1755:     my $offloadto;
1.1175    raeburn  1756:     if ($rule_in_effect eq 'none') {
                   1757:         return [$perlvar{'lonHostID'}];
                   1758:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1759:         $offloadto = $currtargets;
                   1760:     } else {
                   1761:         if ($rule_in_effect eq 'homeserver') {
                   1762:             my $homeserver = &homeserver($uname,$udom);
                   1763:             if ($homeserver ne 'no_host') {
                   1764:                 $offloadto = [$homeserver];
                   1765:             }
                   1766:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1767:             my %domconfig =
                   1768:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1769:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1770:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1771:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1772:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1773:                     }
                   1774:                 }
                   1775:             } else {
1.1178    raeburn  1776:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1777:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1778:                 if (&hostname($remotebalancer) ne '') {
                   1779:                     $offloadto = [$remotebalancer];
                   1780:                 }
                   1781:             }
                   1782:         } elsif (&hostname($rule_in_effect) ne '') {
                   1783:             $offloadto = [$rule_in_effect];
                   1784:         }
                   1785:     }
                   1786:     return $offloadto;
                   1787: }
                   1788: 
1.1127    raeburn  1789: sub internet_dom_servers {
                   1790:     my ($dom) = @_;
                   1791:     my (%uniqservers,%servers);
                   1792:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1793:     my @machinedoms = &machine_domains($primaryserver);
                   1794:     foreach my $mdom (@machinedoms) {
                   1795:         my %currservers = %servers;
                   1796:         my %server = &get_servers($mdom);
                   1797:         %servers = (%currservers,%server);
                   1798:     }
                   1799:     my %by_hostname;
                   1800:     foreach my $id (keys(%servers)) {
                   1801:         push(@{$by_hostname{$servers{$id}}},$id);
                   1802:     }
                   1803:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1804:         if (@{$by_hostname{$hostname}} > 1) {
                   1805:             my $match = 0;
                   1806:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1807:                 if (&host_domain($id) eq $dom) {
                   1808:                     $uniqservers{$id} = $hostname;
                   1809:                     $match = 1;
                   1810:                 }
                   1811:             }
                   1812:             unless ($match) {
                   1813:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1814:             }
                   1815:         } else {
                   1816:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1817:         }
                   1818:     }
                   1819:     return %uniqservers;
                   1820: }
                   1821: 
1.1347    raeburn  1822: sub trusted_domains {
                   1823:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1824:     my ($trusted,$untrusted);
1.1347    raeburn  1825:     if (&domain($calldom) eq '') {
1.1349    raeburn  1826:         return ($trusted,$untrusted);
1.1347    raeburn  1827:     }
1.1395    raeburn  1828:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1829:         return ($trusted,$untrusted);
1.1347    raeburn  1830:     }
                   1831:     my $callprimary = &domain($calldom,'primary');
                   1832:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1833:     if ($intcalldom eq '') {
1.1349    raeburn  1834:         return ($trusted,$untrusted);
1.1347    raeburn  1835:     }
                   1836: 
                   1837:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1838:     unless (defined($cached)) {
                   1839:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1840:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1841:         $trustconfig = $domconfig{'trust'};
                   1842:     }
                   1843:     if (ref($trustconfig)) {
                   1844:         my (%possexc,%possinc,@allexc,@allinc); 
                   1845:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1846:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1847:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1848:             }
                   1849:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1850:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1851:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1852:             }
                   1853:         }
                   1854:         if (keys(%possexc)) {
                   1855:             if (keys(%possinc)) {
                   1856:                 foreach my $key (sort(keys(%possexc))) {
                   1857:                     next if ($key eq $intcalldom);
                   1858:                     unless ($possinc{$key}) {
                   1859:                         push(@allexc,$key);
                   1860:                     }
                   1861:                 }
                   1862:             } else {
                   1863:                 @allexc = sort(keys(%possexc));
                   1864:             }
                   1865:         }
                   1866:         if (keys(%possinc)) {
                   1867:             $possinc{$intcalldom} = 1;
                   1868:             @allinc = sort(keys(%possinc));
                   1869:         }
                   1870:         if ((@allexc > 0) || (@allinc > 0)) {
                   1871:             my %doms_by_intdom;
                   1872:             my %allintdoms = &all_host_intdom();
                   1873:             my %alldoms = &all_host_domain();
                   1874:             foreach my $key (%allintdoms) {
                   1875:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1876:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1877:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1878:                     }
                   1879:                 } else {
                   1880:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1881:                 }
                   1882:             }
                   1883:             foreach my $exc (@allexc) {
                   1884:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1885:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1886:                 }
                   1887:             }
                   1888:             foreach my $inc (@allinc) {
                   1889:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1890:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1891:                 }
                   1892:             }
                   1893:         }
                   1894:     }
1.1349    raeburn  1895:     return ($trusted,$untrusted);
1.1347    raeburn  1896: }
                   1897: 
                   1898: sub will_trust {
                   1899:     my ($cmdtype,$domain,$possdom) = @_;
                   1900:     return 1 if ($domain eq $possdom);
                   1901:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1902:     my $willtrust; 
                   1903:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1904:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1905:             $willtrust = 1;
                   1906:         }
                   1907:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1908:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1909:             $willtrust = 1;
                   1910:         }
                   1911:     } else {
                   1912:         $willtrust = 1;
                   1913:     }
                   1914:     return $willtrust;
                   1915: }
                   1916: 
1.1       albertel 1917: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1918: 
1.599     albertel 1919: my %homecache;
1.1       albertel 1920: sub homeserver {
1.230     stredwic 1921:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1922:     my $index="$uname:$udom";
1.426     albertel 1923: 
1.599     albertel 1924:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1925: 
                   1926:     my %servers = &get_servers($udom,'library');
                   1927:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1928:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1929: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1930: 
                   1931: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1932: 	if ($answer eq 'found') {
                   1933: 	    delete($badServerCache{$tryserver}); 
                   1934: 	    return $homecache{$index}=$tryserver;
                   1935: 	} elsif ($answer eq 'no_host') {
                   1936: 	    $badServerCache{$tryserver}=1;
                   1937: 	}
1.1       albertel 1938:     }    
                   1939:     return 'no_host';
1.70      www      1940: }
                   1941: 
1.1300    raeburn  1942: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1943: 
                   1944: sub idget {
1.1300    raeburn  1945:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1946:     my %returnhash=();
1.1300    raeburn  1947:     my @ids=(); 
                   1948:     if (ref($idsref) eq 'ARRAY') {
                   1949:         @ids = @{$idsref};
                   1950:     } else {
                   1951:         return %returnhash; 
                   1952:     }
                   1953:     if ($namespace eq '') {
                   1954:         $namespace = 'ids';
                   1955:     }
1.70      www      1956:     
1.841     albertel 1957:     my %servers = &get_servers($udom,'library');
                   1958:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1959: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1960: 	if ($namespace eq 'ids') {
                   1961: 	    $idlist=~tr/A-Z/a-z/;
                   1962: 	}
                   1963: 	my $reply;
                   1964: 	if ($namespace eq 'ids') {
                   1965: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1966: 	} else {
                   1967: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1968: 	}
1.841     albertel 1969: 	my @answer=();
                   1970: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1971: 	    @answer=split(/\&/,$reply);
                   1972: 	}                    ;
                   1973: 	my $i;
                   1974: 	for ($i=0;$i<=$#ids;$i++) {
                   1975: 	    if ($answer[$i]) {
1.1299    raeburn  1976: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1977: 	    }
1.841     albertel 1978: 	}
1.1300    raeburn  1979:     }
1.70      www      1980:     return %returnhash;
                   1981: }
                   1982: 
                   1983: # ------------------------------------- Find the IDs behind a list of usernames
                   1984: 
                   1985: sub idrget {
                   1986:     my ($udom,@unames)=@_;
                   1987:     my %returnhash=();
1.800     albertel 1988:     foreach my $uname (@unames) {
                   1989:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1990:     }
1.70      www      1991:     return %returnhash;
                   1992: }
                   1993: 
1.1300    raeburn  1994: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1995: 
                   1996: sub idput {
1.1300    raeburn  1997:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1998:     my %servers=();
1.1300    raeburn  1999:     my %ids=();
                   2000:     my %byid = ();
                   2001:     if (ref($idsref) eq 'HASH') {
                   2002:         %ids=%{$idsref};
                   2003:     }
                   2004:     if ($namespace eq '') {
                   2005:         $namespace = 'ids'; 
                   2006:     }
1.800     albertel 2007:     foreach my $uname (keys(%ids)) {
                   2008: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  2009:         if ($uhom eq '') {
                   2010:             $uhom=&homeserver($uname,$udom);
                   2011:         }
1.70      www      2012:         if ($uhom ne 'no_host') {
1.800     albertel 2013:             my $esc_unam=&escape($uname);
1.1300    raeburn  2014:             if ($namespace eq 'ids') {
                   2015:                 my $id=&escape($ids{$uname});
                   2016:                 $id=~tr/A-Z/a-z/;
                   2017:                 my $esc_unam=&escape($uname);
                   2018:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      2019:             } else {
1.1300    raeburn  2020:                 my @currids = split(/,/,$ids{$uname});
                   2021:                 foreach my $id (@currids) {
                   2022:                     $byid{$uhom}{$id} .= $uname.',';
                   2023:                 }
                   2024:             }
                   2025:         }
                   2026:     }
                   2027:     if ($namespace eq 'clickers') {
                   2028:         foreach my $server (keys(%byid)) {
                   2029:             if (ref($byid{$server}) eq 'HASH') {
                   2030:                 foreach my $id (keys(%{$byid{$server}})) {
                   2031:                     $byid{$server} =~ s/,$//;
                   2032:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   2033:                 }
1.70      www      2034:             }
                   2035:         }
1.191     harris41 2036:     }
1.800     albertel 2037:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2038:         $servers{$server} =~ s/\&$//;
                   2039:         if ($namespace eq 'ids') {     
                   2040:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   2041:         } else {
                   2042:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   2043:         }
1.191     harris41 2044:     }
1.344     www      2045: }
                   2046: 
1.1300    raeburn  2047: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2048: 
                   2049: sub iddel {
1.1300    raeburn  2050:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2051:     my %result=();
1.1300    raeburn  2052:     my %ids=();
                   2053:     my %byid = ();
                   2054:     if (ref($idshashref) eq 'HASH') {
                   2055:         %ids=%{$idshashref};
                   2056:     } else {
1.1231    raeburn  2057:         return %result;
                   2058:     }
1.1300    raeburn  2059:     if ($namespace eq '') {
                   2060:         $namespace = 'ids';
                   2061:     }
1.1231    raeburn  2062:     my %servers=();
1.1300    raeburn  2063:     while (my ($id,$unamestr) = each(%ids)) {
                   2064:         if ($namespace eq 'ids') {
                   2065:             my $uhom = $uhome;
                   2066:             if ($uhom eq '') { 
                   2067:                 $uhom=&homeserver($unamestr,$udom);
                   2068:             }
                   2069:             if ($uhom ne 'no_host') {
                   2070:                 $servers{$uhom}.='&'.&escape($id);
                   2071:             }
                   2072:          } else {
                   2073:             my @curritems = split(/,/,$ids{$id});
                   2074:             foreach my $uname (@curritems) {
                   2075:                 my $uhom = $uhome;
                   2076:                 if ($uhom eq '') {
                   2077:                     $uhom=&homeserver($uname,$udom);
                   2078:                 }
                   2079:                 if ($uhom ne 'no_host') { 
                   2080:                     $byid{$uhom}{$id} .= $uname.',';
                   2081:                 }
                   2082:             }
1.1231    raeburn  2083:         }
1.1300    raeburn  2084:     }
                   2085:     if ($namespace eq 'clickers') {
                   2086:         foreach my $server (keys(%byid)) {
                   2087:             if (ref($byid{$server}) eq 'HASH') {
                   2088:                 foreach my $id (keys(%{$byid{$server}})) {
                   2089:                     $byid{$server}{$id} =~ s/,$//;
                   2090:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2091:                 }
1.1231    raeburn  2092:             }
                   2093:         }
                   2094:     }
                   2095:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2096:         $servers{$server} =~ s/\&$//;
                   2097:         if ($namespace eq 'ids') {
                   2098:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2099:         } elsif ($namespace eq 'clickers') {
                   2100:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2101:         }
1.1231    raeburn  2102:     }
                   2103:     return %result;
                   2104: }
                   2105: 
1.1300    raeburn  2106: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2107: 
                   2108: sub updateclickers {
                   2109:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2110:     my %clickers;
                   2111:     if (ref($idshashref) eq 'HASH') {
                   2112:         %clickers=%{$idshashref};
                   2113:     } else {
                   2114:         return;
                   2115:     }
                   2116:     my $items='';
                   2117:     foreach my $item (keys(%clickers)) {
                   2118:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2119:     }
                   2120:     $items=~s/\&$//;
                   2121:     my $request = "updateclickers:$udom:$action:$items";
                   2122:     if ($critical) {
                   2123:         return &critical($request,$uhome);
                   2124:     } else {
                   2125:         return &reply($request,$uhome);
                   2126:     }
                   2127: }
                   2128: 
1.1023    raeburn  2129: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2130: sub dump_dom {
1.1165    droeschl 2131:     my ($namespace, $udom, $regexp) = @_;
                   2132: 
                   2133:     $udom ||= $env{'user.domain'};
                   2134: 
                   2135:     return () unless $udom;
                   2136: 
                   2137:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2138: }
                   2139: 
1.1023    raeburn  2140: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2141: 
                   2142: sub get_dom {
1.860     raeburn  2143:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2144:     return if ($udom eq 'public');
1.806     raeburn  2145:     my $items='';
                   2146:     foreach my $item (@$storearr) {
                   2147:         $items.=&escape($item).'&';
                   2148:     }
                   2149:     $items=~s/\&$//;
1.860     raeburn  2150:     if (!$udom) {
                   2151:         $udom=$env{'user.domain'};
1.1267    raeburn  2152:         return if ($udom eq 'public');
1.860     raeburn  2153:         if (defined(&domain($udom,'primary'))) {
                   2154:             $uhome=&domain($udom,'primary');
                   2155:         } else {
1.874     albertel 2156:             undef($uhome);
1.860     raeburn  2157:         }
                   2158:     } else {
                   2159:         if (!$uhome) {
                   2160:             if (defined(&domain($udom,'primary'))) {
                   2161:                 $uhome=&domain($udom,'primary');
                   2162:             }
                   2163:         }
                   2164:     }
                   2165:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2166:         my $rep;
1.1442    raeburn  2167:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2168:             # domain information is hosted on this machine
                   2169:             my $cmd = 'getdom';
                   2170:             if ($namespace =~ /^enc/) {
                   2171:                 $cmd = 'egetdom';
                   2172:             }
                   2173:             $rep = &LONCAPA::Lond::get_dom("$cmd:$udom:$namespace:$items");
1.1344    raeburn  2174:         } else {
1.1442    raeburn  2175:             if ($namespace =~ /^enc/) {
                   2176:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2177:             } else {
                   2178:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2179:             }
1.1344    raeburn  2180:         }
1.866     raeburn  2181:         my %returnhash;
1.875     albertel 2182:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2183:             return %returnhash;
                   2184:         }
1.806     raeburn  2185:         my @pairs=split(/\&/,$rep);
                   2186:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2187:             return @pairs;
                   2188:         }
                   2189:         my $i=0;
                   2190:         foreach my $item (@$storearr) {
                   2191:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2192:             $i++;
                   2193:         }
                   2194:         return %returnhash;
                   2195:     } else {
1.880     banghart 2196:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2197:     }
                   2198: }
                   2199: 
                   2200: # -------------------------------------------- put items in domain db files 
                   2201: 
                   2202: sub put_dom {
1.860     raeburn  2203:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2204:     if (!$udom) {
                   2205:         $udom=$env{'user.domain'};
                   2206:         if (defined(&domain($udom,'primary'))) {
                   2207:             $uhome=&domain($udom,'primary');
                   2208:         } else {
1.874     albertel 2209:             undef($uhome);
1.860     raeburn  2210:         }
                   2211:     } else {
                   2212:         if (!$uhome) {
                   2213:             if (defined(&domain($udom,'primary'))) {
                   2214:                 $uhome=&domain($udom,'primary');
                   2215:             }
                   2216:         }
                   2217:     } 
                   2218:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2219:         my $items='';
                   2220:         foreach my $item (keys(%$storehash)) {
                   2221:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2222:         }
                   2223:         $items=~s/\&$//;
1.1344    raeburn  2224:         if ($namespace =~ /^enc/) {
                   2225:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2226:         } else {
                   2227:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2228:         }
1.806     raeburn  2229:     } else {
1.860     raeburn  2230:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2231:     }
                   2232: }
                   2233: 
1.1023    raeburn  2234: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2235: sub newput_dom {
1.1023    raeburn  2236:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2237:     my $result;
                   2238:     if (!$udom) {
                   2239:         $udom=$env{'user.domain'};
                   2240:     }
1.1023    raeburn  2241:     if ($udom) {
                   2242:         my $uname = &get_domainconfiguser($udom);
                   2243:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2244:     }
                   2245:     return $result;
                   2246: }
                   2247: 
1.1023    raeburn  2248: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2249: sub del_dom {
1.1023    raeburn  2250:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2251:     if (ref($storearr) eq 'ARRAY') {
                   2252:         if (!$udom) {
                   2253:             $udom=$env{'user.domain'};
                   2254:         }
1.1023    raeburn  2255:         if ($udom) {
                   2256:             my $uname = &get_domainconfiguser($udom); 
                   2257:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2258:         }
                   2259:     }
                   2260: }
                   2261: 
1.1023    raeburn  2262: # ----------------------------------construct domainconfig user for a domain 
                   2263: sub get_domainconfiguser {
                   2264:     my ($udom) = @_;
                   2265:     return $udom.'-domainconfig';
                   2266: }
                   2267: 
1.837     raeburn  2268: sub retrieve_inst_usertypes {
                   2269:     my ($udom) = @_;
                   2270:     my (%returnhash,@order);
1.989     raeburn  2271:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2272:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2273:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2274:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2275:     } else {
                   2276:         if (defined(&domain($udom,'primary'))) {
                   2277:             my $uhome=&domain($udom,'primary');
                   2278:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2279:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2280:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2281:                 return (\%returnhash,\@order);
                   2282:             }
                   2283:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2284:             my @pairs=split(/\&/,$hashitems);
                   2285:             foreach my $item (@pairs) {
                   2286:                 my ($key,$value)=split(/=/,$item,2);
                   2287:                 $key = &unescape($key);
                   2288:                 next if ($key =~ /^error: 2 /);
                   2289:                 $returnhash{$key}=&thaw_unescape($value);
                   2290:             }
                   2291:             my @esc_order = split(/\&/,$orderitems);
                   2292:             foreach my $item (@esc_order) {
                   2293:                 push(@order,&unescape($item));
                   2294:             }
                   2295:         } else {
1.1256    raeburn  2296:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2297:         }
1.1256    raeburn  2298:         return (\%returnhash,\@order);
1.837     raeburn  2299:     }
                   2300: }
                   2301: 
1.868     raeburn  2302: sub is_domainimage {
                   2303:     my ($url) = @_;
1.1306    raeburn  2304:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2305:         if (&domain($1) ne '') {
                   2306:             return '1';
                   2307:         }
                   2308:     }
                   2309:     return;
                   2310: }
                   2311: 
1.899     raeburn  2312: sub inst_directory_query {
                   2313:     my ($srch) = @_;
                   2314:     my $udom = $srch->{'srchdomain'};
                   2315:     my %results;
                   2316:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2317:     my $outcome;
1.899     raeburn  2318:     if ($homeserver ne '') {
1.1357    raeburn  2319:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2320:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2321:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2322:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2323:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2324:                     (($major == 2) && ($minor < 12))) {
                   2325:                     return;
                   2326:                 }
                   2327:             }
                   2328:         }
1.904     albertel 2329: 	my $queryid=&reply("querysend:instdirsearch:".
                   2330: 			   &escape($srch->{'srchby'}).':'.
                   2331: 			   &escape($srch->{'srchterm'}).':'.
                   2332: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2333: 	my $host=&hostname($homeserver);
                   2334: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2335: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2336: 	    return;
                   2337: 	}
                   2338: 	my $response = &get_query_reply($queryid);
                   2339: 	my $maxtries = 5;
                   2340: 	my $tries = 1;
                   2341: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2342: 	    $response = &get_query_reply($queryid);
                   2343: 	    $tries ++;
                   2344: 	}
                   2345: 
                   2346:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2347:             if ($response eq 'unavailable') {
                   2348:                 $outcome = $response;
                   2349:             } else {
                   2350:                 $outcome = 'ok';
                   2351:                 my @matches = split(/\n/,$response);
                   2352:                 foreach my $match (@matches) {
                   2353:                     my ($key,$value) = split(/=/,$match);
                   2354:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2355:                 }
1.899     raeburn  2356:             }
                   2357:         }
                   2358:     }
1.909     raeburn  2359:     return ($outcome,%results);
1.899     raeburn  2360: }
                   2361: 
                   2362: sub usersearch {
                   2363:     my ($srch) = @_;
                   2364:     my $dom = $srch->{'srchdomain'};
                   2365:     my %results;
                   2366:     my %libserv = &all_library();
                   2367:     my $query = 'usersearch';
                   2368:     foreach my $tryserver (keys(%libserv)) {
                   2369:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2370:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2371:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2372:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2373:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2374:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2375:                              (($major == 2) && ($minor < 12)));
                   2376:                 }
                   2377:             }
1.899     raeburn  2378:             my $host=&hostname($tryserver);
                   2379:             my $queryid=
1.911     raeburn  2380:                 &reply("querysend:".&escape($query).':'.
                   2381:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2382:                        &escape($srch->{'srchtype'}).':'.
                   2383:                        &escape($srch->{'srchterm'}),$tryserver);
                   2384:             if ($queryid !~/^\Q$host\E\_/) {
                   2385:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2386:                 next;
1.899     raeburn  2387:             }
                   2388:             my $reply = &get_query_reply($queryid);
                   2389:             my $maxtries = 1;
                   2390:             my $tries = 1;
                   2391:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2392:                 $reply = &get_query_reply($queryid);
                   2393:                 $tries ++;
                   2394:             }
                   2395:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2396:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2397:             } else {
1.911     raeburn  2398:                 my @matches;
                   2399:                 if ($reply =~ /\n/) {
                   2400:                     @matches = split(/\n/,$reply);
                   2401:                 } else {
                   2402:                     @matches = split(/\&/,$reply);
                   2403:                 }
1.899     raeburn  2404:                 foreach my $match (@matches) {
                   2405:                     my ($uname,$udom,%userhash);
1.911     raeburn  2406:                     foreach my $entry (split(/:/,$match)) {
                   2407:                         my ($key,$value) =
                   2408:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2409:                         $userhash{$key} = $value;
                   2410:                         if ($key eq 'username') {
                   2411:                             $uname = $value;
                   2412:                         } elsif ($key eq 'domain') {
                   2413:                             $udom = $value;
1.911     raeburn  2414:                         }
1.899     raeburn  2415:                     }
                   2416:                     $results{$uname.':'.$udom} = \%userhash;
                   2417:                 }
                   2418:             }
                   2419:         }
                   2420:     }
                   2421:     return %results;
                   2422: }
                   2423: 
1.912     raeburn  2424: sub get_instuser {
                   2425:     my ($udom,$uname,$id) = @_;
                   2426:     my $homeserver = &domain($udom,'primary');
                   2427:     my ($outcome,%results);
                   2428:     if ($homeserver ne '') {
                   2429:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2430:                            &escape($id).':'.&escape($udom),$homeserver);
                   2431:         my $host=&hostname($homeserver);
                   2432:         if ($queryid !~/^\Q$host\E\_/) {
                   2433:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2434:             return;
                   2435:         }
                   2436:         my $response = &get_query_reply($queryid);
                   2437:         my $maxtries = 5;
                   2438:         my $tries = 1;
                   2439:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2440:             $response = &get_query_reply($queryid);
                   2441:             $tries ++;
                   2442:         }
                   2443:         if (!&error($response) && $response ne 'refused') {
                   2444:             if ($response eq 'unavailable') {
                   2445:                 $outcome = $response;
                   2446:             } else {
                   2447:                 $outcome = 'ok';
                   2448:                 my @matches = split(/\n/,$response);
                   2449:                 foreach my $match (@matches) {
                   2450:                     my ($key,$value) = split(/=/,$match);
                   2451:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2452:                 }
                   2453:             }
                   2454:         }
                   2455:     }
                   2456:     my %userinfo;
                   2457:     if (ref($results{$uname}) eq 'HASH') {
                   2458:         %userinfo = %{$results{$uname}};
                   2459:     } 
                   2460:     return ($outcome,%userinfo);
                   2461: }
                   2462: 
1.1290    raeburn  2463: sub get_multiple_instusers {
                   2464:     my ($udom,$users,$caller) = @_;
                   2465:     my ($outcome,$results);
                   2466:     if (ref($users) eq 'HASH') {
                   2467:         my $count = keys(%{$users}); 
                   2468:         my $requested = &freeze_escape($users);
                   2469:         my $homeserver = &domain($udom,'primary');
                   2470:         if ($homeserver ne '') {
                   2471:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2472:             my $host=&hostname($homeserver);
                   2473:             if ($queryid !~/^\Q$host\E\_/) {
                   2474:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2475:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2476:                 return ($outcome,$results);
                   2477:             }
                   2478:             my $response = &get_query_reply($queryid);
                   2479:             my $maxtries = 5;
                   2480:             if ($count > 100) {
                   2481:                 $maxtries = 1+int($count/20);
                   2482:             }
                   2483:             my $tries = 1;
                   2484:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2485:                 $response = &get_query_reply($queryid);
                   2486:                 $tries ++;
                   2487:             }
                   2488:             if ($response eq '') {
                   2489:                 $results = {};
                   2490:                 foreach my $key (keys(%{$users})) {
                   2491:                     my ($uname,$id);
                   2492:                     if ($caller eq 'id') {
                   2493:                         $id = $key;
                   2494:                     } else {
                   2495:                         $uname = $key;
                   2496:                     }
                   2497:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2498:                     $outcome = $resp;
1.1290    raeburn  2499:                     if ($resp eq 'ok') {
                   2500:                         %{$results} = (%{$results}, %info);
                   2501:                     } else {
                   2502:                         last;
                   2503:                     }
                   2504:                 }
                   2505:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2506:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2507:                     $outcome = $response;
                   2508:                 } else {
1.1291    raeburn  2509:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2510:                     if ($outcome eq 'ok') {
                   2511:                         $results = &thaw_unescape($userdata); 
                   2512:                     }
                   2513:                 }
                   2514:             }
                   2515:         }
                   2516:     }
                   2517:     return ($outcome,$results);
                   2518: }
                   2519: 
1.912     raeburn  2520: sub inst_rulecheck {
1.923     raeburn  2521:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2522:     my %returnhash;
                   2523:     if ($udom ne '') {
                   2524:         if (ref($rules) eq 'ARRAY') {
                   2525:             @{$rules} = map {&escape($_);} (@{$rules});
                   2526:             my $rulestr = join(':',@{$rules});
                   2527:             my $homeserver=&domain($udom,'primary');
                   2528:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2529:                 my $response;
                   2530:                 if ($item eq 'username') {                
                   2531:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2532:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2533:                                               $homeserver));
1.923     raeburn  2534:                 } elsif ($item eq 'id') {
                   2535:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2536:                                               ':'.&escape($id).':'.$rulestr,
                   2537:                                               $homeserver));
1.945     raeburn  2538:                 } elsif ($item eq 'selfcreate') {
                   2539:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2540:                                                &escape($udom).':'.&escape($uname).
                   2541:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2542:                 }
1.912     raeburn  2543:                 if ($response ne 'refused') {
                   2544:                     my @pairs=split(/\&/,$response);
                   2545:                     foreach my $item (@pairs) {
                   2546:                         my ($key,$value)=split(/=/,$item,2);
                   2547:                         $key = &unescape($key);
                   2548:                         next if ($key =~ /^error: 2 /);
                   2549:                         $returnhash{$key}=&thaw_unescape($value);
                   2550:                     }
                   2551:                 }
                   2552:             }
                   2553:         }
                   2554:     }
                   2555:     return %returnhash;
                   2556: }
                   2557: 
                   2558: sub inst_userrules {
1.923     raeburn  2559:     my ($udom,$check) = @_;
1.912     raeburn  2560:     my (%ruleshash,@ruleorder);
                   2561:     if ($udom ne '') {
                   2562:         my $homeserver=&domain($udom,'primary');
                   2563:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2564:             my $response;
                   2565:             if ($check eq 'id') {
                   2566:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2567:                                  $homeserver);
1.943     raeburn  2568:             } elsif ($check eq 'email') {
                   2569:                 $response=&reply('instemailrules:'.&escape($udom),
                   2570:                                  $homeserver);
1.923     raeburn  2571:             } else {
                   2572:                 $response=&reply('instuserrules:'.&escape($udom),
                   2573:                                  $homeserver);
                   2574:             }
1.912     raeburn  2575:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2576:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2577:                 ($response ne 'no_such_host')) {
                   2578:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2579:                 my @pairs=split(/\&/,$hashitems);
                   2580:                 foreach my $item (@pairs) {
                   2581:                     my ($key,$value)=split(/=/,$item,2);
                   2582:                     $key = &unescape($key);
                   2583:                     next if ($key =~ /^error: 2 /);
                   2584:                     $ruleshash{$key}=&thaw_unescape($value);
                   2585:                 }
                   2586:                 my @esc_order = split(/\&/,$orderitems);
                   2587:                 foreach my $item (@esc_order) {
                   2588:                     push(@ruleorder,&unescape($item));
                   2589:                 }
                   2590:             }
                   2591:         }
                   2592:     }
                   2593:     return (\%ruleshash,\@ruleorder);
                   2594: }
                   2595: 
1.976     raeburn  2596: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2597: 
                   2598: sub get_domain_defaults {
1.1240    raeburn  2599:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2600:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2601:     my $cachetime = 60*60*24;
1.1240    raeburn  2602:     unless ($ignore_cache) {
                   2603:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2604:         if (defined($cached)) {
                   2605:             if (ref($result) eq 'HASH') {
                   2606:                 return %{$result};
                   2607:             }
1.943     raeburn  2608:         }
                   2609:     }
                   2610:     my %domdefaults;
                   2611:     my %domconfig =
1.989     raeburn  2612:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2613:                                   'requestcourses','inststatus',
1.1183    raeburn  2614:                                   'coursedefaults','usersessions',
1.1258    raeburn  2615:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2616:                                   'coursecategories','ssl','autoenroll',
1.1434    raeburn  2617:                                   'trust','helpsettings','wafproxy'],$domain);
1.1305    raeburn  2618:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2619:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2620:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2621:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2622:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2623:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2624:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2625:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2626:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2627:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2628:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2629:     } else {
                   2630:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2631:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2632:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2633:     }
1.976     raeburn  2634:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2635:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2636:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2637:         } else {
                   2638:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2639:         }
1.1177    raeburn  2640:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2641:         foreach my $item (@usertools) {
                   2642:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2643:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2644:             }
                   2645:         }
1.1229    raeburn  2646:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2647:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2648:         }
1.976     raeburn  2649:     }
1.985     raeburn  2650:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2651:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2652:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2653:         }
                   2654:     }
1.1183    raeburn  2655:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2656:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2657:     }
1.989     raeburn  2658:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2659:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2660:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2661:         }
                   2662:     }
1.1047    raeburn  2663:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2664:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2665:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2666:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2667:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2668:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2669:         }
1.1254    raeburn  2670:         foreach my $type (@coursetypes) {
                   2671:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2672:                 unless ($type eq 'community') {
                   2673:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2674:                 }
                   2675:             }
                   2676:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2677:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2678:             }
1.1277    raeburn  2679:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2680:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2681:                     $domdefaults{$type.'postsubtimeout'} = 
                   2682:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2683:                 }
                   2684:             }
1.1230    raeburn  2685:         }
1.1286    raeburn  2686:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2687:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2688:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2689:                 if (@clonecodes) {
                   2690:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2691:                 }
                   2692:             }
                   2693:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2694:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2695:         }
1.1356    raeburn  2696:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2697:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2698:         } 
1.1047    raeburn  2699:     }
1.1073    raeburn  2700:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2701:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2702:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2703:         }
                   2704:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2705:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2706:         }
1.1279    raeburn  2707:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2708:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2709:         }
1.1440    raeburn  2710:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439    raeburn  2711:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2712:         }
1.1073    raeburn  2713:     }
1.1254    raeburn  2714:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2715:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2716:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2717:                             'approval','limit');
                   2718:             foreach my $type (@coursetypes) {
                   2719:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2720:                     my @mgrdc = ();
                   2721:                     foreach my $item (@settings) {
                   2722:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2723:                             push(@mgrdc,$item);
                   2724:                         }
                   2725:                     }
                   2726:                     if (@mgrdc) {
                   2727:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2728:                     }
                   2729:                 }
                   2730:             }
                   2731:         }
                   2732:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2733:             foreach my $type (@coursetypes) {
                   2734:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2735:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2736:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2737:                     }
                   2738:                 }
                   2739:             }
                   2740:         }
                   2741:     }
1.1258    raeburn  2742:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2743:         $domdefaults{'catauth'} = 'std';
                   2744:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2745:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2746:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2747:         }
                   2748:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2749:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2750:         }
                   2751:     }
1.1315    raeburn  2752:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2753:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2754:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2755:         }
1.1338    raeburn  2756:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2757:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2758:         }
                   2759:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2760:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2761:         }
                   2762:     }
1.1320    raeburn  2763:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2764:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2765:         foreach my $prefix (@prefixes) {
                   2766:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2767:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2768:             }
                   2769:         }
                   2770:     }
1.1314    raeburn  2771:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2772:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2773:     }
1.1332    raeburn  2774:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2775:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2776:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2777:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2778:         }
                   2779:     }
1.1434    raeburn  2780:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1437    raeburn  2781:         foreach my $item ('ipheader','trusted','vpnint','vpnext') {
1.1434    raeburn  2782:             if ($domconfig{'wafproxy'}{$item}) {
                   2783:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2784:             }
                   2785:         }
                   2786:     } 
1.1219    raeburn  2787:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2788:     return %domdefaults;
                   2789: }
                   2790: 
1.1412    raeburn  2791: sub get_dom_cats {
                   2792:     my ($dom) = @_;
                   2793:     return unless (&domain($dom));
                   2794:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2795:     unless (defined($cached)) {
                   2796:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2797:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2798:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2799:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2800:             } else {
                   2801:                 $cats = {};
                   2802:             }
                   2803:         } else {
                   2804:             $cats = {};
                   2805:         }
                   2806:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2807:     }
1.1413    raeburn  2808:     return $cats;
                   2809: }
                   2810: 
                   2811: sub get_dom_instcats {
                   2812:     my ($dom) = @_;
                   2813:     return unless (&domain($dom));
                   2814:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2815:     unless (defined($cached)) {
                   2816:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2817:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2818:         if ($totcodes > 0) {
                   2819:             my $caller = 'global';
                   2820:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2821:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2822:                 $instcats = {
                   2823:                                 codes => \%codes,
                   2824:                                 codetitles => \@codetitles,
                   2825:                                 cat_titles => \%cat_titles,
                   2826:                                 cat_order => \%cat_order,
                   2827:                             };
                   2828:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2829:             }
                   2830:         }
                   2831:     }
                   2832:     return $instcats;
                   2833: }
                   2834: 
                   2835: sub retrieve_instcodes {
                   2836:     my ($coursecodes,$dom) = @_;
                   2837:     my $totcodes;
                   2838:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2839:     foreach my $course (keys(%courses)) {
                   2840:         if (ref($courses{$course}) eq 'HASH') {
                   2841:             if ($courses{$course}{'inst_code'} ne '') {
                   2842:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2843:                 $totcodes ++;
                   2844:             }
                   2845:         }
                   2846:     }
                   2847:     return $totcodes;
1.1412    raeburn  2848: }
                   2849: 
1.1311    raeburn  2850: sub course_portal_url {
                   2851:     my ($cnum,$cdom) = @_;
                   2852:     my $chome = &homeserver($cnum,$cdom);
                   2853:     my $hostname = &hostname($chome);
                   2854:     my $protocol = $protocol{$chome};
                   2855:     $protocol = 'http' if ($protocol ne 'https');
                   2856:     my %domdefaults = &get_domain_defaults($cdom);
                   2857:     my $firsturl;
                   2858:     if ($domdefaults{'portal_def'}) {
                   2859:         $firsturl = $domdefaults{'portal_def'};
                   2860:     } else {
                   2861:         $firsturl = $protocol.'://'.$hostname;
                   2862:     }
                   2863:     return $firsturl;
                   2864: }
                   2865: 
1.1407    raeburn  2866: # --------------------------------------------- Get domain config for passwords
                   2867: 
                   2868: sub get_passwdconf {
                   2869:     my ($dom) = @_;
                   2870:     my (%passwdconf,$gotconf,$lookup);
                   2871:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2872:     if (defined($cached)) {
                   2873:         if (ref($result) eq 'HASH') {
                   2874:             %passwdconf = %{$result};
                   2875:             $gotconf = 1;
                   2876:         }
                   2877:     }
                   2878:     unless ($gotconf) {
                   2879:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2880:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2881:             %passwdconf = %{$domconfig{'passwords'}};
                   2882:         }
                   2883:         my $cachetime = 24*60*60;
                   2884:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2885:     }
                   2886:     return %passwdconf;
                   2887: }
                   2888: 
1.344     www      2889: # --------------------------------------------------- Assign a key to a student
                   2890: 
                   2891: sub assign_access_key {
1.364     www      2892: #
                   2893: # a valid key looks like uname:udom#comments
                   2894: # comments are being appended
                   2895: #
1.498     www      2896:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2897:     $kdom=
1.620     albertel 2898:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2899:     $knum=
1.620     albertel 2900:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2901:     $cdom=
1.620     albertel 2902:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2903:     $cnum=
1.620     albertel 2904:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2905:     $udom=$env{'user.name'} unless (defined($udom));
                   2906:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2907:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2908:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2909:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2910:                                                   # assigned to this person
                   2911:                                                   # - this should not happen,
1.345     www      2912:                                                   # unless something went wrong
                   2913:                                                   # the first time around
                   2914: # ready to assign
1.364     www      2915:         $logentry=$1.'; '.$logentry;
1.496     www      2916:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2917:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2918: # key now belongs to user
1.346     www      2919: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2920:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2921:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2922:                 return 'ok';
                   2923:             } else {
                   2924:                 return 
                   2925:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2926: 	    }
                   2927:         } else {
                   2928:             return 'error: Could not assign key, try again later.';
                   2929:         }
1.364     www      2930:     } elsif (!$existing{$ckey}) {
1.345     www      2931: # the key does not exist
                   2932: 	return 'error: The key does not exist';
                   2933:     } else {
                   2934: # the key is somebody else's
                   2935: 	return 'error: The key is already in use';
                   2936:     }
1.344     www      2937: }
                   2938: 
1.364     www      2939: # ------------------------------------------ put an additional comment on a key
                   2940: 
                   2941: sub comment_access_key {
                   2942: #
                   2943: # a valid key looks like uname:udom#comments
                   2944: # comments are being appended
                   2945: #
                   2946:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2947:     $cdom=
1.620     albertel 2948:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2949:     $cnum=
1.620     albertel 2950:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2951:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2952:     if ($existing{$ckey}) {
                   2953:         $existing{$ckey}.='; '.$logentry;
                   2954: # ready to assign
1.367     www      2955:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2956:                                                  $cdom,$cnum) eq 'ok') {
                   2957: 	    return 'ok';
                   2958:         } else {
                   2959: 	    return 'error: Count not store comment.';
                   2960:         }
                   2961:     } else {
                   2962: # the key does not exist
                   2963: 	return 'error: The key does not exist';
                   2964:     }
                   2965: }
                   2966: 
1.344     www      2967: # ------------------------------------------------------ Generate a set of keys
                   2968: 
                   2969: sub generate_access_keys {
1.364     www      2970:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2971:     $cdom=
1.620     albertel 2972:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2973:     $cnum=
1.620     albertel 2974:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2975:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2976:     unless (($cdom) && ($cnum)) { return 0; }
                   2977:     if ($number>10000) { return 0; }
                   2978:     sleep(2); # make sure don't get same seed twice
                   2979:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2980:     my $total=0;
                   2981:     for (my $i=1;$i<=$number;$i++) {
                   2982:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2983:                   sprintf("%lx",int(100000*rand)).'-'.
                   2984:                   sprintf("%lx",int(100000*rand));
                   2985:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2986:        $newkey=~s/0/h/g; # and also 0 and O
                   2987:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2988:        if ($existing{$newkey}) {
                   2989:            $i--;
                   2990:        } else {
1.364     www      2991: 	  if (&put('accesskeys',
                   2992:               { $newkey => '# generated '.localtime().
1.620     albertel 2993:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2994:                            '; '.$logentry },
                   2995: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2996:               $total++;
                   2997: 	  }
                   2998:        }
                   2999:     }
1.620     albertel 3000:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      3001:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   3002:     return $total;
                   3003: }
                   3004: 
                   3005: # ------------------------------------------------------- Validate an accesskey
                   3006: 
                   3007: sub validate_access_key {
                   3008:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3009:     $cdom=
1.620     albertel 3010:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3011:     $cnum=
1.620     albertel 3012:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3013:     $udom=$env{'user.domain'} unless (defined($udom));
                   3014:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3015:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3016:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3017: }
                   3018: 
                   3019: # ------------------------------------- Find the section of student in a course
1.652     albertel 3020: sub devalidate_getsection_cache {
                   3021:     my ($udom,$unam,$courseid)=@_;
                   3022:     my $hashid="$udom:$unam:$courseid";
                   3023:     &devalidate_cache_new('getsection',$hashid);
                   3024: }
1.298     matthew  3025: 
1.815     albertel 3026: sub courseid_to_courseurl {
                   3027:     my ($courseid) = @_;
                   3028:     #already url style courseid
                   3029:     return $courseid if ($courseid =~ m{^/});
                   3030: 
                   3031:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3032: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3033: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3034: 	return "/$cdom/$cnum";
                   3035:     }
                   3036: 
                   3037:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3038:     if (exists($courseinfo{'num'})) {
                   3039: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3040:     }
                   3041: 
                   3042:     return undef;
                   3043: }
                   3044: 
1.298     matthew  3045: sub getsection {
                   3046:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3047:     my $cachetime=1800;
1.551     albertel 3048: 
                   3049:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3050:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3051:     if (defined($cached)) { return $result; }
                   3052: 
1.298     matthew  3053:     my %Pending; 
                   3054:     my %Expired;
                   3055:     #
                   3056:     # Each role can either have not started yet (pending), be active, 
                   3057:     #    or have expired.
                   3058:     #
                   3059:     # If there is an active role, we are done.
                   3060:     #
                   3061:     # If there is more than one role which has not started yet, 
                   3062:     #     choose the one which will start sooner
                   3063:     # If there is one role which has not started yet, return it.
                   3064:     #
                   3065:     # If there is more than one expired role, choose the one which ended last.
                   3066:     # If there is a role which has expired, return it.
                   3067:     #
1.815     albertel 3068:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3069:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3070:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3071:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3072:         my $section=$1;
                   3073:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3074:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3075:         my $now=time;
1.548     albertel 3076:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3077:             $Expired{$end}=$section;
                   3078:             next;
                   3079:         }
1.548     albertel 3080:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3081:             $Pending{$start}=$section;
                   3082:             next;
                   3083:         }
1.599     albertel 3084:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3085:     }
                   3086:     #
                   3087:     # Presumedly there will be few matching roles from the above
                   3088:     # loop and the sorting time will be negligible.
                   3089:     if (scalar(keys(%Pending))) {
                   3090:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3091:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3092:     } 
                   3093:     if (scalar(keys(%Expired))) {
                   3094:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3095:         my $time = pop(@sorted);
1.599     albertel 3096:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3097:     }
1.599     albertel 3098:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3099: }
1.70      www      3100: 
1.599     albertel 3101: sub save_cache {
                   3102:     &purge_remembered();
1.722     albertel 3103:     #&Apache::loncommon::validate_page();
1.620     albertel 3104:     undef(%env);
1.780     albertel 3105:     undef($env_loaded);
1.599     albertel 3106: }
1.452     albertel 3107: 
1.599     albertel 3108: my $to_remember=-1;
                   3109: my %remembered;
                   3110: my %accessed;
                   3111: my $kicks=0;
                   3112: my $hits=0;
1.849     albertel 3113: sub make_key {
                   3114:     my ($name,$id) = @_;
1.872     albertel 3115:     if (length($id) > 65 
                   3116: 	&& length(&escape($id)) > 200) {
                   3117: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3118:     }
1.849     albertel 3119:     return &escape($name.':'.$id);
                   3120: }
                   3121: 
1.599     albertel 3122: sub devalidate_cache_new {
                   3123:     my ($name,$id,$debug) = @_;
                   3124:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3125:     my $remembered_id=$name.':'.$id;
1.849     albertel 3126:     $id=&make_key($name,$id);
1.599     albertel 3127:     $memcache->delete($id);
1.1319    damieng  3128:     delete($remembered{$remembered_id});
                   3129:     delete($accessed{$remembered_id});
1.599     albertel 3130: }
                   3131: 
                   3132: sub is_cached_new {
                   3133:     my ($name,$id,$debug) = @_;
1.1319    damieng  3134:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3135:     if (exists($remembered{$remembered_id})) {
                   3136: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3137: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3138: 	$hits++;
1.1319    damieng  3139: 	return ($remembered{$remembered_id},1);
1.599     albertel 3140:     }
1.1319    damieng  3141:     $id=&make_key($name,$id);
1.599     albertel 3142:     my $value = $memcache->get($id);
                   3143:     if (!(defined($value))) {
                   3144: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3145: 	return (undef,undef);
1.416     albertel 3146:     }
1.599     albertel 3147:     if ($value eq '__undef__') {
                   3148: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3149: 	$value=undef;
                   3150:     }
1.1319    damieng  3151:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3152:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3153:     return ($value,1);
                   3154: }
                   3155: 
                   3156: sub do_cache_new {
                   3157:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3158:     my $remembered_id=$name.':'.$id;
1.849     albertel 3159:     $id=&make_key($name,$id);
1.599     albertel 3160:     my $setvalue=$value;
                   3161:     if (!defined($setvalue)) {
                   3162: 	$setvalue='__undef__';
                   3163:     }
1.623     albertel 3164:     if (!defined($time) ) {
                   3165: 	$time=600;
                   3166:     }
1.599     albertel 3167:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3168:     my $result = $memcache->set($id,$setvalue,$time);
                   3169:     if (! $result) {
1.872     albertel 3170: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3171: 	$memcache->disconnect_all();
1.872     albertel 3172:     }
1.600     albertel 3173:     # need to make a copy of $value
1.1319    damieng  3174:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3175:     return $value;
                   3176: }
                   3177: 
                   3178: sub make_room {
1.1319    damieng  3179:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3180: 
1.1319    damieng  3181:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3182:                                     : $value;
1.599     albertel 3183:     if ($to_remember<0) { return; }
1.1319    damieng  3184:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3185:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3186:     my $to_kick;
                   3187:     my $max_time=0;
                   3188:     foreach my $other (keys(%accessed)) {
                   3189: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3190: 	    $to_kick=$other;
                   3191: 	    $max_time=&tv_interval($accessed{$other});
                   3192: 	}
                   3193:     }
                   3194:     delete($remembered{$to_kick});
                   3195:     delete($accessed{$to_kick});
                   3196:     $kicks++;
                   3197:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3198:     return;
                   3199: }
                   3200: 
1.599     albertel 3201: sub purge_remembered {
1.604     albertel 3202:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3203:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3204:     undef(%remembered);
                   3205:     undef(%accessed);
1.428     albertel 3206: }
1.70      www      3207: # ------------------------------------- Read an entry from a user's environment
                   3208: 
                   3209: sub userenvironment {
                   3210:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3211:     my $items;
                   3212:     foreach my $item (@what) {
                   3213:         $items.=&escape($item).'&';
                   3214:     }
                   3215:     $items=~s/\&$//;
1.70      www      3216:     my %returnhash=();
1.1009    raeburn  3217:     my $uhome = &homeserver($unam,$udom);
                   3218:     unless ($uhome eq 'no_host') {
                   3219:         my @answer=split(/\&/, 
                   3220:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3221:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3222:             return %returnhash;
                   3223:         }
1.1009    raeburn  3224:         my $i;
                   3225:         for ($i=0;$i<=$#what;$i++) {
                   3226: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3227:         }
1.70      www      3228:     }
                   3229:     return %returnhash;
1.1       albertel 3230: }
                   3231: 
1.617     albertel 3232: # ---------------------------------------------------------- Get a studentphoto
                   3233: sub studentphoto {
                   3234:     my ($udom,$unam,$ext) = @_;
                   3235:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3236:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3237:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3238:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3239:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3240:             } else {
                   3241:                 my ($result,$perm_reqd)=
1.707     albertel 3242: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3243:                 if ($result eq 'ok') {
                   3244:                     if (!($perm_reqd eq 'yes')) {
                   3245:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3246:                     }
                   3247:                 }
                   3248:             }
                   3249:         }
                   3250:     } else {
                   3251:         my ($result,$perm_reqd) = 
1.707     albertel 3252: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3253:         if ($result eq 'ok') {
                   3254:             if (!($perm_reqd eq 'yes')) {
                   3255:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3256:             }
                   3257:         }
                   3258:     }
                   3259:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3260: }
                   3261: 
                   3262: sub retrievestudentphoto {
                   3263:     my ($udom,$unam,$ext,$type) = @_;
                   3264:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3265:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3266:     if ($ret eq 'ok') {
                   3267:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3268:         if ($type eq 'thumbnail') {
                   3269:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3270:         }
                   3271:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3272:         return $tokenurl;
                   3273:     } else {
                   3274:         if ($type eq 'thumbnail') {
                   3275:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3276:         } else { 
                   3277:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3278:         }
1.617     albertel 3279:     }
                   3280: }
                   3281: 
1.263     www      3282: # -------------------------------------------------------------------- New chat
                   3283: 
                   3284: sub chatsend {
1.724     raeburn  3285:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3286:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3287:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3288:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3289:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3290: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3291: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3292: }
                   3293: 
                   3294: # ------------------------------------------ Find current version of a resource
                   3295: 
                   3296: sub getversion {
                   3297:     my $fname=&clutter(shift);
1.1189    raeburn  3298:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3299:     return &currentversion(&filelocation('',$fname));
                   3300: }
                   3301: 
                   3302: sub currentversion {
                   3303:     my $fname=shift;
                   3304:     my $author=$fname;
                   3305:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3306:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3307:     my $home=&homeserver($uname,$udom);
1.292     www      3308:     if ($home eq 'no_host') { 
                   3309:         return -1; 
                   3310:     }
1.1112    www      3311:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3312:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3313: 	return -1;
                   3314:     }
1.1112    www      3315:     return $answer;
1.263     www      3316: }
                   3317: 
1.1111    www      3318: #
                   3319: # Return special version number of resource if set by override, empty otherwise
                   3320: #
                   3321: sub usedversion {
                   3322:     my $fname=shift;
                   3323:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3324:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3325:     if ($urlversion) { return $urlversion; }
                   3326:     return '';
                   3327: }
                   3328: 
1.1       albertel 3329: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3330: 
1.1       albertel 3331: sub subscribe {
                   3332:     my $fname=shift;
1.761     raeburn  3333:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3334:     $fname=~s/[\n\r]//g;
1.1       albertel 3335:     my $author=$fname;
                   3336:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3337:     my ($udom,$uname)=split(/\//,$author);
                   3338:     my $home=homeserver($uname,$udom);
1.335     albertel 3339:     if ($home eq 'no_host') {
                   3340:         return 'not_found';
1.1       albertel 3341:     }
                   3342:     my $answer=reply("sub:$fname",$home);
1.64      www      3343:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3344: 	$answer.=' by '.$home;
                   3345:     }
1.1       albertel 3346:     return $answer;
                   3347: }
                   3348:     
1.8       www      3349: # -------------------------------------------------------------- Replicate file
                   3350: 
                   3351: sub repcopy {
                   3352:     my $filename=shift;
1.23      www      3353:     $filename=~s/\/+/\//g;
1.1142    raeburn  3354:     my $londocroot = $perlvar{'lonDocRoot'};
                   3355:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3356:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3357:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3358: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3359: 	return &repcopy_userfile($filename);
                   3360:     }
1.532     albertel 3361:     $filename=~s/[\n\r]//g;
1.8       www      3362:     my $transname="$filename.in.transfer";
1.828     www      3363: # FIXME: this should flock
1.607     raeburn  3364:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3365:     my $remoteurl=subscribe($filename);
1.64      www      3366:     if ($remoteurl =~ /^con_lost by/) {
                   3367: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3368:            return 'unavailable';
1.8       www      3369:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3370: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3371: 	   return 'not_found';
1.64      www      3372:     } elsif ($remoteurl =~ /^rejected by/) {
                   3373: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3374:            return 'forbidden';
1.20      www      3375:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3376:            return 'ok';
1.8       www      3377:     } else {
1.290     www      3378:         my $author=$filename;
                   3379:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3380:         my ($udom,$uname)=split(/\//,$author);
                   3381:         my $home=homeserver($uname,$udom);
                   3382:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3383:            my @parts=split(/\//,$filename);
                   3384:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3385:            if ($path ne "$londocroot/res") {
1.8       www      3386:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3387: 	       return 'bad_request';
1.8       www      3388:            }
                   3389:            my $count;
                   3390:            for ($count=5;$count<$#parts;$count++) {
                   3391:                $path.="/$parts[$count]";
                   3392:                if ((-e $path)!=1) {
                   3393: 		   mkdir($path,0777);
                   3394:                }
                   3395:            }
                   3396:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3397:            my $response;
                   3398:            if ($remoteurl =~ m{/raw/}) {
                   3399:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3400:            } else {
                   3401:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3402:            }
1.8       www      3403:            if ($response->is_error()) {
                   3404: 	       unlink($transname);
                   3405:                my $message=$response->status_line;
1.672     albertel 3406:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3407:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3408:                return 'unavailable';
1.8       www      3409:            } else {
1.16      www      3410: 	       if ($remoteurl!~/\.meta$/) {
                   3411:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3412:                   my $mresponse;
                   3413:                   if ($remoteurl =~ m{/raw/}) {
                   3414:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3415:                   } else {
                   3416:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3417:                   }
1.16      www      3418:                   if ($mresponse->is_error()) {
                   3419: 		      unlink($filename.'.meta');
                   3420:                       &logthis(
1.672     albertel 3421:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3422:                   }
                   3423: 	       }
1.8       www      3424:                rename($transname,$filename);
1.607     raeburn  3425:                return 'ok';
1.8       www      3426:            }
1.290     www      3427:        }
1.8       www      3428:     }
1.330     www      3429: }
                   3430: 
1.1422    raeburn  3431: # ------------------------------------------------- Unsubscribe from a resource
                   3432: 
                   3433: sub unsubscribe {
                   3434:     my ($fname) = @_;
                   3435:     my $answer;
                   3436:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3437:     $fname=~s/[\n\r]//g;
                   3438:     my $author=$fname;
                   3439:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3440:     my ($udom,$uname)=split(/\//,$author);
                   3441:     my $home=homeserver($uname,$udom);
                   3442:     if ($home eq 'no_host') {
                   3443:         $answer = 'no_host';
                   3444:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3445:         $answer = 'home';
                   3446:     } else {
                   3447:         my $defdom = $perlvar{'lonDefDomain'};
                   3448:         if (&will_trust('content',$defdom,$udom)) {
                   3449:             $answer = reply("unsub:$fname",$home);
                   3450:         } else {
                   3451:             $answer = 'untrusted';
                   3452:         }
                   3453:     }
                   3454:     return $answer;
                   3455: }
                   3456: 
1.330     www      3457: # ------------------------------------------------ Get server side include body
                   3458: sub ssi_body {
1.381     albertel 3459:     my ($filelink,%form)=@_;
1.606     matthew  3460:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3461:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3462:     }
1.953     www      3463:     my $output='';
                   3464:     my $response;
1.980     raeburn  3465:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3466:        ($output,$response)=&externalssi($filelink);
1.953     www      3467:     } else {
1.1004    droeschl 3468:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3469:        $filelink .= 'inhibitmenu=yes';
1.953     www      3470:        ($output,$response)=&ssi($filelink,%form);
                   3471:     }
1.778     albertel 3472:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3473:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3474:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3475:     if (wantarray) {
                   3476:         return ($output, $response);
                   3477:     } else {
                   3478:         return $output;
                   3479:     }
1.8       www      3480: }
                   3481: 
1.15      www      3482: # --------------------------------------------------------- Server Side Include
                   3483: 
1.782     albertel 3484: sub absolute_url {
                   3485:     my ($host_name) = @_;
                   3486:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3487:     if ($host_name eq '') {
                   3488: 	$host_name = $ENV{'SERVER_NAME'};
                   3489:     }
                   3490:     return $protocol.$host_name;
                   3491: }
                   3492: 
1.942     foxr     3493: #
                   3494: #   Server side include.
                   3495: # Parameters:
                   3496: #  fn     Possibly encrypted resource name/id.
                   3497: #  form   Hash that describes how the rendering should be done
                   3498: #         and other things.
1.944     foxr     3499: # Returns:
1.950     raeburn  3500: #   Scalar context: The content of the response.
                   3501: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3502: #     
1.15      www      3503: sub ssi {
                   3504: 
1.944     foxr     3505:     my ($fn,%form)=@_;
1.23      www      3506:     my $request;
1.711     albertel 3507: 
                   3508:     $form{'no_update_last_known'}=1;
1.895     albertel 3509:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3510:     if (%form) {
1.782     albertel 3511:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3512:       $request->content(join('&',map { 
                   3513:             my $name = escape($_);
                   3514:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3515:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3516:             : &escape($form{$_}) );    
                   3517:         } keys(%form)));
1.23      www      3518:     } else {
1.782     albertel 3519:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3520:     }
                   3521: 
1.15      www      3522:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3523:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3524:     my $islocal;
                   3525:     if (($env{'request.course.id'}) &&
                   3526:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3527:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3528:         ($form{'grade_symb'} ne '') &&
                   3529:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3530:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3531:         $islocal = 1;
                   3532:     }
1.1384    raeburn  3533:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3534:                                                 '','','',$islocal);
1.1182    foxr     3535: 
1.944     foxr     3536:     if (wantarray) {
1.1345    raeburn  3537: 	return ($response->content, $response);
1.944     foxr     3538:     } else {
1.1345    raeburn  3539: 	return $response->content;
1.942     foxr     3540:     }
1.324     www      3541: }
                   3542: 
                   3543: sub externalssi {
                   3544:     my ($url)=@_;
                   3545:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3546:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3547:     if (wantarray) {
                   3548:         return ($response->content, $response);
                   3549:     } else {
                   3550:         return $response->content;
                   3551:     }
1.15      www      3552: }
1.254     www      3553: 
1.1354    raeburn  3554: 
                   3555: # If the local copy of a replicated resource is outdated, trigger a  
                   3556: # connection from the homeserver to flush the delayed queue. If no update 
                   3557: # happens, remove local copies of outdated resource (and corresponding
                   3558: # metadata file).
                   3559: 
1.1352    raeburn  3560: sub remove_stale_resfile {
                   3561:     my ($url) = @_;
1.1354    raeburn  3562:     my $removed;
1.1352    raeburn  3563:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3564:         my $audom = $1;
                   3565:         my $auname = $2;
1.1353    raeburn  3566:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3567:             my $homeserver = &homeserver($auname,$audom);
                   3568:             unless (($homeserver eq 'no_host') ||
                   3569:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3570:                 my $fname = &filelocation('',$url);
                   3571:                 if (-e $fname) {
                   3572:                     my $hostname = &hostname($homeserver);
                   3573:                     if ($hostname) {
1.1397    raeburn  3574:                         my $protocol = $protocol{$homeserver};
                   3575:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3576:                         my $uri = &declutter($url);
                   3577:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3578:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3579:                         if ($response->is_success()) {
                   3580:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3581:                             my $locmodtime = (stat($fname))[9];
                   3582:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3583:                                 my $stale;
                   3584:                                 my $answer = &reply('pong',$homeserver);
                   3585:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3586:                                     sleep(0.2);
                   3587:                                     $locmodtime = (stat($fname))[9];
                   3588:                                     if ($locmodtime < $remmodtime) {
                   3589:                                         my $posstransfer = $fname.'.in.transfer';
                   3590:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3591:                                             $removed = 1;
                   3592:                                         } else {
                   3593:                                             $stale = 1;
                   3594:                                         }
                   3595:                                     } else {
                   3596:                                         $removed = 1;
                   3597:                                     }
                   3598:                                 } else {
                   3599:                                     $stale = 1;
                   3600:                                 }
                   3601:                                 if ($stale) {
1.1421    raeburn  3602:                                     if (unlink($fname)) {
                   3603:                                         if ($uri!~/\.meta$/) {
                   3604:                                             if (-e $fname.'.meta') {
                   3605:                                                 unlink($fname.'.meta');
                   3606:                                             }
                   3607:                                         }
1.1422    raeburn  3608:                                         my $unsubresult = &unsubscribe($fname);
                   3609:                                         unless ($unsubresult eq 'ok') {
                   3610:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3611:                                         }
1.1421    raeburn  3612:                                         $removed = 1;
1.1354    raeburn  3613:                                     }
1.1352    raeburn  3614:                                 }
                   3615:                             }
                   3616:                         }
                   3617:                     }
                   3618:                 }
                   3619:             }
                   3620:         }
                   3621:     }
1.1354    raeburn  3622:     return $removed;
1.1352    raeburn  3623: }
                   3624: 
1.492     albertel 3625: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3626: 
                   3627: sub allowuploaded {
                   3628:     my ($srcurl,$url)=@_;
                   3629:     $url=&clutter(&declutter($url));
                   3630:     my $dir=$url;
                   3631:     $dir=~s/\/[^\/]+$//;
                   3632:     my %httpref=();
                   3633:     my $httpurl=&hreflocation('',$url);
                   3634:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3635:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3636: }
1.477     raeburn  3637: 
1.1193    raeburn  3638: #
                   3639: # Determine if the current user should be able to edit a particular resource,
                   3640: # when viewing in course context.
                   3641: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3642: #     Functions.
                   3643: # (b) When displaying folder contents in course editor, used to determine if
                   3644: #     "Edit" link will be displayed alongside resource.
                   3645: #
1.1196    raeburn  3646: #  input: six args -- filename (decluttered), course number, course domain,
                   3647: #                   url, symb (if registered) and group (if this is a group
                   3648: #                   item -- e.g., bulletin board, group page etc.).
                   3649: #  output: array of five scalars -- 
1.1193    raeburn  3650: #          $cfile -- url for file editing if editable on current server
                   3651: #          $home -- homeserver of resource (i.e., for author if published,
                   3652: #                                           or course if uploaded.).
                   3653: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3654: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3655: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3656: #
                   3657: 
                   3658: sub can_edit_resource {
1.1194    raeburn  3659:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3660:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3661: #
                   3662: # For aboutme pages user can only edit his/her own.
                   3663: #
1.1199    raeburn  3664:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3665:         my ($sdom,$sname) = ($1,$2);
                   3666:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3667:             $home = $env{'user.home'};
                   3668:             $cfile = $resurl;
                   3669:             if ($env{'form.forceedit'}) {
                   3670:                 $forceview = 1;
                   3671:             } else {
                   3672:                 $forceedit = 1;
                   3673:             }
                   3674:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3675:         } else {
                   3676:             return;
                   3677:         }
                   3678:     }
                   3679: 
                   3680:     if ($env{'request.course.id'}) {
                   3681:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3682:         if ($group ne '') {
                   3683: # if this is a group homepage or group bulletin board, check group privs
                   3684:             my $allowed = 0;
1.1197    raeburn  3685:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3686:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3687:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3688:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3689:                     $allowed = 1;
                   3690:                 }
1.1197    raeburn  3691:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3692:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3693:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3694:                     $allowed = 1;
                   3695:                 }
                   3696:             }
                   3697:             if ($allowed) {
                   3698:                 $home=&homeserver($cnum,$cdom);
                   3699:                 if ($env{'form.forceedit'}) {
                   3700:                     $forceview = 1;
                   3701:                 } else {
                   3702:                     $forceedit = 1;
                   3703:                 }
                   3704:                 $cfile = $resurl;
                   3705:             } else {
                   3706:                 return;
                   3707:             }
                   3708:         } else {
1.1208    raeburn  3709:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3710:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3711:                     return;
                   3712:                 }
                   3713:             } elsif (!$crsedit) {
1.1194    raeburn  3714: #
                   3715: # No edit allowed where CC has switched to student role.
                   3716: #
                   3717:                 return;
                   3718:             }
                   3719:         }
                   3720:     }
                   3721: 
1.1193    raeburn  3722:     if ($file ne '') {
                   3723:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3724:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3725:                 $uploaded = 1;
                   3726:                 $incourse = 1;
1.1193    raeburn  3727:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3728:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3729:                     if ($env{'form.forceedit'}) {
                   3730:                         $forceview = 1;
                   3731:                     } else {
                   3732:                         $forceedit = 1;
                   3733:                     }
1.1194    raeburn  3734:                 }
                   3735:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3736:                 $incourse = 1;
                   3737:                 if ($env{'form.forceedit'}) {
                   3738:                     $forceview = 1;
                   3739:                 } else {
                   3740:                     $forceedit = 1;
                   3741:                 }
                   3742:                 $cfile = $resurl;
                   3743:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3744:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3745:                     $incourse = 1;
                   3746:                     if ($env{'form.forceedit'}) {
                   3747:                         $forceview = 1;
                   3748:                     } else {
                   3749:                         $forceedit = 1;
                   3750:                     }
                   3751:                     $cfile = $resurl;
1.1199    raeburn  3752:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3753:                     $incourse = 1;
                   3754:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3755:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3756:                     $incourse = 1;
1.1199    raeburn  3757:                     if ($env{'form.forceedit'}) {
                   3758:                         $forceview = 1;
                   3759:                     } else {
                   3760:                         $forceedit = 1;
                   3761:                     }
                   3762:                     $cfile = $resurl;
1.1419    raeburn  3763:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3764:                     my ($map,$id,$res) = &decode_symb($symb);
                   3765:                     if ($map =~ /\.page$/) {
                   3766:                         $incourse = 1;
                   3767:                         if ($env{'form.forceedit'}) {
                   3768:                             $forceview = 1;
                   3769:                             $cfile = $map;
                   3770:                         } else {
                   3771:                             $forceedit = 1;
                   3772:                             $cfile =  '/adm/wrapper'.$resurl;
                   3773:                         }
                   3774:                     }
1.1343    raeburn  3775:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3776:                     $incourse = 1;
                   3777:                     if ($env{'form.forceedit'}) {
                   3778:                         $forceview = 1;
                   3779:                     } else {
                   3780:                         $forceedit = 1;
                   3781:                     }
                   3782:                     $cfile = $resurl;
1.1208    raeburn  3783:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3784:                     $incourse = 1;
                   3785:                     if ($env{'form.forceedit'}) {
                   3786:                         $forceview = 1;
                   3787:                     } else {
                   3788:                         $forceedit = 1;
                   3789:                     }
                   3790:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3791:                 }
                   3792:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3793:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3794:                 if (&is_on_map($template)) { 
                   3795:                     $incourse = 1;
                   3796:                     $forceview = 1;
                   3797:                     $cfile = $template;
1.1193    raeburn  3798:                 }
1.1199    raeburn  3799:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  3800:                 $incourse = 1;
                   3801:                 if ($env{'form.forceedit'}) {
                   3802:                     $forceview = 1;
                   3803:                 } else {
                   3804:                     $forceedit = 1;
                   3805:                 }
                   3806:                 $cfile = $resurl;
1.1343    raeburn  3807:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3808:                 $incourse = 1;
                   3809:                 if ($env{'form.forceedit'}) {
                   3810:                     $forceview = 1;
                   3811:                 } else {
                   3812:                     $forceedit = 1;
                   3813:                 }
                   3814:                 $cfile = $resurl;
1.1199    raeburn  3815:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3816:                 $incourse = 1;
                   3817:                 $forceview = 1;
                   3818:                 if ($symb) {
                   3819:                     my ($map,$id,$res)=&decode_symb($symb);
                   3820:                     $env{'request.symb'} = $symb;
                   3821:                     $cfile = &clutter($res);
                   3822:                 } else {
                   3823:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3824:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3825:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3826:                         $cfile = '/adm/wrapper'.$escfile;
                   3827:                     } else {
                   3828:                         $escfile =~ s{^http://}{};
                   3829:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3830:                     }
1.1199    raeburn  3831:                 }
1.1234    raeburn  3832:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3833:                 if ($env{'form.forceedit'}) {
                   3834:                     $forceview = 1;
                   3835:                 } else {
                   3836:                     $forceedit = 1;
                   3837:                 }
                   3838:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3839:             }
                   3840:         }
1.1194    raeburn  3841:         if ($uploaded || $incourse) {
                   3842:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3843:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3844:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3845:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3846:             # Check that the user has permission to edit this resource
                   3847:             my $setpriv = 1;
                   3848:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3849:             if (defined($cfudom)) {
                   3850:                 $home=&homeserver($cfuname,$cfudom);
                   3851:                 $cfile=$file;
                   3852:             }
                   3853:         }
1.1194    raeburn  3854:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3855:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3856:             my @ids=&current_machine_ids();
                   3857:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3858:                 $switchserver=1;
                   3859:             }
                   3860:         }
                   3861:     }
1.1194    raeburn  3862:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3863: }
                   3864: 
                   3865: sub is_course_upload {
                   3866:     my ($file,$cnum,$cdom) = @_;
                   3867:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3868:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3869:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3870:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3871:         return 1;
                   3872:     }
                   3873:     return;
                   3874: }
                   3875: 
1.1194    raeburn  3876: sub in_course {
1.1195    raeburn  3877:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3878:     if ($hideprivileged) {
                   3879:         my $skipuser;
1.1219    raeburn  3880:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3881:         my @possdoms = ($cdom);  
                   3882:         if ($coursehash{'checkforpriv'}) { 
                   3883:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3884:         }
                   3885:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3886:             $skipuser = 1;
                   3887:             if ($coursehash{'nothideprivileged'}) {
                   3888:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3889:                     my $user;
                   3890:                     if ($item =~ /:/) {
                   3891:                         $user = $item;
                   3892:                     } else {
                   3893:                         $user = join(':',split(/[\@]/,$item));
                   3894:                     }
                   3895:                     if ($user eq $uname.':'.$udom) {
                   3896:                         undef($skipuser);
                   3897:                         last;
                   3898:                     }
                   3899:                 }
                   3900:             }
                   3901:             if ($skipuser) {
                   3902:                 return 0;
                   3903:             }
                   3904:         }
                   3905:     }
1.1194    raeburn  3906:     $type ||= 'any';
                   3907:     if (!defined($cdom) || !defined($cnum)) {
                   3908:         my $cid  = $env{'request.course.id'};
                   3909:         $cdom = $env{'course.'.$cid.'.domain'};
                   3910:         $cnum = $env{'course.'.$cid.'.num'};
                   3911:     }
                   3912:     my $typesref;
1.1195    raeburn  3913:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3914:         $typesref = ['active','previous','future'];
                   3915:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3916:         $typesref = [$type];
                   3917:     }
                   3918:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3919:                               $typesref,undef,[$cdom]);
                   3920:     my ($tmp) = keys(%roles);
                   3921:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3922:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3923:     if (@course_roles > 0) {
                   3924:         return 1;
                   3925:     }
                   3926:     return 0;
                   3927: }
                   3928: 
1.478     albertel 3929: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3930: # input: action, courseID, current domain, intended
1.637     raeburn  3931: #        path to file, source of file, instruction to parse file for objects,
                   3932: #        ref to hash for embedded objects,
                   3933: #        ref to hash for codebase of java objects.
1.1095    raeburn  3934: #        reference to scalar to accommodate mime type determined
                   3935: #          from File::MMagic if $parser = parse.
1.637     raeburn  3936: #
1.485     raeburn  3937: # output: url to file (if action was uploaddoc), 
                   3938: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3939: #
1.478     albertel 3940: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3941: # course.
1.477     raeburn  3942: #
1.478     albertel 3943: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3944: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3945: #          course's home server.
1.477     raeburn  3946: #
1.478     albertel 3947: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3948: #          be copied from $source (current location) to 
                   3949: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3950: #         and will then be copied to
                   3951: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3952: #         course's home server.
1.485     raeburn  3953: #
1.481     raeburn  3954: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3955: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3956: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3957: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3958: #         in course's home server.
1.637     raeburn  3959: #
1.477     raeburn  3960: 
                   3961: sub process_coursefile {
1.1095    raeburn  3962:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3963:         $mimetype)=@_;
1.477     raeburn  3964:     my $fetchresult;
1.638     albertel 3965:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3966:     if ($action eq 'propagate') {
1.638     albertel 3967:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3968: 			     $home);
1.481     raeburn  3969:     } else {
1.477     raeburn  3970:         my $fpath = '';
                   3971:         my $fname = $file;
1.478     albertel 3972:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3973:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3974:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3975:         if ($action eq 'copy') {
                   3976:             if ($source eq '') {
                   3977:                 $fetchresult = 'no source file';
                   3978:                 return $fetchresult;
                   3979:             } else {
                   3980:                 my $destination = $filepath.'/'.$fname;
                   3981:                 rename($source,$destination);
                   3982:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3983:                                  $home);
1.481     raeburn  3984:             }
                   3985:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3986:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3987:             print $fh $env{'form.'.$source};
1.481     raeburn  3988:             close($fh);
1.637     raeburn  3989:             if ($parser eq 'parse') {
1.1024    raeburn  3990:                 my $mm = new File::MMagic;
1.1095    raeburn  3991:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3992:                 if ($type eq 'text/html') {
1.1024    raeburn  3993:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3994:                     unless ($parse_result eq 'ok') {
                   3995:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3996:                     }
1.637     raeburn  3997:                 }
1.1095    raeburn  3998:                 if (ref($mimetype)) {
                   3999:                     $$mimetype = $type;
                   4000:                 } 
1.637     raeburn  4001:             }
1.477     raeburn  4002:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4003:                                  $home);
1.481     raeburn  4004:             if ($fetchresult eq 'ok') {
                   4005:                 return '/uploaded/'.$fpath.'/'.$fname;
                   4006:             } else {
                   4007:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4008:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4009:                 return '/adm/notfound.html';
                   4010:             }
1.477     raeburn  4011:         }
                   4012:     }
1.485     raeburn  4013:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4014:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4015:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4016:     }
                   4017:     return $fetchresult;
                   4018: }
                   4019: 
1.637     raeburn  4020: sub build_filepath {
                   4021:     my ($fpath) = @_;
                   4022:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4023:     unless ($fpath eq '') {
                   4024:         my @parts=split('/',$fpath);
                   4025:         foreach my $part (@parts) {
                   4026:             $filepath.= '/'.$part;
                   4027:             if ((-e $filepath)!=1) {
                   4028:                 mkdir($filepath,0777);
                   4029:             }
                   4030:         }
                   4031:     }
                   4032:     return $filepath;
                   4033: }
                   4034: 
                   4035: sub store_edited_file {
1.638     albertel 4036:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4037:     my $file = $primary_url;
                   4038:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4039:     my $fpath = '';
                   4040:     my $fname = $file;
                   4041:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4042:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4043:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4044:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4045:     print $fh $content;
                   4046:     close($fh);
1.638     albertel 4047:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4048:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4049: 			  $home);
1.637     raeburn  4050:     if ($$fetchresult eq 'ok') {
                   4051:         return '/uploaded/'.$fpath.'/'.$fname;
                   4052:     } else {
1.638     albertel 4053:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4054: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4055:         return '/adm/notfound.html';
                   4056:     }
                   4057: }
                   4058: 
1.531     albertel 4059: sub clean_filename {
1.831     albertel 4060:     my ($fname,$args)=@_;
1.315     www      4061: # Replace Windows backslashes by forward slashes
1.257     www      4062:     $fname=~s/\\/\//g;
1.831     albertel 4063:     if (!$args->{'keep_path'}) {
                   4064:         # Get rid of everything but the actual filename
                   4065: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4066:     }
1.315     www      4067: # Replace spaces by underscores
                   4068:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4069: # Transliterate non-ascii text to ascii
                   4070:     my $lang = &Apache::lonlocal::current_language();
                   4071:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4072: # Replace all other weird characters by nothing
1.831     albertel 4073:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4074: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4075: # numbers
                   4076:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443  ! raeburn  4077: # Replace three or more adjacent underscores with one for consistency 
        !          4078: # with loncfile::filename_check() so complete url can be extracted by
        !          4079: # lonnet::decode_symb()
        !          4080:     $fname=~s/_{3,}/_/g;
1.531     albertel 4081:     return $fname;
                   4082: }
1.1406    raeburn  4083: 
1.1051    raeburn  4084: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4085: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4086: # image with the same aspect ratio as the original, but with dimensions which do 
                   4087: # not exceed $resizewidth and $resizeheight.
                   4088:  
1.984     neumanie 4089: sub resizeImage {
1.1051    raeburn  4090:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4091:     my $ima = Image::Magick->new;
                   4092:     my $resized;
                   4093:     if (-e $img_path) {
                   4094:         $ima->Read($img_path);
                   4095:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4096:             my $width = $ima->Get('width');
                   4097:             my $height = $ima->Get('height');
                   4098:             if ($width > $resizewidth) {
                   4099: 	        my $factor = $width/$resizewidth;
                   4100:                 my $newheight = $height/$factor;
                   4101:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4102:                 $resized = 1;
                   4103:             }
                   4104:         }
                   4105:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4106:             my $width = $ima->Get('width');
                   4107:             my $height = $ima->Get('height');
                   4108:             if ($height > $resizeheight) {
                   4109:                 my $factor = $height/$resizeheight;
                   4110:                 my $newwidth = $width/$factor;
                   4111:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4112:                 $resized = 1;
                   4113:             }
                   4114:         }
                   4115:         if ($resized) {
                   4116:             $ima->Write($img_path);
                   4117:         }
                   4118:     }
                   4119:     return;
1.977     amueller 4120: }
                   4121: 
1.608     albertel 4122: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4123: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4124: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4125: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4126: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4127: #                   if 'coursedoc': upload to the current course
                   4128: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4129: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4130: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4131: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4132: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4133: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4134: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4135: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4136: #        $allfiles - reference to hash for embedded objects
                   4137: #        $codebase - reference to hash for codebase of java objects
                   4138: #        $desuname - username for permanent storage of uploaded file
                   4139: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4140: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4141: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4142: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4143: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4144: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4145: #                    from File::MMagic.
1.858     raeburn  4146: # 
1.686     albertel 4147: # output: url of file in userspace, or error: <message> 
                   4148: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4149: 
1.531     albertel 4150: sub userfileupload {
1.1090    raeburn  4151:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4152:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4153:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4154:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4155:     $fname=&clean_filename($fname);
1.1090    raeburn  4156:     # See if there is anything left
1.257     www      4157:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4158:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4159:     if ($fname =~ /^\./) {
                   4160:         my ($s,$usec) = &gettimeofday();
                   4161:         while (length($usec) < 6) {
                   4162:             $usec = '0'.$usec;
                   4163:         }
                   4164:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4165:     }
1.1090    raeburn  4166:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4167:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4168:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4169:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4170:         my $now = time;
1.1090    raeburn  4171:         my $filepath;
1.1095    raeburn  4172:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4173:              $filepath = 'tmp/helprequests/'.$now;
                   4174:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4175:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4176:                          '_'.$env{'user.domain'}.'/pending';
                   4177:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4178:             my ($docuname,$docudom);
1.1350    raeburn  4179:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4180:                 $docudom = $destudom;
                   4181:             } else {
                   4182:                 $docudom = $env{'user.domain'};
                   4183:             }
1.1350    raeburn  4184:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4185:                 $docuname = $destuname;
                   4186:             } else {
                   4187:                 $docuname = $env{'user.name'};
                   4188:             }
                   4189:             if (exists($env{'form.group'})) {
                   4190:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4191:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4192:             }
                   4193:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4194:             if ($context eq 'canceloverwrite') {
                   4195:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4196:                 if (-e  $tempfile) {
                   4197:                     my @info = stat($tempfile);
                   4198:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4199:                         unlink($tempfile);
                   4200:                     }
                   4201:                 }
                   4202:                 return;
1.523     raeburn  4203:             }
                   4204:         }
1.1090    raeburn  4205:         # Create the directory if not present
1.741     raeburn  4206:         my @parts=split(/\//,$filepath);
                   4207:         my $fullpath = $perlvar{'lonDaemons'};
                   4208:         for (my $i=0;$i<@parts;$i++) {
                   4209:             $fullpath .= '/'.$parts[$i];
                   4210:             if ((-e $fullpath)!=1) {
                   4211:                 mkdir($fullpath,0777);
                   4212:             }
                   4213:         }
1.1359    raeburn  4214:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4215:         print $fh $env{'form.'.$formname};
                   4216:         close($fh);
1.1090    raeburn  4217:         if ($context eq 'existingfile') {
                   4218:             my @info = stat($fullpath.'/'.$fname);
                   4219:             return ($fullpath.'/'.$fname,$info[9]);
                   4220:         } else {
                   4221:             return $fullpath.'/'.$fname;
                   4222:         }
1.523     raeburn  4223:     }
1.995     raeburn  4224:     if ($subdir eq 'scantron') {
                   4225:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4226:     } else {
1.995     raeburn  4227:         $fname="$subdir/$fname";
                   4228:     }
1.1090    raeburn  4229:     if ($context eq 'coursedoc') {
1.638     albertel 4230: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4231: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4232:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4233:             return &finishuserfileupload($docuname,$docudom,
                   4234: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4235: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4236:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4237:         } else {
1.1218    raeburn  4238:             if ($env{'form.folder'}) {
                   4239:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4240:             }
1.638     albertel 4241:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4242: 				       $fname,$formname,$parser,
1.1095    raeburn  4243: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4244:         }
1.719     banghart 4245:     } elsif (defined($destuname)) {
                   4246:         my $docuname=$destuname;
                   4247:         my $docudom=$destudom;
1.860     raeburn  4248: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4249: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4250:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4251:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4252:     } else {
1.638     albertel 4253:         my $docuname=$env{'user.name'};
                   4254:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4255:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4256:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4257:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4258:         }
1.860     raeburn  4259: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4260: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4261:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4262:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4263:     }
1.271     www      4264: }
                   4265: 
                   4266: sub finishuserfileupload {
1.860     raeburn  4267:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4268:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4269:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4270:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4271:   
1.860     raeburn  4272:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4273:     $file=$fname;
                   4274:     if ($fname=~m|/|) {
                   4275:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4276: 	$path.=$fnamepath.'/';
                   4277:     }
1.259     www      4278:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4279:     my $count;
                   4280:     for ($count=4;$count<=$#parts;$count++) {
                   4281:         $filepath.="/$parts[$count]";
                   4282:         if ((-e $filepath)!=1) {
                   4283: 	    mkdir($filepath,0777);
                   4284:         }
                   4285:     }
1.984     neumanie 4286: 
1.258     www      4287: # Save the file
                   4288:     {
1.1359    raeburn  4289: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4290: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4291: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4292: 	    return '/adm/notfound.html';
                   4293: 	}
1.1090    raeburn  4294:         if ($context eq 'overwrite') {
1.1117    foxr     4295:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4296:             my $target = $filepath.'/'.$file;
                   4297:             if (-e $source) {
                   4298:                 my @info = stat($source);
                   4299:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4300:                     unless (&File::Copy::move($source,$target)) {
                   4301:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4302:                         return "Moving from $source failed";
                   4303:                     }
                   4304:                 } else {
                   4305:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4306:                 }
                   4307:             } else {
                   4308:                 return "Temporary file: $source missing";
                   4309:             }
                   4310:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4311: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4312: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4313: 	    return '/adm/notfound.html';
                   4314: 	}
1.570     albertel 4315: 	close(FH);
1.1051    raeburn  4316:         if ($resizewidth && $resizeheight) {
                   4317:             my $mm = new File::MMagic;
                   4318:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4319:             if ($mime_type =~ m{^image/}) {
                   4320: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4321:             }  
1.977     amueller 4322: 	}
1.258     www      4323:     }
1.1152    raeburn  4324:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4325:         if (ref($mimetype)) {
                   4326:             if ($$mimetype eq '') {
                   4327:                 my $mm = new File::MMagic;
                   4328:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4329:                 $$mimetype = $type;
                   4330:             }
                   4331:         }
                   4332:     }
1.1401    raeburn  4333:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4334:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4335:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4336:                                                        $allfiles,$codebase);
                   4337:             unless ($parse_result eq 'ok') {
                   4338:                 &logthis('Failed to parse '.$filepath.$file.
                   4339: 	   	         ' for embedded media: '.$parse_result); 
                   4340:             }
1.637     raeburn  4341:         }
1.1401    raeburn  4342:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4343:         my $format = $env{'form.scantron_format'};
                   4344:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4345:     }
1.860     raeburn  4346:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4347:         my $input = $filepath.'/'.$file;
                   4348:         my $output = $filepath.'/'.'tn-'.$file;
                   4349:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4350:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4351:         system({$args[0]} @args);
1.860     raeburn  4352:         if (-e $filepath.'/'.'tn-'.$file) {
                   4353:             $fetchthumb  = 1; 
                   4354:         }
                   4355:     }
1.858     raeburn  4356:  
1.259     www      4357: # Notify homeserver to grep it
                   4358: #
1.984     neumanie 4359:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4360:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4361:     if ($fetchresult eq 'ok') {
1.860     raeburn  4362:         if ($fetchthumb) {
                   4363:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4364:             if ($thumbresult ne 'ok') {
                   4365:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4366:                          $docuhome.': '.$thumbresult);
                   4367:             }
                   4368:         }
1.259     www      4369: #
1.258     www      4370: # Return the URL to it
1.494     albertel 4371:         return '/uploaded/'.$path.$file;
1.263     www      4372:     } else {
1.494     albertel 4373:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4374: 		 ': '.$fetchresult);
1.263     www      4375:         return '/adm/notfound.html';
1.858     raeburn  4376:     }
1.493     albertel 4377: }
                   4378: 
1.637     raeburn  4379: sub extract_embedded_items {
1.961     raeburn  4380:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4381:     my @state = ();
1.1164    raeburn  4382:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4383:     my %javafiles = (
                   4384:                       codebase => '',
                   4385:                       code => '',
                   4386:                       archive => ''
                   4387:                     );
                   4388:     my %mediafiles = (
                   4389:                       src => '',
                   4390:                       movie => '',
                   4391:                      );
1.648     raeburn  4392:     my $p;
                   4393:     if ($content) {
                   4394:         $p = HTML::LCParser->new($content);
                   4395:     } else {
1.961     raeburn  4396:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4397:     }
1.641     albertel 4398:     while (my $t=$p->get_token()) {
1.640     albertel 4399: 	if ($t->[0] eq 'S') {
                   4400: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4401: 	    push(@state, $tagname);
1.648     raeburn  4402:             if (lc($tagname) eq 'allow') {
                   4403:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4404:             }
1.640     albertel 4405: 	    if (lc($tagname) eq 'img') {
                   4406: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4407: 	    }
1.886     albertel 4408: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4409:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4410:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4411:                 }
1.886     albertel 4412: 	    }
1.645     raeburn  4413:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4414:                 my $src;
1.645     raeburn  4415:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4416:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4417:                 } else {
1.1164    raeburn  4418:                     if ($attr->{'src'} ne '') {
                   4419:                         $src = $attr->{'src'};
                   4420:                         &add_filetype($allfiles,$src,'src');
                   4421:                     }
                   4422:                 }
                   4423:                 my $text = $p->get_trimmed_text();
                   4424:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4425:                     my @swfargs = split(/,/,$1);
                   4426:                     foreach my $item (@swfargs) {
                   4427:                         $item =~ s/["']//g;
                   4428:                         $item =~ s/^\s+//;
                   4429:                         $item =~ s/\s+$//;
                   4430:                     }
                   4431:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4432:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4433:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4434:                         } else {
                   4435:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4436:                         }
                   4437:                     }
1.645     raeburn  4438:                 }
                   4439:             }
                   4440:             if (lc($tagname) eq 'link') {
                   4441:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4442:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4443:                 }
                   4444:             }
1.640     albertel 4445: 	    if (lc($tagname) eq 'object' ||
                   4446: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4447: 		foreach my $item (keys(%javafiles)) {
                   4448: 		    $javafiles{$item} = '';
                   4449: 		}
1.1164    raeburn  4450:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4451:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4452:                 }
1.640     albertel 4453: 	    }
                   4454: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4455: 		my $name = lc($attr->{'name'});
                   4456: 		foreach my $item (keys(%javafiles)) {
                   4457: 		    if ($name eq $item) {
                   4458: 			$javafiles{$item} = $attr->{'value'};
                   4459: 			last;
                   4460: 		    }
                   4461: 		}
1.1164    raeburn  4462:                 my $pathfrom;
1.640     albertel 4463: 		foreach my $item (keys(%mediafiles)) {
                   4464: 		    if ($name eq $item) {
1.1164    raeburn  4465:                         $pathfrom = $attr->{'value'};
                   4466:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4467: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4468: 			last;
                   4469: 		    }
                   4470: 		}
1.1164    raeburn  4471:                 if ($name eq 'flashvars') {
                   4472:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4473:                 }
                   4474:                 if ($pathfrom ne '') {
                   4475:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4476:                                          $pathfrom);
                   4477:                 }
1.640     albertel 4478: 	    }
                   4479: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4480: 		foreach my $item (keys(%javafiles)) {
                   4481: 		    if ($attr->{$item}) {
                   4482: 			$javafiles{$item} = $attr->{$item};
                   4483: 			last;
                   4484: 		    }
                   4485: 		}
                   4486: 		foreach my $item (keys(%mediafiles)) {
                   4487: 		    if ($attr->{$item}) {
                   4488: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4489: 			last;
                   4490: 		    }
                   4491: 		}
1.1164    raeburn  4492:                 if (lc($tagname) eq 'embed') {
                   4493:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4494:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4495:                                              $attr->{'src'});
                   4496:                     }
                   4497:                 }
1.640     albertel 4498: 	    }
1.1243    raeburn  4499:             if (lc($tagname) eq 'iframe') {
                   4500:                 my $src = $attr->{'src'} ;
                   4501:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4502:                     &add_filetype($allfiles,$src,'src');
                   4503:                 } elsif ($src =~ m{^/}) {
                   4504:                     if ($env{'request.course.id'}) {
                   4505:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4506:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4507:                         my $url = &hreflocation('',$fullpath);
                   4508:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4509:                             my $relpath = $1;
                   4510:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4511:                                 &add_filetype($allfiles,$1,'src');
                   4512:                             }
                   4513:                         }
                   4514:                     }
                   4515:                 }
                   4516:             }
1.1164    raeburn  4517:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4518:                 pop(@state);
1.1164    raeburn  4519:             }
1.640     albertel 4520: 	} elsif ($t->[0] eq 'E') {
                   4521: 	    my ($tagname) = ($t->[1]);
                   4522: 	    if ($javafiles{'codebase'} ne '') {
                   4523: 		$javafiles{'codebase'} .= '/';
                   4524: 	    }  
                   4525: 	    if (lc($tagname) eq 'applet' ||
                   4526: 		lc($tagname) eq 'object' ||
                   4527: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4528: 		) {
                   4529: 		foreach my $item (keys(%javafiles)) {
                   4530: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4531: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4532: 			&add_filetype($allfiles,$file,$item);
                   4533: 		    }
                   4534: 		}
                   4535: 	    } 
                   4536: 	    pop @state;
                   4537: 	}
                   4538:     }
1.1164    raeburn  4539:     foreach my $id (sort(keys(%flashvars))) {
                   4540:         if ($shockwave{$id} ne '') {
                   4541:             my @pairs = split(/\&/,$flashvars{$id});
                   4542:             foreach my $pair (@pairs) {
                   4543:                 my ($key,$value) = split(/\=/,$pair);
                   4544:                 if ($key eq 'thumb') {
                   4545:                     &add_filetype($allfiles,$value,$key);
                   4546:                 } elsif ($key eq 'content') {
                   4547:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4548:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4549:                     if ($ext ne '') {
                   4550:                         &add_filetype($allfiles,$path.$value,$ext);
                   4551:                     }
                   4552:                 }
                   4553:             }
                   4554:         }
                   4555:     }
1.637     raeburn  4556:     return 'ok';
                   4557: }
                   4558: 
1.639     albertel 4559: sub add_filetype {
                   4560:     my ($allfiles,$file,$type)=@_;
                   4561:     if (exists($allfiles->{$file})) {
                   4562: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4563: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4564: 	}
                   4565:     } else {
                   4566: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4567:     }
                   4568: }
                   4569: 
1.1164    raeburn  4570: sub embedded_dependency {
                   4571:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4572:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4573:         if (($identifier ne '') &&
                   4574:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4575:             ($pathfrom ne '')) {
                   4576:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4577:             foreach my $dep (@{$related->{$identifier}}) {
                   4578:                 &add_filetype($allfiles,$path.$dep,'object');
                   4579:             }
                   4580:         }
                   4581:     }
                   4582:     return;
                   4583: }
                   4584: 
1.1401    raeburn  4585: sub bubblesheet_converter {
                   4586:     my ($cdom,$fullpath,$config,$format) = @_;
                   4587:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4588:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4589:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4590:         my (%csvcols,%csvoptions);
                   4591:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4592:             %csvcols = %{$config->{'fields'}};
                   4593:         }
                   4594:         if (ref($config->{'options'}) eq 'HASH') {
                   4595:             %csvoptions = %{$config->{'options'}};
                   4596:         }
1.1401    raeburn  4597:         my %csvbynum = reverse(%csvcols);
                   4598:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4599:         if (keys(%scantronconf)) {
                   4600:             my %bynum = (
                   4601:                           $scantronconf{CODEstart} => 'CODEstart',
                   4602:                           $scantronconf{IDstart}   => 'IDstart',
                   4603:                           $scantronconf{PaperID}   => 'PaperID',
                   4604:                           $scantronconf{FirstName} => 'FirstName',
                   4605:                           $scantronconf{LastName}  => 'LastName',
                   4606:                           $scantronconf{Qstart}    => 'Qstart',
                   4607:                         );
                   4608:             my @ordered;
                   4609:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4610:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4611:             }
                   4612:             my %mapstart = (
                   4613:                               CODEstart => 'CODE',
                   4614:                               IDstart   => 'ID',
                   4615:                               PaperID   => 'PaperID',
                   4616:                               FirstName => 'FirstName',
                   4617:                               LastName  => 'LastName',
                   4618:                               Qstart    => 'FirstQuestion',
                   4619:                            );
                   4620:             my %maplength = (
                   4621:                               CODEstart => 'CODElength',
                   4622:                               IDstart   => 'IDlength',
                   4623:                               PaperID   => 'PaperIDlength',
                   4624:                               FirstName => 'FirstNamelength',
                   4625:                               LastName  => 'LastNamelength',
                   4626:             );
                   4627:             if (open(my $fh,'<',$fullpath)) {
                   4628:                 my $output;
1.1403    raeburn  4629:                 my %lettdig = &letter_to_digits();
                   4630:                 my %diglett = reverse(%lettdig);
                   4631:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4632:                 my $num = 0;
1.1401    raeburn  4633:                 while (my $line=<$fh>) {
1.1404    raeburn  4634:                     $num ++;
                   4635:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4636:                     $line =~ s{[\r\n]+$}{};
                   4637:                     my %found;
                   4638:                     my @values = split(/,/,$line);
                   4639:                     my ($qstart,$record);
                   4640:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4641:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4642:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4643:                             if ($values[$i] eq '') {
                   4644:                                 $values[$i] = $scantronconf{'Qoff'};
                   4645:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4646:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4647:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4648:                                 }
                   4649:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4650:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4651:                                     $values[$i] = $diglett{$values[$i]};
                   4652:                                 }
                   4653:                             } else {
                   4654:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4655:                                     my $digit;
                   4656:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4657:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4658:                                         if ($values[$i] eq 'J') {
                   4659:                                             $digit += $numletts;
                   4660:                                         }
                   4661:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4662:                                         $digit = $values[$i]-1;
                   4663:                                         if ($values[$i] eq '0') {
                   4664:                                             $digit += $numletts;
                   4665:                                         }
                   4666:                                     }
                   4667:                                     my $qval='';
                   4668:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4669:                                         if ($j == $digit) {
                   4670:                                             $qval .= $scantronconf{'Qon'};
                   4671:                                         } else {
                   4672:                                             $qval .= $scantronconf{'Qoff'};
                   4673:                                         }
                   4674:                                     }
                   4675:                                     $values[$i] = $qval;
                   4676:                                 }
                   4677:                             }
                   4678:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4679:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4680:                             }
                   4681:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4682:                             if ($numblank > 0) {
                   4683:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4684:                             }
1.1401    raeburn  4685:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4686:                                 $qstart = $i;
1.1403    raeburn  4687:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4688:                             } else {
1.1403    raeburn  4689:                                 $found{'FirstQuestion'} .= $values[$i];
                   4690:                             }
                   4691:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4692:                             if ($csvoptions{'rem'}) {
                   4693:                                 $values[$i] =~ s/^\s+//;
                   4694:                             }
                   4695:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4696:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4697:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4698:                                 }
                   4699:                             }
                   4700:                             $found{$csvbynum{$i}} = $values[$i];
                   4701:                         }
                   4702:                     }
                   4703:                     foreach my $item (@ordered) {
                   4704:                         my $currlength = 1+length($record);
                   4705:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4706:                         if ($numspaces > 0) {
                   4707:                             $record .= (' ' x $numspaces);
                   4708:                         }
                   4709:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4710:                             unless ($item eq 'Qstart') {
                   4711:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4712:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4713:                                 }
                   4714:                             }
                   4715:                             $record .= $found{$mapstart{$item}};
                   4716:                         }
                   4717:                     }
                   4718:                     $output .= "$record\n";
                   4719:                 }
                   4720:                 close($fh);
                   4721:                 if ($output) {
                   4722:                     if (open(my $fh,'>',$fullpath)) {
                   4723:                         print $fh $output;
                   4724:                         close($fh);
                   4725:                     }
                   4726:                 }
                   4727:             }
                   4728:         }
                   4729:         return;
                   4730:     }
                   4731: }
                   4732: 
1.1403    raeburn  4733: sub letter_to_digits {
                   4734:     my %lettdig = (
                   4735:                     A => 1,
                   4736:                     B => 2,
                   4737:                     C => 3,
                   4738:                     D => 4,
                   4739:                     E => 5,
                   4740:                     F => 6,
                   4741:                     G => 7,
                   4742:                     H => 8,
                   4743:                     I => 9,
                   4744:                     J => 0,
                   4745:                   );
                   4746:     return %lettdig;
                   4747: }
                   4748: 
1.1401    raeburn  4749: sub get_scantron_config {
                   4750:     my ($which,$cdom) = @_;
                   4751:     my @lines = &get_scantronformat_file($cdom);
                   4752:     my %config;
                   4753:     #FIXME probably should move to XML it has already gotten a bit much now
                   4754:     foreach my $line (@lines) {
                   4755:         my ($name,$descrip)=split(/:/,$line);
                   4756:         if ($name ne $which ) { next; }
                   4757:         chomp($line);
                   4758:         my @config=split(/:/,$line);
                   4759:         $config{'name'}=$config[0];
                   4760:         $config{'description'}=$config[1];
                   4761:         $config{'CODElocation'}=$config[2];
                   4762:         $config{'CODEstart'}=$config[3];
                   4763:         $config{'CODElength'}=$config[4];
                   4764:         $config{'IDstart'}=$config[5];
                   4765:         $config{'IDlength'}=$config[6];
                   4766:         $config{'Qstart'}=$config[7];
                   4767:         $config{'Qlength'}=$config[8];
                   4768:         $config{'Qoff'}=$config[9];
                   4769:         $config{'Qon'}=$config[10];
                   4770:         $config{'PaperID'}=$config[11];
                   4771:         $config{'PaperIDlength'}=$config[12];
                   4772:         $config{'FirstName'}=$config[13];
                   4773:         $config{'FirstNamelength'}=$config[14];
                   4774:         $config{'LastName'}=$config[15];
                   4775:         $config{'LastNamelength'}=$config[16];
                   4776:         $config{'BubblesPerRow'}=$config[17];
                   4777:         last;
                   4778:     }
                   4779:     return %config;
                   4780: }
                   4781: 
                   4782: sub get_scantronformat_file {
                   4783:     my ($cdom) = @_;
                   4784:     if ($cdom eq '') {
                   4785:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4786:     }
                   4787:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4788:     my $gottab = 0;
                   4789:     my @lines;
                   4790:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4791:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4792:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4793:             if ($formatfile ne '-1') {
                   4794:                 @lines = split("\n",$formatfile,-1);
                   4795:                 $gottab = 1;
                   4796:             }
                   4797:         }
                   4798:     }
                   4799:     if (!$gottab) {
                   4800:         my $confname = $cdom.'-domainconfig';
                   4801:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4802:         my $formatfile = &getfile($default);
                   4803:         if ($formatfile ne '-1') {
                   4804:             @lines = split("\n",$formatfile,-1);
                   4805:             $gottab = 1;
                   4806:         }
                   4807:     }
                   4808:     if (!$gottab) {
                   4809:         my @domains = &current_machine_domains();
                   4810:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4811:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4812:                 @lines = <$fh>;
                   4813:                 close($fh);
1.1403    raeburn  4814:             }
1.1401    raeburn  4815:         } else {
                   4816:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4817:                 @lines = <$fh>;
                   4818:                 close($fh);
                   4819:             }
                   4820:         }
                   4821:     }
                   4822:     return @lines;
                   4823: }
                   4824: 
1.493     albertel 4825: sub removeuploadedurl {
1.984     neumanie 4826:     my ($url)=@_;	
                   4827:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4828:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4829: }
                   4830: 
                   4831: sub removeuserfile {
                   4832:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4833:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4834:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4835:     if ($result eq 'ok') {	
1.798     raeburn  4836:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4837:             my $metafile = $fname.'.meta';
                   4838:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4839: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4840:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4841:             my $sqlresult = 
1.823     albertel 4842:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4843:                                         'portfolio_metadata',$group,
                   4844:                                         'delete');
1.798     raeburn  4845:         }
                   4846:     }
                   4847:     return $result;
1.257     www      4848: }
1.15      www      4849: 
1.530     albertel 4850: sub mkdiruserfile {
                   4851:     my ($docuname,$docudom,$dir)=@_;
                   4852:     my $home=&homeserver($docuname,$docudom);
                   4853:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4854: }
                   4855: 
1.531     albertel 4856: sub renameuserfile {
                   4857:     my ($docuname,$docudom,$old,$new)=@_;
                   4858:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4859:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4860:                         &escape("$old").':'.&escape("$new"),$home);
                   4861:     if ($result eq 'ok') {
                   4862:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4863:             my $oldmeta = $old.'.meta';
                   4864:             my $newmeta = $new.'.meta';
                   4865:             my $metaresult = 
                   4866:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4867: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4868:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4869:             my $sqlresult = 
1.823     albertel 4870:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4871:                                         'portfolio_metadata',$group,
                   4872:                                         'delete');
1.798     raeburn  4873:         }
                   4874:     }
                   4875:     return $result;
1.531     albertel 4876: }
                   4877: 
1.14      www      4878: # ------------------------------------------------------------------------- Log
                   4879: 
                   4880: sub log {
                   4881:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4882:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4883: }
                   4884: 
                   4885: # ------------------------------------------------------------------ Course Log
1.352     www      4886: #
                   4887: # This routine flushes several buffers of non-mission-critical nature
                   4888: #
1.157     www      4889: 
                   4890: sub flushcourselogs {
1.352     www      4891:     &logthis('Flushing log buffers');
                   4892: #
                   4893: # course logs
                   4894: # This is a log of all transactions in a course, which can be used
                   4895: # for data mining purposes
                   4896: #
                   4897: # It also collects the courseid database, which lists last transaction
                   4898: # times and course titles for all courseids
                   4899: #
                   4900:     my %courseidbuffer=();
1.921     raeburn  4901:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4902:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4903: 		          &escape($courselogs{$crsid}),
                   4904: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4905: 	    delete $courselogs{$crsid};
                   4906:         } else {
                   4907:             &logthis('Failed to flush log buffer for '.$crsid);
                   4908:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4909:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4910:                         " exceeded maximum size, deleting.</font>");
                   4911:                delete $courselogs{$crsid};
                   4912:             }
1.352     www      4913:         }
1.920     raeburn  4914:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4915:             'description' => $coursedescrbuf{$crsid},
                   4916:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4917:             'type'        => $coursetypebuf{$crsid},
                   4918:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4919:         };
1.191     harris41 4920:     }
1.352     www      4921: #
                   4922: # Write course id database (reverse lookup) to homeserver of courses 
                   4923: # Is used in pickcourse
                   4924: #
1.840     albertel 4925:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4926:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4927:                                     $courseidbuffer{$crs_home},
                   4928:                                     $crs_home,'timeonly');
1.352     www      4929:     }
                   4930: #
                   4931: # File accesses
                   4932: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4933: #
1.449     matthew  4934:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4935:         if ($entry =~ /___count$/) {
                   4936:             my ($dom,$name);
1.807     albertel 4937:             ($dom,$name,undef)=
1.811     albertel 4938: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4939:             if (! defined($dom) || $dom eq '' || 
                   4940:                 ! defined($name) || $name eq '') {
1.620     albertel 4941:                 my $cid = $env{'request.course.id'};
                   4942:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4943:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4944:             }
1.450     matthew  4945:             my $value = $accesshash{$entry};
                   4946:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4947:             my %temphash=($url => $value);
1.449     matthew  4948:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4949:             if ($result eq 'ok') {
                   4950:                 delete $accesshash{$entry};
                   4951:             }
                   4952:         } else {
1.811     albertel 4953:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4954:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4955:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4956:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4957:                 delete $accesshash{$entry};
                   4958:             }
1.185     www      4959:         }
1.191     harris41 4960:     }
1.352     www      4961: #
                   4962: # Roles
                   4963: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4964: #
1.800     albertel 4965:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4966:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4967: 	    split(/\:/,$entry);
                   4968:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4969:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4970:                 $rudom,$runame) eq 'ok') {
                   4971: 	    delete $userrolehash{$entry};
                   4972:         }
                   4973:     }
1.662     raeburn  4974: #
1.1334    raeburn  4975: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4976: #
                   4977:     my %domrolebuffer = ();
1.1000    raeburn  4978:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4979:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4980:         if ($domrolebuffer{$rudom}) {
                   4981:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4982:                       '='.&escape($domainrolehash{$entry});
                   4983:         } else {
                   4984:             $domrolebuffer{$rudom}.=&escape($entry).
                   4985:                       '='.&escape($domainrolehash{$entry});
                   4986:         }
                   4987:         delete $domainrolehash{$entry};
                   4988:     }
                   4989:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4990: 	my %servers;
                   4991: 	if (defined(&domain($dom,'primary'))) {
                   4992: 	    my $primary=&domain($dom,'primary');
                   4993: 	    my $hostname=&hostname($primary);
                   4994: 	    $servers{$primary} = $hostname;
                   4995: 	} else { 
                   4996: 	    %servers = &get_servers($dom,'library');
                   4997: 	}
1.841     albertel 4998: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4999: 	    if (&reply('domroleput:'.$dom.':'.
                   5000: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5001: 		last;
                   5002: 	    } else {  
1.841     albertel 5003: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5004: 	    }
1.662     raeburn  5005:         }
                   5006:     }
1.186     www      5007:     $dumpcount++;
1.157     www      5008: }
                   5009: 
                   5010: sub courselog {
                   5011:     my $what=shift;
1.158     www      5012:     $what=time.':'.$what;
1.620     albertel 5013:     unless ($env{'request.course.id'}) { return ''; }
                   5014:     $coursedombuf{$env{'request.course.id'}}=
                   5015:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5016:     $coursenumbuf{$env{'request.course.id'}}=
                   5017:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5018:     $coursehombuf{$env{'request.course.id'}}=
                   5019:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5020:     $coursedescrbuf{$env{'request.course.id'}}=
                   5021:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5022:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5023:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5024:     $courseownerbuf{$env{'request.course.id'}}=
                   5025:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5026:     $coursetypebuf{$env{'request.course.id'}}=
                   5027:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5028:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5029: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5030:     } else {
1.620     albertel 5031: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5032:     }
1.620     albertel 5033:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5034: 	&flushcourselogs();
                   5035:     }
1.158     www      5036: }
                   5037: 
                   5038: sub courseacclog {
                   5039:     my $fnsymb=shift;
1.620     albertel 5040:     unless ($env{'request.course.id'}) { return ''; }
                   5041:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5042:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5043:         $what.=':POST';
1.583     matthew  5044:         # FIXME: Probably ought to escape things....
1.800     albertel 5045: 	foreach my $key (keys(%env)) {
                   5046:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5047:                 my $formitem = $1;
                   5048:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5049:                     $what.=':'.$formitem.'='.$env{$key};
                   5050:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5051:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5052:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5053:                     } else {
                   5054:                         $what.=':'.$formitem.'='.$env{$key};
                   5055:                     }
1.975     raeburn  5056:                 }
1.158     www      5057:             }
1.191     harris41 5058:         }
1.583     matthew  5059:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5060:         # FIXME: We should not be depending on a form parameter that someone
                   5061:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5062:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5063:             $what.= ':POST';
                   5064:             # FIXME: Probably ought to escape things....
                   5065:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5066:                                  'crsdiscuss') {
1.620     albertel 5067:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5068:             }
                   5069:         }
1.158     www      5070:     }
                   5071:     &courselog($what);
1.149     www      5072: }
                   5073: 
1.185     www      5074: sub countacc {
                   5075:     my $url=&declutter(shift);
1.458     matthew  5076:     return if (! defined($url) || $url eq '');
1.620     albertel 5077:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5078: #
                   5079: # Mark that this url was used in this course
                   5080: #
1.620     albertel 5081:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5082: #
                   5083: # Increase the access count for this resource in this child process
                   5084: #
1.281     www      5085:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5086:     $accesshash{$key}++;
1.185     www      5087: }
1.349     www      5088: 
1.361     www      5089: sub linklog {
                   5090:     my ($from,$to)=@_;
                   5091:     $from=&declutter($from);
                   5092:     $to=&declutter($to);
                   5093:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5094:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5095: }
1.1160    www      5096: 
                   5097: sub statslog {
                   5098:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5099:     if ($users<2) { return; }
                   5100:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5101:             'course'       => $env{'request.course.id'},
                   5102:             'sections'     => '"all"',
                   5103:             'num_students' => $users,
                   5104:             'part'         => $part,
                   5105:             'symb'         => $symb,
                   5106:             'mean_tries'   => $av_attempts,
                   5107:             'deg_of_diff'  => $degdiff});
                   5108:     foreach my $key (keys(%dynstore)) {
                   5109:         $accesshash{$key}=$dynstore{$key};
                   5110:     }
                   5111: }
1.361     www      5112:   
1.349     www      5113: sub userrolelog {
                   5114:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5115:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5116:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5117:        $userrolehash
                   5118:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5119:                     =$tend.':'.$tstart;
1.662     raeburn  5120:     }
1.1169    droeschl 5121:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5122:        $userrolehash
                   5123:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5124:                     =$tend.':'.$tstart;
                   5125:     }
1.1334    raeburn  5126:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5127:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5128:        $domainrolehash
                   5129:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5130:                     = $tend.':'.$tstart;
                   5131:     }
1.351     www      5132: }
                   5133: 
1.957     raeburn  5134: sub courserolelog {
                   5135:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5136:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5137:         my $cdom = $1;
                   5138:         my $cnum = $2;
                   5139:         my $sec = $3;
                   5140:         my $namespace = 'rolelog';
                   5141:         my %storehash = (
                   5142:                            role    => $trole,
                   5143:                            start   => $tstart,
                   5144:                            end     => $tend,
                   5145:                            selfenroll => $selfenroll,
                   5146:                            context    => $context,
                   5147:                         );
                   5148:         if ($trole eq 'gr') {
                   5149:             $namespace = 'groupslog';
                   5150:             $storehash{'group'} = $sec;
                   5151:         } else {
                   5152:             $storehash{'section'} = $sec;
                   5153:         }
1.1188    raeburn  5154:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5155:                    $domain,$cnum,$cdom);
1.1184    raeburn  5156:         if (($trole ne 'st') || ($sec ne '')) {
                   5157:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5158:         }
                   5159:     }
                   5160:     return;
                   5161: }
                   5162: 
1.1184    raeburn  5163: sub domainrolelog {
                   5164:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5165:     if ($area =~ m{^/($match_domain)/$}) {
                   5166:         my $cdom = $1;
                   5167:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5168:         my $namespace = 'rolelog';
                   5169:         my %storehash = (
                   5170:                            role    => $trole,
                   5171:                            start   => $tstart,
                   5172:                            end     => $tend,
                   5173:                            context => $context,
                   5174:                         );
1.1188    raeburn  5175:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5176:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5177:     }
                   5178:     return;
                   5179: 
                   5180: }
                   5181: 
                   5182: sub coauthorrolelog {
                   5183:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5184:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5185:         my $audom = $1;
                   5186:         my $auname = $2;
                   5187:         my $namespace = 'rolelog';
                   5188:         my %storehash = (
                   5189:                            role    => $trole,
                   5190:                            start   => $tstart,
                   5191:                            end     => $tend,
                   5192:                            context => $context,
                   5193:                         );
1.1188    raeburn  5194:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5195:                    $domain,$auname,$audom);
1.1184    raeburn  5196:     }
                   5197:     return;
                   5198: }
                   5199: 
1.351     www      5200: sub get_course_adv_roles {
1.948     raeburn  5201:     my ($cid,$codes) = @_;
1.620     albertel 5202:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5203:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5204:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5205:     my %nothide=();
1.800     albertel 5206:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5207:         if ($user !~ /:/) {
                   5208: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5209:         } else {
                   5210:             $nothide{$user}=1;
                   5211:         }
1.470     www      5212:     }
1.1219    raeburn  5213:     my @possdoms = ($coursehash{'domain'});
                   5214:     if ($coursehash{'checkforpriv'}) {
                   5215:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5216:     }
1.351     www      5217:     my %returnhash=();
                   5218:     my %dumphash=
                   5219:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5220:     my $now=time;
1.997     raeburn  5221:     my %privileged;
1.1000    raeburn  5222:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5223: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5224:         if (($tstart) && ($tstart<0)) { next; }
                   5225:         if (($tend) && ($tend<$now)) { next; }
                   5226:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5227:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5228: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5229:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5230:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5231: 	if ($role eq 'cr') { next; }
1.948     raeburn  5232:         if ($codes) {
                   5233:             if ($section) { $role .= ':'.$section; }
                   5234:             if ($returnhash{$role}) {
                   5235:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5236:             } else {
                   5237:                 $returnhash{$role}=$username.':'.$domain;
                   5238:             }
1.351     www      5239:         } else {
1.988     raeburn  5240:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5241:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5242:             if ($returnhash{$key}) {
                   5243: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5244:             } else {
                   5245:                 $returnhash{$key}=$username.':'.$domain;
                   5246:             }
1.351     www      5247:         }
1.948     raeburn  5248:     }
1.400     www      5249:     return %returnhash;
                   5250: }
                   5251: 
                   5252: sub get_my_roles {
1.937     raeburn  5253:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5254:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5255:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5256:     my (%dumphash,%nothide);
1.1086    raeburn  5257:     if ($context eq 'userroles') {
1.1166    raeburn  5258:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5259:     } else {
1.1219    raeburn  5260:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5261:         if ($hidepriv) {
                   5262:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5263:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5264:                 if ($user !~ /:/) {
                   5265:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5266:                 } else {
                   5267:                     $nothide{$user} = 1;
                   5268:                 }
                   5269:             }
                   5270:         }
1.858     raeburn  5271:     }
1.400     www      5272:     my %returnhash=();
                   5273:     my $now=time;
1.999     raeburn  5274:     my %privileged;
1.800     albertel 5275:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5276:         my ($role,$tend,$tstart);
                   5277:         if ($context eq 'userroles') {
1.1149    raeburn  5278:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5279: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5280:         } else {
                   5281:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5282:         }
1.400     www      5283:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5284:         my $status = 'active';
1.939     raeburn  5285:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5286:             $status = 'previous';
                   5287:         } 
                   5288:         if (($tstart) && ($now<$tstart)) {
                   5289:             $status = 'future';
                   5290:         }
                   5291:         if (ref($types) eq 'ARRAY') {
                   5292:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5293:                 next;
                   5294:             } 
                   5295:         } else {
                   5296:             if ($status ne 'active') {
                   5297:                 next;
                   5298:             }
                   5299:         }
1.867     raeburn  5300:         my ($rolecode,$username,$domain,$section,$area);
                   5301:         if ($context eq 'userroles') {
1.1186    raeburn  5302:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5303:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5304:         } else {
                   5305:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5306:         }
1.832     raeburn  5307:         if (ref($roledoms) eq 'ARRAY') {
                   5308:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5309:                 next;
                   5310:             }
                   5311:         }
                   5312:         if (ref($roles) eq 'ARRAY') {
                   5313:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5314:                 if ($role =~ /^cr\//) {
                   5315:                     if (!grep(/^cr$/,@{$roles})) {
                   5316:                         next;
                   5317:                     }
1.1104    raeburn  5318:                 } elsif ($role =~ /^gr\//) {
                   5319:                     if (!grep(/^gr$/,@{$roles})) {
                   5320:                         next;
                   5321:                     }
1.922     raeburn  5322:                 } else {
                   5323:                     next;
                   5324:                 }
1.832     raeburn  5325:             }
1.867     raeburn  5326:         }
1.937     raeburn  5327:         if ($hidepriv) {
1.1219    raeburn  5328:             my @privroles = ('dc','su');
1.999     raeburn  5329:             if ($context eq 'userroles') {
1.1219    raeburn  5330:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5331:             } else {
1.1219    raeburn  5332:                 my $possdoms = [$domain];
                   5333:                 if (ref($roledoms) eq 'ARRAY') {
                   5334:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5335:                 }
1.1219    raeburn  5336:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5337:                     if (!$nothide{$username.':'.$domain}) {
                   5338:                         next;
                   5339:                     }
                   5340:                 }
1.937     raeburn  5341:             }
                   5342:         }
1.933     raeburn  5343:         if ($withsec) {
                   5344:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5345:                 $tstart.':'.$tend;
                   5346:         } else {
                   5347:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5348:         }
1.832     raeburn  5349:     }
1.373     www      5350:     return %returnhash;
1.399     www      5351: }
                   5352: 
1.1333    raeburn  5353: sub get_all_adhocroles {
                   5354:     my ($dom) = @_;
                   5355:     my @roles_by_num = ();
                   5356:     my %domdefaults = &get_domain_defaults($dom);
                   5357:     my (%description,%access_in_dom,%access_info);
                   5358:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5359:         my $count = 0;
                   5360:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5361:         my %ordered;
                   5362:         foreach my $role (sort(keys(%domcurrent))) {
                   5363:             my ($order,$desc,$access_in_dom);
                   5364:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5365:                 $order = $domcurrent{$role}{'order'};
                   5366:                 $desc = $domcurrent{$role}{'desc'};
                   5367:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5368:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5369:             }
                   5370:             if ($order eq '') {
                   5371:                 $order = $count;
                   5372:             }
                   5373:             $ordered{$order} = $role;
                   5374:             if ($desc ne '') {
                   5375:                 $description{$role} = $desc;
                   5376:             } else {
                   5377:                 $description{$role}= $role;
                   5378:             }
                   5379:             $count++;
                   5380:         }
                   5381:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5382:             push(@roles_by_num,$ordered{$item});
                   5383:         }
                   5384:     }
                   5385:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5386: }
                   5387: 
1.1332    raeburn  5388: sub get_my_adhocroles {
1.1333    raeburn  5389:     my ($cid,$checkreg) = @_;
                   5390:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5391:     if ($env{'request.course.id'} eq $cid) {
                   5392:         $cdom = $env{'course.'.$cid.'.domain'};
                   5393:         $cnum = $env{'course.'.$cid.'.num'};
                   5394:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5395:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5396:         $cdom = $1;
                   5397:         $cnum = $2;
                   5398:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5399:                                      $cdom,$cnum);
                   5400:     }
                   5401:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5402:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5403:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5404:         if ($rosterhash{$user} ne '') {
                   5405:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5406:             return ([],{}) if ($type eq 'auto');
                   5407:         }
                   5408:     }
                   5409:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5410:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5411:             my $then=$env{'user.login.time'};
                   5412:             my $update=$env{'user.update.time'};
1.1335    raeburn  5413:             if (!$update) {
                   5414:                 $update = $then;
                   5415:             }
                   5416:             my @liveroles;
1.1334    raeburn  5417:             foreach my $role ('dh','da') {
                   5418:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5419:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5420:                     my $limit = $update;
                   5421:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5422:                         $limit = $then;
                   5423:                     }
1.1335    raeburn  5424:                     my $activerole = 1;
                   5425:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5426:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5427:                     if ($activerole) {
                   5428:                         push(@liveroles,$role);
                   5429:                     }
1.1334    raeburn  5430:                 }
1.1332    raeburn  5431:             }
1.1335    raeburn  5432:             if (@liveroles) {
1.1332    raeburn  5433:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5434:                     my ($accessref,$accessinfo,%access_in_dom);
                   5435:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5436:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5437:                         if (@{$roles_by_num}) {
1.1332    raeburn  5438:                             my %settings;
                   5439:                             if ($env{'request.course.id'} eq $cid) {
                   5440:                                 foreach my $envkey (keys(%env)) {
                   5441:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5442:                                         $settings{$1} = $env{$envkey};
                   5443:                                     }
                   5444:                                 }
                   5445:                             } else {
                   5446:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5447:                             }
                   5448:                             my %setincrs;
                   5449:                             if ($settings{'internal.adhocaccess'}) {
                   5450:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5451:                             }
                   5452:                             my @statuses;
                   5453:                             if ($env{'environment.inststatus'}) {
                   5454:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5455:                             }
                   5456:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5457:                             if (ref($accessref) eq 'HASH') {
                   5458:                                 %access_in_dom = %{$accessref};
                   5459:                             }
                   5460:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5461:                                 my ($curraccess,@okstatus,@personnel);
                   5462:                                 if ($setincrs{$role}) {
                   5463:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5464:                                     if ($curraccess eq 'status') {
                   5465:                                         @okstatus = split(/\&/,$rest);
                   5466:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5467:                                         @personnel = split(/\&/,$rest);
                   5468:                                     }
                   5469:                                 } else {
                   5470:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5471:                                     if (ref($accessinfo) eq 'HASH') {
                   5472:                                         if ($curraccess eq 'status') {
                   5473:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5474:                                                 @okstatus = @{$accessinfo->{$role}};
                   5475:                                             }
                   5476:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5477:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5478:                                                 @personnel = @{$accessinfo->{$role}};
                   5479:                                             }
1.1332    raeburn  5480:                                         }
                   5481:                                     }
                   5482:                                 }
                   5483:                                 if ($curraccess eq 'none') {
                   5484:                                     next;
                   5485:                                 } elsif ($curraccess eq 'all') {
                   5486:                                     push(@possroles,$role);
1.1336    raeburn  5487:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5488:                                     if (grep(/^dh$/,@liveroles)) {
                   5489:                                         push(@possroles,$role);
                   5490:                                     } else {
                   5491:                                         next;
                   5492:                                     }
1.1336    raeburn  5493:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5494:                                     if (grep(/^da$/,@liveroles)) {
                   5495:                                         push(@possroles,$role);
                   5496:                                     } else {
                   5497:                                         next;
                   5498:                                     }
1.1332    raeburn  5499:                                 } elsif ($curraccess eq 'status') {
                   5500:                                     if (@okstatus) {
                   5501:                                         if (!@statuses) {
                   5502:                                             if (grep(/^default$/,@okstatus)) {
                   5503:                                                 push(@possroles,$role);
                   5504:                                             }
                   5505:                                         } else {
                   5506:                                             foreach my $status (@okstatus) {
                   5507:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5508:                                                     push(@possroles,$role);
                   5509:                                                     last;
                   5510:                                                 }
                   5511:                                             }
                   5512:                                         }
                   5513:                                     }
                   5514:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5515:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5516:                                         if ($curraccess eq 'exc') {
                   5517:                                             push(@possroles,$role);
                   5518:                                         }
                   5519:                                     } elsif ($curraccess eq 'inc') {
                   5520:                                         push(@possroles,$role);
                   5521:                                     }
                   5522:                                 }
                   5523:                             }
                   5524:                         }
                   5525:                     }
                   5526:                 }
                   5527:             }
                   5528:         }
                   5529:     }
1.1333    raeburn  5530:     unless (ref($description) eq 'HASH') {
                   5531:         if (ref($roles_by_num) eq 'ARRAY') {
                   5532:             my %desc;
                   5533:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5534:             $description = \%desc;
                   5535:         } else {
                   5536:             $description = {};
                   5537:         }
                   5538:     }
                   5539:     return (\@possroles,$description);
1.1332    raeburn  5540: }
                   5541: 
1.399     www      5542: # ----------------------------------------------------- Frontpage Announcements
                   5543: #
                   5544: #
                   5545: 
                   5546: sub postannounce {
                   5547:     my ($server,$text)=@_;
1.844     albertel 5548:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5549:     unless ($text=~/\w/) { $text=''; }
                   5550:     return &reply('setannounce:'.&escape($text),$server);
                   5551: }
                   5552: 
                   5553: sub getannounce {
1.448     albertel 5554: 
1.1359    raeburn  5555:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5556: 	my $announcement='';
1.800     albertel 5557: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5558: 	close($fh);
1.399     www      5559: 	if ($announcement=~/\w/) { 
                   5560: 	    return 
                   5561:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5562:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5563: 	} else {
                   5564: 	    return '';
                   5565: 	}
                   5566:     } else {
                   5567: 	return '';
                   5568:     }
1.351     www      5569: }
1.353     www      5570: 
                   5571: # ---------------------------------------------------------- Course ID routines
                   5572: # Deal with domain's nohist_courseid.db files
                   5573: #
                   5574: 
                   5575: sub courseidput {
1.921     raeburn  5576:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5577:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5578:     my $outcome;
                   5579:     if ($caller eq 'timeonly') {
                   5580:         my $cids = '';
                   5581:         foreach my $item (keys(%$storehash)) {
                   5582:             $cids.=&escape($item).'&';
                   5583:         }
                   5584:         $cids=~s/\&$//;
                   5585:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5586:                           $coursehome);       
                   5587:     } else {
                   5588:         my $items = '';
                   5589:         foreach my $item (keys(%$storehash)) {
                   5590:             $items.= &escape($item).'='.
                   5591:                      &freeze_escape($$storehash{$item}).'&';
                   5592:         }
                   5593:         $items=~s/\&$//;
                   5594:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5595:                           $coursehome);
1.918     raeburn  5596:     }
                   5597:     if ($outcome eq 'unknown_cmd') {
                   5598:         my $what;
                   5599:         foreach my $cid (keys(%$storehash)) {
                   5600:             $what .= &escape($cid).'=';
1.921     raeburn  5601:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5602:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5603:             }
                   5604:             $what =~ s/\:$/&/;
                   5605:         }
                   5606:         $what =~ s/\&$//;  
                   5607:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5608:     } else {
                   5609:         return $outcome;
                   5610:     }
1.353     www      5611: }
                   5612: 
                   5613: sub courseiddump {
1.921     raeburn  5614:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5615:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5616:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5617:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5618:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5619:     my $as_hash = 1;
                   5620:     my %returnhash;
                   5621:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5622:     my %libserv = &all_library();
                   5623:     foreach my $tryserver (keys(%libserv)) {
                   5624:         if ( (  $hostidflag == 1 
                   5625: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5626: 	     || (!defined($hostidflag)) ) {
                   5627: 
1.918     raeburn  5628: 	    if (($domfilter eq '') ||
                   5629: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5630:                 my $rep;
                   5631:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5632:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5633:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5634:                                 &escape($descfilter), &escape($instcodefilter), 
                   5635:                                 &escape($ownerfilter), &escape($coursefilter),
                   5636:                                 &escape($typefilter), &escape($regexp_ok), 
                   5637:                                 $as_hash, &escape($selfenrollonly), 
                   5638:                                 &escape($catfilter), $showhidden, $caller, 
                   5639:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5640:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5641:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5642:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5643:                 } else {
                   5644:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5645:                              $sincefilter.':'.&escape($descfilter).':'.
                   5646:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5647:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5648:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5649:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5650:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5651:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5652:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5653:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5654:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5655:                 }
                   5656:                      
1.918     raeburn  5657:                 my @pairs=split(/\&/,$rep);
                   5658:                 foreach my $item (@pairs) {
                   5659:                     my ($key,$value)=split(/\=/,$item,2);
                   5660:                     $key = &unescape($key);
                   5661:                     next if ($key =~ /^error: 2 /);
                   5662:                     my $result = &thaw_unescape($value);
                   5663:                     if (ref($result) eq 'HASH') {
                   5664:                         $returnhash{$key}=$result;
                   5665:                     } else {
1.921     raeburn  5666:                         my @responses = split(/:/,$value);
                   5667:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5668:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5669:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5670:                         }
1.1008    raeburn  5671:                     }
1.353     www      5672:                 }
                   5673:             }
                   5674:         }
                   5675:     }
                   5676:     return %returnhash;
                   5677: }
                   5678: 
1.1055    raeburn  5679: sub courselastaccess {
                   5680:     my ($cdom,$cnum,$hostidref) = @_;
                   5681:     my %returnhash;
                   5682:     if ($cdom && $cnum) {
                   5683:         my $chome = &homeserver($cnum,$cdom);
                   5684:         if ($chome ne 'no_host') {
                   5685:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5686:             &extract_lastaccess(\%returnhash,$rep);
                   5687:         }
                   5688:     } else {
                   5689:         if (!$cdom) { $cdom=''; }
                   5690:         my %libserv = &all_library();
                   5691:         foreach my $tryserver (keys(%libserv)) {
                   5692:             if (ref($hostidref) eq 'ARRAY') {
                   5693:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5694:             } 
                   5695:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5696:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5697:                 &extract_lastaccess(\%returnhash,$rep);
                   5698:             }
                   5699:         }
                   5700:     }
                   5701:     return %returnhash;
                   5702: }
                   5703: 
                   5704: sub extract_lastaccess {
                   5705:     my ($returnhash,$rep) = @_;
                   5706:     if (ref($returnhash) eq 'HASH') {
                   5707:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5708:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5709:                  $rep eq '') {
                   5710:             my @pairs=split(/\&/,$rep);
                   5711:             foreach my $item (@pairs) {
                   5712:                 my ($key,$value)=split(/\=/,$item,2);
                   5713:                 $key = &unescape($key);
                   5714:                 next if ($key =~ /^error: 2 /);
                   5715:                 $returnhash->{$key} = &thaw_unescape($value);
                   5716:             }
                   5717:         }
                   5718:     }
                   5719:     return;
                   5720: }
                   5721: 
1.658     raeburn  5722: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5723: 
                   5724: sub dcmailput {
1.685     raeburn  5725:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5726:     my $status = &Apache::lonnet::critical(
1.740     www      5727:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5728:        &escape($message),$server);
1.662     raeburn  5729:     return $status;
                   5730: }
                   5731: 
1.658     raeburn  5732: sub dcmaildump {
                   5733:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5734:     my %returnhash=();
1.846     albertel 5735: 
                   5736:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5737:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5738:                                                          &escape($enddate).':';
                   5739: 	my @esc_senders=map { &escape($_)} @$senders;
                   5740: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5741: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5742:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5743:             if (($key) && ($value)) {
                   5744:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5745:             }
                   5746:         }
                   5747:     }
                   5748:     return %returnhash;
                   5749: }
1.662     raeburn  5750: # ---------------------------------------------------------- Domain roles
                   5751: 
                   5752: sub get_domain_roles {
                   5753:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5754:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5755:         $startdate = '.';
                   5756:     }
1.1018    raeburn  5757:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5758:         $enddate = '.';
                   5759:     }
1.922     raeburn  5760:     my $rolelist;
                   5761:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5762:         $rolelist = join('&',@{$roles});
1.922     raeburn  5763:     }
1.662     raeburn  5764:     my %personnel = ();
1.841     albertel 5765: 
                   5766:     my %servers = &get_servers($dom,'library');
                   5767:     foreach my $tryserver (keys(%servers)) {
                   5768: 	%{$personnel{$tryserver}}=();
                   5769: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5770: 					    &escape($startdate).':'.
                   5771: 					    &escape($enddate).':'.
                   5772: 					    &escape($rolelist), $tryserver))) {
                   5773: 	    my ($key,$value) = split(/\=/,$line,2);
                   5774: 	    if (($key) && ($value)) {
                   5775: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5776: 	    }
                   5777: 	}
1.662     raeburn  5778:     }
                   5779:     return %personnel;
                   5780: }
1.658     raeburn  5781: 
1.1332    raeburn  5782: sub get_active_domroles {
                   5783:     my ($dom,$roles) = @_;
                   5784:     return () unless (ref($roles) eq 'ARRAY');
                   5785:     my $now = time;
                   5786:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5787:     my %domroles;
                   5788:     foreach my $server (keys(%dompersonnel)) {
                   5789:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5790:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5791:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5792:         }
                   5793:     }
                   5794:     return %domroles;
                   5795: }
                   5796: 
1.1057    www      5797: # ----------------------------------------------------------- Interval timing 
1.149     www      5798: 
1.1153    www      5799: {
                   5800: # Caches needed for speedup of navmaps
                   5801: # We don't want to cache this for very long at all (5 seconds at most)
                   5802: # 
                   5803: # The user for whom we cache
                   5804: my $cachedkey='';
                   5805: # The cached times for this user
                   5806: my %cachedtimes=();
                   5807: # When this was last done
1.1282    raeburn  5808: my $cachedtime='';
1.1153    www      5809: 
                   5810: sub load_all_first_access {
1.1308    raeburn  5811:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5812:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5813:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5814:         (!$ignorecache)) {
1.1154    raeburn  5815:         return;
                   5816:     }
                   5817:     $cachedtime=time;
                   5818:     $cachedkey=$uname.':'.$udom;
                   5819:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5820: }
                   5821: 
1.504     albertel 5822: sub get_first_access {
1.1308    raeburn  5823:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5824:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5825:     if ($argsymb) { $symb=$argsymb; }
                   5826:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5827:     if ($argmap) { $map = $argmap; }
1.926     albertel 5828:     if ($type eq 'course') {
                   5829: 	$res='course';
                   5830:     } elsif ($type eq 'map') {
1.588     albertel 5831: 	$res=&symbread($map);
                   5832:     } else {
                   5833: 	$res=$symb;
                   5834:     }
1.1308    raeburn  5835:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5836:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5837: }
                   5838: 
                   5839: sub set_first_access {
1.1162    raeburn  5840:     my ($type,$interval)=@_;
1.790     albertel 5841:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5842:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5843:     if ($type eq 'course') {
                   5844: 	$res='course';
                   5845:     } elsif ($type eq 'map') {
1.588     albertel 5846: 	$res=&symbread($map);
                   5847:     } else {
                   5848: 	$res=$symb;
                   5849:     }
1.1153    www      5850:     $cachedkey='';
1.1162    raeburn  5851:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5852:     if ($firstaccess) {
                   5853:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5854:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5855:                  "in $courseid");
1.1386    raeburn  5856:         return 'already_set';
                   5857:     } else {
1.1162    raeburn  5858:         my $start = time;
                   5859: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5860:                           $udom,$uname);
                   5861:         if ($putres eq 'ok') {
                   5862:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5863:                  $udom,$uname); 
                   5864:             &appenv(
                   5865:                      {
                   5866:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5867:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5868:                      }
                   5869:                   );
1.1365    raeburn  5870:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5871:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5872:             }
1.1386    raeburn  5873:         } elsif ($putres ne 'refused') {
                   5874:             &logthis("Result: $putres when attempting to set first access time ".
                   5875:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5876:         }
                   5877:         return $putres;
1.505     albertel 5878:     }
                   5879:     return 'already_set';
1.504     albertel 5880: }
1.1153    www      5881: }
1.1282    raeburn  5882: 
1.110     www      5883: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5884: 
                   5885: sub expirespread {
                   5886:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5887:     my $cid=$env{'request.course.id'}; 
1.110     www      5888:     if ($cid) {
                   5889:        my $now=time;
                   5890:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5891:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5892:                             $env{'course.'.$cid.'.num'}.
1.110     www      5893: 	        	    ':nohist_expirationdates:'.
                   5894:                             &escape($key).'='.$now,
1.620     albertel 5895:                             $env{'course.'.$cid.'.home'})
1.110     www      5896:     }
                   5897:     return 'ok';
1.14      www      5898: }
                   5899: 
1.109     www      5900: # ----------------------------------------------------- Devalidate Spreadsheets
                   5901: 
                   5902: sub devalidate {
1.325     www      5903:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5904:     my $cid=$env{'request.course.id'}; 
1.109     www      5905:     if ($cid) {
1.391     matthew  5906:         # delete the stored spreadsheets for
                   5907:         # - the student level sheet of this user in course's homespace
                   5908:         # - the assessment level sheet for this resource 
                   5909:         #   for this user in user's homespace
1.553     albertel 5910: 	# - current conditional state info
1.325     www      5911: 	my $key=$uname.':'.$udom.':';
1.109     www      5912:         my $status=
1.299     matthew  5913: 	    &del('nohist_calculatedsheets',
1.391     matthew  5914: 		 [$key.'studentcalc:'],
1.620     albertel 5915: 		 $env{'course.'.$cid.'.domain'},
                   5916: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5917: 		.' '.
                   5918: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5919: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5920:         unless ($status eq 'ok ok') {
                   5921:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5922:                     $uname.' at '.$udom.' for '.
1.109     www      5923: 		    $symb.': '.$status);
1.133     albertel 5924:         }
1.553     albertel 5925: 	&delenv('user.state.'.$cid);
1.109     www      5926:     }
                   5927: }
                   5928: 
1.265     albertel 5929: sub get_scalar {
                   5930:     my ($string,$end) = @_;
                   5931:     my $value;
                   5932:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5933: 	$value = $1;
                   5934:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5935: 	$value = $1;
                   5936:     }
                   5937:     return &unescape($value);
                   5938: }
                   5939: 
                   5940: sub array2str {
                   5941:   my (@array) = @_;
                   5942:   my $result=&arrayref2str(\@array);
                   5943:   $result=~s/^__ARRAY_REF__//;
                   5944:   $result=~s/__END_ARRAY_REF__$//;
                   5945:   return $result;
                   5946: }
                   5947: 
1.204     albertel 5948: sub arrayref2str {
                   5949:   my ($arrayref) = @_;
1.265     albertel 5950:   my $result='__ARRAY_REF__';
1.204     albertel 5951:   foreach my $elem (@$arrayref) {
1.265     albertel 5952:     if(ref($elem) eq 'ARRAY') {
                   5953:       $result.=&arrayref2str($elem).'&';
                   5954:     } elsif(ref($elem) eq 'HASH') {
                   5955:       $result.=&hashref2str($elem).'&';
                   5956:     } elsif(ref($elem)) {
                   5957:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5958:     } else {
                   5959:       $result.=&escape($elem).'&';
                   5960:     }
                   5961:   }
                   5962:   $result=~s/\&$//;
1.265     albertel 5963:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5964:   return $result;
                   5965: }
                   5966: 
1.168     albertel 5967: sub hash2str {
1.204     albertel 5968:   my (%hash) = @_;
                   5969:   my $result=&hashref2str(\%hash);
1.265     albertel 5970:   $result=~s/^__HASH_REF__//;
                   5971:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5972:   return $result;
                   5973: }
                   5974: 
                   5975: sub hashref2str {
                   5976:   my ($hashref)=@_;
1.265     albertel 5977:   my $result='__HASH_REF__';
1.800     albertel 5978:   foreach my $key (sort(keys(%$hashref))) {
                   5979:     if (ref($key) eq 'ARRAY') {
                   5980:       $result.=&arrayref2str($key).'=';
                   5981:     } elsif (ref($key) eq 'HASH') {
                   5982:       $result.=&hashref2str($key).'=';
                   5983:     } elsif (ref($key)) {
1.265     albertel 5984:       $result.='=';
1.800     albertel 5985:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5986:     } else {
1.1132    raeburn  5987: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5988:     }
                   5989: 
1.800     albertel 5990:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5991:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5992:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5993:       $result.=&hashref2str($hashref->{$key}).'&';
                   5994:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5995:        $result.='&';
1.800     albertel 5996:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5997:     } else {
1.800     albertel 5998:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5999:     }
                   6000:   }
1.168     albertel 6001:   $result=~s/\&$//;
1.265     albertel 6002:   $result .= '__END_HASH_REF__';
1.168     albertel 6003:   return $result;
                   6004: }
                   6005: 
                   6006: sub str2hash {
1.265     albertel 6007:     my ($string)=@_;
                   6008:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6009:     return %$hash;
                   6010: }
                   6011: 
                   6012: sub str2hashref {
1.168     albertel 6013:   my ($string) = @_;
1.265     albertel 6014: 
                   6015:   my %hash;
                   6016: 
                   6017:   if($string !~ /^__HASH_REF__/) {
                   6018:       if (! ($string eq '' || !defined($string))) {
                   6019: 	  $hash{'error'}='Not hash reference';
                   6020:       }
                   6021:       return (\%hash, $string);
                   6022:   }
                   6023: 
                   6024:   $string =~ s/^__HASH_REF__//;
                   6025: 
                   6026:   while($string !~ /^__END_HASH_REF__/) {
                   6027:       #key
                   6028:       my $key='';
                   6029:       if($string =~ /^__HASH_REF__/) {
                   6030:           ($key, $string)=&str2hashref($string);
                   6031:           if(defined($key->{'error'})) {
                   6032:               $hash{'error'}='Bad data';
                   6033:               return (\%hash, $string);
                   6034:           }
                   6035:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6036:           ($key, $string)=&str2arrayref($string);
                   6037:           if($key->[0] eq 'Array reference error') {
                   6038:               $hash{'error'}='Bad data';
                   6039:               return (\%hash, $string);
                   6040:           }
                   6041:       } else {
                   6042:           $string =~ s/^(.*?)=//;
1.267     albertel 6043: 	  $key=&unescape($1);
1.265     albertel 6044:       }
                   6045:       $string =~ s/^=//;
                   6046: 
                   6047:       #value
                   6048:       my $value='';
                   6049:       if($string =~ /^__HASH_REF__/) {
                   6050:           ($value, $string)=&str2hashref($string);
                   6051:           if(defined($value->{'error'})) {
                   6052:               $hash{'error'}='Bad data';
                   6053:               return (\%hash, $string);
                   6054:           }
                   6055:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6056:           ($value, $string)=&str2arrayref($string);
                   6057:           if($value->[0] eq 'Array reference error') {
                   6058:               $hash{'error'}='Bad data';
                   6059:               return (\%hash, $string);
                   6060:           }
                   6061:       } else {
                   6062: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6063:       }
                   6064:       $string =~ s/^&//;
                   6065: 
                   6066:       $hash{$key}=$value;
1.204     albertel 6067:   }
1.265     albertel 6068: 
                   6069:   $string =~ s/^__END_HASH_REF__//;
                   6070: 
                   6071:   return (\%hash, $string);
1.204     albertel 6072: }
                   6073: 
                   6074: sub str2array {
1.265     albertel 6075:     my ($string)=@_;
                   6076:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6077:     return @$array;
                   6078: }
                   6079: 
                   6080: sub str2arrayref {
1.204     albertel 6081:   my ($string) = @_;
1.265     albertel 6082:   my @array;
                   6083: 
                   6084:   if($string !~ /^__ARRAY_REF__/) {
                   6085:       if (! ($string eq '' || !defined($string))) {
                   6086: 	  $array[0]='Array reference error';
                   6087:       }
                   6088:       return (\@array, $string);
                   6089:   }
                   6090: 
                   6091:   $string =~ s/^__ARRAY_REF__//;
                   6092: 
                   6093:   while($string !~ /^__END_ARRAY_REF__/) {
                   6094:       my $value='';
                   6095:       if($string =~ /^__HASH_REF__/) {
                   6096:           ($value, $string)=&str2hashref($string);
                   6097:           if(defined($value->{'error'})) {
                   6098:               $array[0] ='Array reference error';
                   6099:               return (\@array, $string);
                   6100:           }
                   6101:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6102:           ($value, $string)=&str2arrayref($string);
                   6103:           if($value->[0] eq 'Array reference error') {
                   6104:               $array[0] ='Array reference error';
                   6105:               return (\@array, $string);
                   6106:           }
                   6107:       } else {
                   6108: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6109:       }
                   6110:       $string =~ s/^&//;
                   6111: 
                   6112:       push(@array, $value);
1.191     harris41 6113:   }
1.265     albertel 6114: 
                   6115:   $string =~ s/^__END_ARRAY_REF__//;
                   6116: 
                   6117:   return (\@array, $string);
1.168     albertel 6118: }
                   6119: 
1.167     albertel 6120: # -------------------------------------------------------------------Temp Store
                   6121: 
1.168     albertel 6122: sub tmpreset {
                   6123:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6124:   if (!$symb) {
                   6125:     $symb=&symbread();
1.620     albertel 6126:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6127:   }
                   6128:   $symb=escape($symb);
                   6129: 
1.620     albertel 6130:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6131:   $namespace=~s/\//\_/g;
                   6132:   $namespace=~s/\W//g;
                   6133: 
1.620     albertel 6134:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6135:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6136:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6137:       $stuname=&get_requestor_ip();
1.591     albertel 6138:   }
1.1117    foxr     6139:   my $path=LONCAPA::tempdir();
1.168     albertel 6140:   my %hash;
                   6141:   if (tie(%hash,'GDBM_File',
                   6142: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6143: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6144:     foreach my $key (keys(%hash)) {
1.180     albertel 6145:       if ($key=~ /:$symb/) {
1.168     albertel 6146: 	delete($hash{$key});
                   6147:       }
                   6148:     }
                   6149:   }
                   6150: }
                   6151: 
1.167     albertel 6152: sub tmpstore {
1.168     albertel 6153:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6154: 
                   6155:   if (!$symb) {
                   6156:     $symb=&symbread();
1.620     albertel 6157:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6158:   }
                   6159:   $symb=escape($symb);
                   6160: 
                   6161:   if (!$namespace) {
                   6162:     # I don't think we would ever want to store this for a course.
                   6163:     # it seems this will only be used if we don't have a course.
1.620     albertel 6164:     #$namespace=$env{'request.course.id'};
1.168     albertel 6165:     #if (!$namespace) {
1.620     albertel 6166:       $namespace=$env{'request.state'};
1.168     albertel 6167:     #}
                   6168:   }
                   6169:   $namespace=~s/\//\_/g;
                   6170:   $namespace=~s/\W//g;
1.620     albertel 6171:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6172:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6173:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6174:       $stuname=&get_requestor_ip();
1.591     albertel 6175:   }
1.168     albertel 6176:   my $now=time;
                   6177:   my %hash;
1.1117    foxr     6178:   my $path=LONCAPA::tempdir();
1.168     albertel 6179:   if (tie(%hash,'GDBM_File',
                   6180: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6181: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6182:     $hash{"version:$symb"}++;
                   6183:     my $version=$hash{"version:$symb"};
                   6184:     my $allkeys=''; 
                   6185:     foreach my $key (keys(%$storehash)) {
                   6186:       $allkeys.=$key.':';
1.591     albertel 6187:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6188:     }
                   6189:     $hash{"$version:$symb:timestamp"}=$now;
                   6190:     $allkeys.='timestamp';
                   6191:     $hash{"$version:keys:$symb"}=$allkeys;
                   6192:     if (untie(%hash)) {
                   6193:       return 'ok';
                   6194:     } else {
                   6195:       return "error:$!";
                   6196:     }
                   6197:   } else {
                   6198:     return "error:$!";
                   6199:   }
                   6200: }
1.167     albertel 6201: 
1.168     albertel 6202: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6203: 
1.168     albertel 6204: sub tmprestore {
                   6205:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6206: 
1.168     albertel 6207:   if (!$symb) {
                   6208:     $symb=&symbread();
1.620     albertel 6209:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6210:   }
                   6211:   $symb=escape($symb);
                   6212: 
1.620     albertel 6213:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6214: 
1.620     albertel 6215:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6216:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6217:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6218:       $stuname=&get_requestor_ip();
1.591     albertel 6219:   }
1.168     albertel 6220:   my %returnhash;
                   6221:   $namespace=~s/\//\_/g;
                   6222:   $namespace=~s/\W//g;
                   6223:   my %hash;
1.1117    foxr     6224:   my $path=LONCAPA::tempdir();
1.168     albertel 6225:   if (tie(%hash,'GDBM_File',
                   6226: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6227: 	  &GDBM_READER(),0640)) {
1.168     albertel 6228:     my $version=$hash{"version:$symb"};
                   6229:     $returnhash{'version'}=$version;
                   6230:     my $scope;
                   6231:     for ($scope=1;$scope<=$version;$scope++) {
                   6232:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6233:       my @keys=split(/:/,$vkeys);
                   6234:       my $key;
                   6235:       $returnhash{"$scope:keys"}=$vkeys;
                   6236:       foreach $key (@keys) {
1.591     albertel 6237: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6238: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6239:       }
                   6240:     }
1.168     albertel 6241:     if (!(untie(%hash))) {
                   6242:       return "error:$!";
                   6243:     }
                   6244:   } else {
                   6245:     return "error:$!";
                   6246:   }
                   6247:   return %returnhash;
1.167     albertel 6248: }
                   6249: 
1.9       www      6250: # ----------------------------------------------------------------------- Store
                   6251: 
                   6252: sub store {
1.1269    raeburn  6253:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6254:     my $home='';
                   6255: 
1.168     albertel 6256:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6257: 
1.213     www      6258:     $symb=&symbclean($symb);
1.122     albertel 6259:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6260: 
1.620     albertel 6261:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6262:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6263: 
                   6264:     &devalidate($symb,$stuname,$domain);
1.109     www      6265: 
                   6266:     $symb=escape($symb);
1.187     www      6267:     if (!$namespace) { 
1.620     albertel 6268:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6269:           return ''; 
                   6270:        } 
                   6271:     }
1.620     albertel 6272:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6273: 
1.1434    raeburn  6274:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6275:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6276: 
1.12      www      6277:     my $namevalue='';
1.800     albertel 6278:     foreach my $key (keys(%$storehash)) {
                   6279:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6280:     }
1.12      www      6281:     $namevalue=~s/\&$//;
1.187     www      6282:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6283:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6284: }
                   6285: 
1.47      www      6286: # -------------------------------------------------------------- Critical Store
                   6287: 
                   6288: sub cstore {
1.1269    raeburn  6289:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6290:     my $home='';
                   6291: 
1.168     albertel 6292:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6293: 
1.213     www      6294:     $symb=&symbclean($symb);
1.122     albertel 6295:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6296: 
1.620     albertel 6297:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6298:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6299: 
                   6300:     &devalidate($symb,$stuname,$domain);
1.109     www      6301: 
                   6302:     $symb=escape($symb);
1.187     www      6303:     if (!$namespace) { 
1.620     albertel 6304:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6305:           return ''; 
                   6306:        } 
                   6307:     }
1.620     albertel 6308:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6309: 
1.1434    raeburn  6310:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6311:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6312: 
1.47      www      6313:     my $namevalue='';
1.800     albertel 6314:     foreach my $key (keys(%$storehash)) {
                   6315:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6316:     }
1.47      www      6317:     $namevalue=~s/\&$//;
1.187     www      6318:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6319:     return critical
1.1269    raeburn  6320:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6321: }
                   6322: 
1.9       www      6323: # --------------------------------------------------------------------- Restore
                   6324: 
                   6325: sub restore {
1.124     www      6326:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6327:     my $home='';
                   6328: 
1.168     albertel 6329:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6330: 
1.122     albertel 6331:     if (!$symb) {
1.1224    raeburn  6332:         return if ($namespace eq 'courserequests');
                   6333:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6334:     } else {
1.1224    raeburn  6335:         unless ($namespace eq 'courserequests') {
                   6336:             $symb=&escape(&symbclean($symb));
                   6337:         }
1.122     albertel 6338:     }
1.188     www      6339:     if (!$namespace) { 
1.620     albertel 6340:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6341:           return ''; 
                   6342:        } 
                   6343:     }
1.620     albertel 6344:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6345:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6346:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6347:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6348: 
1.12      www      6349:     my %returnhash=();
1.800     albertel 6350:     foreach my $line (split(/\&/,$answer)) {
                   6351: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6352:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6353:     }
1.75      www      6354:     my $version;
                   6355:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6356:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6357:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6358:        }
1.75      www      6359:     }
1.13      www      6360:     return %returnhash;
1.34      www      6361: }
                   6362: 
                   6363: # ---------------------------------------------------------- Course Description
1.1118    foxr     6364: #
                   6365: #  
1.34      www      6366: 
                   6367: sub coursedescription {
1.731     albertel 6368:     my ($courseid,$args)=@_;
1.34      www      6369:     $courseid=~s/^\///;
1.49      www      6370:     $courseid=~s/\_/\//g;
1.34      www      6371:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6372:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6373:     my $normalid=$cdomain.'_'.$cnum;
                   6374:     # need to always cache even if we get errors otherwise we keep 
                   6375:     # trying and trying and trying to get the course description.
                   6376:     my %envhash=();
                   6377:     my %returnhash=();
1.731     albertel 6378:     
                   6379:     my $expiretime=600;
                   6380:     if ($env{'request.course.id'} eq $normalid) {
                   6381: 	$expiretime=120;
                   6382:     }
                   6383: 
                   6384:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6385:     if (!$args->{'freshen_cache'}
                   6386: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6387: 	foreach my $key (keys(%env)) {
                   6388: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6389: 	    my ($setting) = $1;
                   6390: 	    $returnhash{$setting} = $env{$key};
                   6391: 	}
                   6392: 	return %returnhash;
                   6393:     }
                   6394: 
1.1118    foxr     6395:     # get the data again
                   6396: 
1.731     albertel 6397:     if (!$args->{'one_time'}) {
                   6398: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6399:     }
1.811     albertel 6400: 
1.34      www      6401:     if ($chome ne 'no_host') {
1.302     albertel 6402:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6403:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6404: 	   my $username = $env{'user.name'}; # Defult username
                   6405: 	   if(defined $args->{'user'}) {
                   6406: 	       $username = $args->{'user'};
                   6407: 	   }
1.129     albertel 6408:            $returnhash{'home'}= $chome;
                   6409: 	   $returnhash{'domain'} = $cdomain;
                   6410: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6411:            if (!defined($returnhash{'type'})) {
                   6412:                $returnhash{'type'} = 'Course';
                   6413:            }
1.130     albertel 6414:            while (my ($name,$value) = each %returnhash) {
1.53      www      6415:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6416:            }
1.270     www      6417:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6418:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6419: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6420:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6421:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6422:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6423:        }
                   6424:     }
1.731     albertel 6425:     if (!$args->{'one_time'}) {
1.949     raeburn  6426: 	&appenv(\%envhash);
1.731     albertel 6427:     }
1.302     albertel 6428:     return %returnhash;
1.461     www      6429: }
                   6430: 
1.1080    raeburn  6431: sub update_released_required {
                   6432:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6433:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6434:         $cid = $env{'request.course.id'};
                   6435:         $cdom = $env{'course.'.$cid.'.domain'};
                   6436:         $cnum = $env{'course.'.$cid.'.num'};
                   6437:         $chome = $env{'course.'.$cid.'.home'};
                   6438:     }
                   6439:     if ($needsrelease) {
                   6440:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6441:         my $needsupdate;
                   6442:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6443:             $needsupdate = 1;
                   6444:         } else {
                   6445:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6446:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6447:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6448:                 $needsupdate = 1;
                   6449:             }
                   6450:         }
                   6451:         if ($needsupdate) {
                   6452:             my %needshash = (
                   6453:                              'internal.releaserequired' => $needsrelease,
                   6454:                             );
                   6455:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6456:             if ($putresult eq 'ok') {
                   6457:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6458:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6459:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6460:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6461:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6462:                 }
                   6463:             }
                   6464:         }
                   6465:     }
                   6466:     return;
                   6467: }
                   6468: 
1.461     www      6469: # -------------------------------------------------See if a user is privileged
                   6470: 
                   6471: sub privileged {
1.1219    raeburn  6472:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6473:     my $now = time;
1.1219    raeburn  6474:     my $roles;
                   6475:     if (ref($possroles) eq 'ARRAY') {
                   6476:         $roles = $possroles; 
                   6477:     } else {
                   6478:         $roles = ['dc','su'];
                   6479:     }
                   6480:     if (ref($possdomains) eq 'ARRAY') {
                   6481:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6482:         foreach my $dom (@{$possdomains}) {
                   6483:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6484:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6485:                 foreach my $role (@{$roles}) {
                   6486:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6487:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6488:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6489:                             return 1 unless (($end && $end < $now) ||
                   6490:                                              ($start && $start > $now));
                   6491:                         }
                   6492:                     }
                   6493:                 }
                   6494:             }
                   6495:         }
                   6496:     } else {
                   6497:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6498:         my $now = time;
1.1170    droeschl 6499: 
1.1275    musolffc 6500:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6501:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6502:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6503:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6504:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6505:             }
1.1219    raeburn  6506:         }
                   6507:     }
                   6508:     return 0;
                   6509: }
1.1170    droeschl 6510: 
1.1219    raeburn  6511: sub privileged_by_domain {
                   6512:     my ($domains,$roles) = @_;
                   6513:     my %privileged = ();
                   6514:     my $cachetime = 60*60*24;
                   6515:     my $now = time;
                   6516:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6517:         return %privileged;
                   6518:     }
                   6519:     foreach my $dom (@{$domains}) {
                   6520:         next if (ref($privileged{$dom}) eq 'HASH');
                   6521:         my $needroles;
                   6522:         foreach my $role (@{$roles}) {
                   6523:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6524:             if (defined($cached)) {
                   6525:                 if (ref($result) eq 'HASH') {
                   6526:                     $privileged{$dom}{$role} = $result;
                   6527:                 }
                   6528:             } else {
                   6529:                 $needroles = 1;
                   6530:             }
                   6531:         }
                   6532:         if ($needroles) {
                   6533:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6534:             $privileged{$dom} = {};
                   6535:             foreach my $server (keys(%dompersonnel)) {
                   6536:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6537:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6538:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6539:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6540:                         next if ($end && $end < $now);
                   6541:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6542:                             $dompersonnel{$server}{$item};
                   6543:                     }
                   6544:                 }
                   6545:             }
                   6546:             if (ref($privileged{$dom}) eq 'HASH') {
                   6547:                 foreach my $role (@{$roles}) {
                   6548:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6549:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6550:                     } else {
                   6551:                         my %hash = ();
                   6552:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6553:                     }
                   6554:                 }
                   6555:             }
                   6556:         }
                   6557:     }
                   6558:     return %privileged;
1.9       www      6559: }
1.1       albertel 6560: 
1.103     harris41 6561: # -------------------------------------------------------- Get user privileges
1.11      www      6562: 
                   6563: sub rolesinit {
1.1169    droeschl 6564:     my ($domain, $username) = @_;
                   6565:     my %userroles = ('user.login.time' => time);
                   6566:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6567: 
                   6568:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6569:     # also, blocking can be triggered by an activating timer
                   6570:     # it's saved in the user's %env.
                   6571:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6572:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6573:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6574:         %timerintchk, %timerintenv);
                   6575: 
1.1162    raeburn  6576:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6577:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6578:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6579:     }
1.1169    droeschl 6580: 
1.1162    raeburn  6581:     foreach my $key (keys(%timerinterval)) {
                   6582:         my ($cid,$rest) = split(/\0/,$key);
                   6583:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6584:     }
1.1169    droeschl 6585: 
1.11      www      6586:     my %allroles=();
1.1162    raeburn  6587:     my %allgroups=();
1.11      www      6588: 
1.1274    raeburn  6589:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6590:         my $role = $rolesdump{$area};
                   6591:         $area =~ s/\_\w\w$//;
                   6592: 
                   6593:         my ($trole, $tend, $tstart, $group_privs);
                   6594: 
                   6595:         if ($role =~ /^cr/) {
                   6596:         # Custom role, defined by a user 
                   6597:         # e.g., user.role.cr/msu/smith/mynewrole
                   6598:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6599:                 $trole = $1;
                   6600:                 ($tend, $tstart) = split('_', $2);
                   6601:             } else {
                   6602:                 $trole = $role;
                   6603:             }
                   6604:         } elsif ($role =~ m|^gr/|) {
                   6605:         # Role of member in a group, defined within a course/community
                   6606:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6607:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6608:             next if $tstart eq '-1';
                   6609:             ($trole, $group_privs) = split(/\//, $trole);
                   6610:             $group_privs = &unescape($group_privs);
                   6611:         } else {
                   6612:         # Just a normal role, defined in roles.tab
                   6613:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6614:         }
                   6615: 
                   6616:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6617:                  $username);
                   6618:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6619: 
                   6620:         # role expired or not available yet?
                   6621:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6622:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6623: 
                   6624:         next if $area eq '' or $trole eq '';
                   6625: 
                   6626:         my $spec = "$trole.$area";
                   6627:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6628: 
                   6629:         if ($trole =~ /^cr\//) {
                   6630:         # Custom role, defined by a user
                   6631:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6632:         } elsif ($trole eq 'gr') {
                   6633:         # Role of a member in a group, defined within a course/community
                   6634:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6635:             next;
                   6636:         } else {
                   6637:         # Normal role, defined in roles.tab
                   6638:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6639:         }
                   6640: 
                   6641:         my $cid = $tdomain.'_'.$trest;
                   6642:         unless ($firstaccchk{$cid}) {
                   6643:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6644:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6645:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6646:                         $coursetimerstarts{$cid}{$item}; 
                   6647:                 }
                   6648:             }
                   6649:             $firstaccchk{$cid} = 1;
                   6650:         }
                   6651:         unless ($timerintchk{$cid}) {
                   6652:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6653:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6654:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6655:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6656:                 }
1.12      www      6657:             }
1.1169    droeschl 6658:             $timerintchk{$cid} = 1;
1.191     harris41 6659:         }
1.11      www      6660:     }
1.1169    droeschl 6661: 
1.1341    raeburn  6662:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6663:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6664:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6665:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6666: 
1.1162    raeburn  6667:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6668: }
                   6669: 
1.567     raeburn  6670: sub set_arearole {
1.1215    raeburn  6671:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6672:     unless ($nolog) {
1.567     raeburn  6673: # log the associated role with the area
1.1215    raeburn  6674:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6675:     }
1.743     albertel 6676:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6677: }
                   6678: 
                   6679: sub custom_roleprivs {
                   6680:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6681:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6682:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6683:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6684:         my ($rdummy,$roledef)=
                   6685:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6686:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6687:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6688:             if (defined($syspriv)) {
1.1043    raeburn  6689:                 if ($trest =~ /^$match_community$/) {
                   6690:                     $syspriv =~ s/bre\&S//; 
                   6691:                 }
1.567     raeburn  6692:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6693:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6694:             }
                   6695:             if ($tdomain ne '') {
                   6696:                 if (defined($dompriv)) {
                   6697:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6698:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6699:                 }
                   6700:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6701:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6702:                         my $rolename = $1;
                   6703:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6704:                     }
1.567     raeburn  6705:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6706:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6707:                 }
                   6708:             }
                   6709:         }
                   6710:     }
                   6711: }
                   6712: 
1.1332    raeburn  6713: sub course_adhocrole_privs {
                   6714:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6715:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6716:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6717:         my (%currprivs,%storeprivs);
                   6718:         foreach my $item (split(/:/,$coursepriv)) {
                   6719:             my ($priv,$restrict) = split(/\&/,$item);
                   6720:             $currprivs{$priv} = $restrict;
                   6721:         }
                   6722:         my (%possadd,%possremove,%full);
                   6723:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6724:             my ($priv,$restrict)=split(/\&/,$item);
                   6725:             $full{$priv} = $restrict;
                   6726:         }
                   6727:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6728:              next if ($item eq '');
                   6729:              my ($rule,$rest) = split(/=/,$item);
                   6730:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6731:              foreach my $priv (split(/:/,$rest)) {
                   6732:                  if ($priv ne '') {
                   6733:                      if ($rule eq 'off') {
                   6734:                          $possremove{$priv} = 1;
                   6735:                      } else {
                   6736:                          $possadd{$priv} = 1;
                   6737:                      }
                   6738:                  }
                   6739:              }
                   6740:          }
                   6741:          foreach my $priv (sort(keys(%full))) {
                   6742:              if (exists($currprivs{$priv})) {
                   6743:                  unless (exists($possremove{$priv})) {
                   6744:                      $storeprivs{$priv} = $currprivs{$priv};
                   6745:                  }
                   6746:              } elsif (exists($possadd{$priv})) {
                   6747:                  $storeprivs{$priv} = $full{$priv};
                   6748:              }
                   6749:          }
                   6750:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6751:      }
                   6752:      return $coursepriv;
                   6753: }
                   6754: 
1.678     raeburn  6755: sub group_roleprivs {
                   6756:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6757:     my $access = 1;
                   6758:     my $now = time;
                   6759:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6760:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6761:     if ($access) {
1.811     albertel 6762:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6763:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6764:     }
                   6765: }
1.567     raeburn  6766: 
                   6767: sub standard_roleprivs {
                   6768:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6769:     if (defined($pr{$trole.':s'})) {
                   6770:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6771:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6772:     }
                   6773:     if ($tdomain ne '') {
                   6774:         if (defined($pr{$trole.':d'})) {
                   6775:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6776:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6777:         }
                   6778:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6779:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6780:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6781:         }
                   6782:     }
                   6783: }
                   6784: 
                   6785: sub set_userprivs {
1.1064    raeburn  6786:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6787:     my $author=0;
                   6788:     my $adv=0;
1.1341    raeburn  6789:     my $rar=0;
1.678     raeburn  6790:     my %grouproles = ();
                   6791:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6792:         my @groupkeys; 
1.1000    raeburn  6793:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6794:             push(@groupkeys,$role);
                   6795:         }
                   6796:         if (ref($groups_roles) eq 'HASH') {
                   6797:             foreach my $key (keys(%{$groups_roles})) {
                   6798:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6799:                     push(@groupkeys,$key);
                   6800:                 }
                   6801:             }
                   6802:         }
                   6803:         if (@groupkeys > 0) {
                   6804:             foreach my $role (@groupkeys) {
                   6805:                 my ($trole,$area,$sec,$extendedarea);
                   6806:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6807:                     $trole = $1;
                   6808:                     $area = $2;
                   6809:                     $sec = $3;
                   6810:                     $extendedarea = $area.$sec;
                   6811:                     if (exists($$allgroups{$area})) {
                   6812:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6813:                             my $spec = $trole.'.'.$extendedarea;
                   6814:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6815:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6816:                         }
1.678     raeburn  6817:                     }
                   6818:                 }
                   6819:             }
                   6820:         }
                   6821:     }
1.800     albertel 6822:     foreach my $group (keys(%grouproles)) {
                   6823:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6824:     }
1.800     albertel 6825:     foreach my $role (keys(%{$allroles})) {
                   6826:         my %thesepriv;
1.941     raeburn  6827:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6828:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6829:             if ($item ne '') {
                   6830:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6831:                 if ($restrictions eq '') {
                   6832:                     $thesepriv{$privilege}='F';
                   6833:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6834:                     $thesepriv{$privilege}.=$restrictions;
                   6835:                 }
                   6836:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6837:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6838:             }
                   6839:         }
                   6840:         my $thesestr='';
1.1104    raeburn  6841:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6842: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6843: 	}
                   6844:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6845:     }
1.1341    raeburn  6846:     return ($author,$adv,$rar);
1.567     raeburn  6847: }
                   6848: 
1.994     raeburn  6849: sub role_status {
1.1104    raeburn  6850:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6851:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6852:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6853:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6854:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6855:             $$where = '/'.$two;
1.994     raeburn  6856:             $$trolecode=$$role.'.'.$$where;
                   6857:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6858:             $$tstatus='is';
1.1104    raeburn  6859:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6860:                 $$tstatus='future';
1.1034    raeburn  6861:                 if ($$tstart<$now) {
                   6862:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6863:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6864:                             my (%allroles,%allgroups,$group_privs,
                   6865:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6866:                             my %userroles = (
                   6867:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6868:                             );
1.1064    raeburn  6869:                             @rolecodes = ('cm'); 
1.1002    raeburn  6870:                             my $spec=$$role.'.'.$$where;
                   6871:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6872:                             if ($$role =~ /^cr\//) {
                   6873:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6874:                                 push(@rolecodes,'cr');
1.1002    raeburn  6875:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6876:                                 push(@rolecodes,$$role);
1.1002    raeburn  6877:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6878:                                                     $env{'user.name'});
1.1064    raeburn  6879:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6880:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6881:                                 $group_privs = &unescape($group_privs);
                   6882:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6883:                                 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  6884:                                 &get_groups_roles($tdomain,$trest,
                   6885:                                                   \%course_roles,\@rolecodes,
                   6886:                                                   \%groups_roles);
1.1002    raeburn  6887:                             } else {
1.1064    raeburn  6888:                                 push(@rolecodes,$$role);
1.1002    raeburn  6889:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6890:                             }
1.1341    raeburn  6891:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6892:                                                                    \%groups_roles);
1.1064    raeburn  6893:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6894:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6895:                         }
                   6896:                     }
1.1034    raeburn  6897:                     $$tstatus = 'is';
1.1002    raeburn  6898:                 }
1.994     raeburn  6899:             }
                   6900:             if ($$tend) {
1.1104    raeburn  6901:                 if ($$tend<$update) {
1.994     raeburn  6902:                     $$tstatus='expired';
                   6903:                 } elsif ($$tend<$now) {
                   6904:                     $$tstatus='will_not';
                   6905:                 }
                   6906:             }
                   6907:         }
                   6908:     }
                   6909: }
                   6910: 
1.1104    raeburn  6911: sub get_groups_roles {
                   6912:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6913:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6914:                   (ref($rolecodes) eq 'ARRAY') && 
                   6915:                   (ref($groups_roles) eq 'HASH')); 
                   6916:     if (keys(%{$cdom_courseroles}) > 0) {
                   6917:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6918:         if ($cdom ne '' && $cnum ne '') {
                   6919:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6920:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6921:                     my $crsrole = $1;
                   6922:                     my $crssec = $2;
                   6923:                     if ($crsrole =~ /^cr/) {
                   6924:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6925:                             push(@{$rolecodes},'cr');
                   6926:                         }
                   6927:                     } else {
                   6928:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6929:                             push(@{$rolecodes},$crsrole);
                   6930:                         }
                   6931:                     }
                   6932:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6933:                     if ($crssec ne '') {
                   6934:                         $rolekey .= "/$crssec";
                   6935:                     }
                   6936:                     $rolekey .= './';
                   6937:                     $groups_roles->{$rolekey} = $rolecodes;
                   6938:                 }
                   6939:             }
                   6940:         }
                   6941:     }
                   6942:     return;
                   6943: }
                   6944: 
                   6945: sub delete_env_groupprivs {
                   6946:     my ($where,$courseroles,$possroles) = @_;
                   6947:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6948:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6949:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6950:         %{$courseroles->{$udom}} =
                   6951:             &get_my_roles('','','userroles',['active'],
                   6952:                           $possroles,[$udom],1);
                   6953:     }
                   6954:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6955:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6956:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6957:             my $area = '/'.$cdom.'/'.$cnum;
                   6958:             my $privkey = "user.priv.$crsrole.$area";
                   6959:             if ($crssec ne '') {
                   6960:                 $privkey .= '/'.$crssec;
                   6961:             }
                   6962:             $privkey .= ".$area/$group";
                   6963:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6964:         }
                   6965:     }
                   6966:     return;
                   6967: }
                   6968: 
1.994     raeburn  6969: sub check_adhoc_privs {
1.1329    raeburn  6970:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6971:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6972:     if ($sec) {
                   6973:         $cckey .= '/'.$sec;
                   6974:     } 
1.1185    raeburn  6975:     my $setprivs;
1.994     raeburn  6976:     if ($env{$cckey}) {
                   6977:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6978:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6979:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6980:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6981:             $setprivs = 1;
1.994     raeburn  6982:         }
                   6983:     } else {
1.1330    raeburn  6984:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6985:         $setprivs = 1;
1.994     raeburn  6986:     }
1.1185    raeburn  6987:     return $setprivs;
1.994     raeburn  6988: }
                   6989: 
                   6990: sub set_adhoc_privileges {
1.1326    raeburn  6991: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6992:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6993:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6994:     if ($sec ne '') {
                   6995:         $area .= '/'.$sec;
                   6996:     }
1.994     raeburn  6997:     my $spec = $role.'.'.$area;
                   6998:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6999:                                   $env{'user.name'},1);
1.1326    raeburn  7000:     my %rolehash = ();
1.1332    raeburn  7001:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7002:         my $rolename = $1;
1.1326    raeburn  7003:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  7004:         my %domdef = &get_domain_defaults($dcdom);
                   7005:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7006:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7007:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7008:             }
                   7009:         }
1.1326    raeburn  7010:     } else {
                   7011:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7012:     }
1.1341    raeburn  7013:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7014:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7015:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7016:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7017:             ($caller eq 'tiny')) {
1.1088    raeburn  7018:         &appenv( {'request.role'        => $spec,
                   7019:                   'request.role.domain' => $dcdom,
1.1332    raeburn  7020:                   'request.course.sec'  => $sec,
1.1088    raeburn  7021:                  }
                   7022:                );
                   7023:         my $tadv=0;
                   7024:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7025:         &appenv({'request.role.adv'    => $tadv});
                   7026:     }
1.994     raeburn  7027: }
                   7028: 
1.12      www      7029: # --------------------------------------------------------------- get interface
                   7030: 
                   7031: sub get {
1.131     albertel 7032:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7033:    my $items='';
1.800     albertel 7034:    foreach my $item (@$storearr) {
                   7035:        $items.=&escape($item).'&';
1.191     harris41 7036:    }
1.12      www      7037:    $items=~s/\&$//;
1.620     albertel 7038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7039:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7040:    my $uhome=&homeserver($uname,$udomain);
                   7041: 
1.133     albertel 7042:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7043:    my @pairs=split(/\&/,$rep);
1.273     albertel 7044:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7045:      return @pairs;
                   7046:    }
1.15      www      7047:    my %returnhash=();
1.42      www      7048:    my $i=0;
1.800     albertel 7049:    foreach my $item (@$storearr) {
                   7050:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7051:       $i++;
1.191     harris41 7052:    }
1.15      www      7053:    return %returnhash;
1.27      www      7054: }
                   7055: 
                   7056: # --------------------------------------------------------------- del interface
                   7057: 
                   7058: sub del {
1.133     albertel 7059:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7060:    my $items='';
1.800     albertel 7061:    foreach my $item (@$storearr) {
                   7062:        $items.=&escape($item).'&';
1.191     harris41 7063:    }
1.984     neumanie 7064: 
1.27      www      7065:    $items=~s/\&$//;
1.620     albertel 7066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7067:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7068:    my $uhome=&homeserver($uname,$udomain);
                   7069:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7070: }
                   7071: 
                   7072: # -------------------------------------------------------------- dump interface
                   7073: 
1.1180    droeschl 7074: sub unserialize {
                   7075:     my ($rep, $escapedkeys) = @_;
                   7076: 
                   7077:     return {} if $rep =~ /^error/;
                   7078: 
                   7079:     my %returnhash=();
1.1252    raeburn  7080: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7081: 	    my ($key, $value) = split(/=/, $item, 2);
                   7082: 	    $key = unescape($key) unless $escapedkeys;
                   7083: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7084: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7085: 	}
                   7086:     #return %returnhash;
                   7087:     return \%returnhash;
                   7088: }        
                   7089: 
                   7090: # see Lond::dump_with_regexp
                   7091: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7092: sub dump {
1.1180    droeschl 7093:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 7094:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7095:     if (!$uname) { $uname=$env{'user.name'}; }
                   7096:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7097: 
1.1266    raeburn  7098:     if ($regexp) {
                   7099:         $regexp=&escape($regexp);
                   7100:     } else {
                   7101:         $regexp='.';
                   7102:     }
1.1180    droeschl 7103:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7104:         # user is hosted on this machine
1.1266    raeburn  7105:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7106:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7107:         return %{unserialize($reply, $escapedkeys)};
                   7108:     }
1.1166    raeburn  7109:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 7110:     my @pairs=split(/\&/,$rep);
                   7111:     my %returnhash=();
1.1098    foxr     7112:     if (!($rep =~ /^error/ )) {
                   7113: 	foreach my $item (@pairs) {
                   7114: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7115:         $key = unescape($key) unless $escapedkeys;
                   7116:         #$key = &unescape($key);
1.1098    foxr     7117: 	    next if ($key =~ /^error: 2 /);
                   7118: 	    $returnhash{$key}=&thaw_unescape($value);
                   7119: 	}
1.755     albertel 7120:     }
                   7121:     return %returnhash;
1.407     www      7122: }
                   7123: 
1.1098    foxr     7124: 
1.717     albertel 7125: # --------------------------------------------------------- dumpstore interface
                   7126: 
                   7127: sub dumpstore {
                   7128:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7129:    # same as dump but keys must be escaped. They may contain colon separated
                   7130:    # lists of values that may themself contain colons (e.g. symbs).
                   7131:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7132: }
                   7133: 
1.407     www      7134: # -------------------------------------------------------------- keys interface
                   7135: 
                   7136: sub getkeys {
                   7137:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7138:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7139:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7140:    my $uhome=&homeserver($uname,$udomain);
                   7141:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7142:    my @keyarray=();
1.800     albertel 7143:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7144:       next if ($key =~ /^error: 2 /);
1.800     albertel 7145:       push(@keyarray,&unescape($key));
1.407     www      7146:    }
                   7147:    return @keyarray;
1.318     matthew  7148: }
                   7149: 
1.319     matthew  7150: # --------------------------------------------------------------- currentdump
                   7151: sub currentdump {
1.328     matthew  7152:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7153:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7154:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7155:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7156:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7157:    my $rep;
                   7158: 
                   7159:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7160:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7161:                    $courseid)));
                   7162:    } else {
                   7163:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7164:    }
                   7165: 
1.318     matthew  7166:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7167:    #
1.318     matthew  7168:    my %returnhash=();
1.319     matthew  7169:    #
1.1343    raeburn  7170:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7171:        # an old lond will not know currentdump
                   7172:        # Do a dump and make it look like a currentdump
1.822     albertel 7173:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7174:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7175:        my %hash = @tmp;
                   7176:        @tmp=();
1.424     matthew  7177:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7178:    } else {
                   7179:        my @pairs=split(/\&/,$rep);
1.800     albertel 7180:        foreach my $pair (@pairs) {
                   7181:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7182:            my ($symb,$param) = split(/:/,$key);
                   7183:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7184:                                                         &thaw_unescape($value);
1.319     matthew  7185:        }
1.191     harris41 7186:    }
1.12      www      7187:    return %returnhash;
1.424     matthew  7188: }
                   7189: 
                   7190: sub convert_dump_to_currentdump{
                   7191:     my %hash = %{shift()};
                   7192:     my %returnhash;
                   7193:     # Code ripped from lond, essentially.  The only difference
                   7194:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7195:     # we might run in to problems with parameter names =~ /^v\./
                   7196:     while (my ($key,$value) = each(%hash)) {
                   7197:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7198: 	$symb  = &unescape($symb);
                   7199: 	$param = &unescape($param);
1.424     matthew  7200:         next if ($v eq 'version' || $symb eq 'keys');
                   7201:         next if (exists($returnhash{$symb}) &&
                   7202:                  exists($returnhash{$symb}->{$param}) &&
                   7203:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7204:         $returnhash{$symb}->{$param}=$value;
                   7205:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7206:     }
                   7207:     #
                   7208:     # Remove all of the keys in the hashes which keep track of
                   7209:     # the version of the parameter.
                   7210:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7211:         # use a foreach because we are going to delete from the hash.
                   7212:         foreach my $key (keys(%$param_hash)) {
                   7213:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7214:         }
                   7215:     }
                   7216:     return \%returnhash;
1.12      www      7217: }
                   7218: 
1.627     albertel 7219: # ------------------------------------------------------ critical inc interface
                   7220: 
                   7221: sub cinc {
                   7222:     return &inc(@_,'critical');
                   7223: }
                   7224: 
1.449     matthew  7225: # --------------------------------------------------------------- inc interface
                   7226: 
                   7227: sub inc {
1.627     albertel 7228:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7229:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7230:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7231:     my $uhome=&homeserver($uname,$udomain);
                   7232:     my $items='';
                   7233:     if (! ref($store)) {
                   7234:         # got a single value, so use that instead
                   7235:         $items = &escape($store).'=&';
                   7236:     } elsif (ref($store) eq 'SCALAR') {
                   7237:         $items = &escape($$store).'=&';        
                   7238:     } elsif (ref($store) eq 'ARRAY') {
                   7239:         $items = join('=&',map {&escape($_);} @{$store});
                   7240:     } elsif (ref($store) eq 'HASH') {
                   7241:         while (my($key,$value) = each(%{$store})) {
                   7242:             $items.= &escape($key).'='.&escape($value).'&';
                   7243:         }
                   7244:     }
                   7245:     $items=~s/\&$//;
1.627     albertel 7246:     if ($critical) {
                   7247: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7248:     } else {
                   7249: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7250:     }
1.449     matthew  7251: }
                   7252: 
1.12      www      7253: # --------------------------------------------------------------- put interface
                   7254: 
                   7255: sub put {
1.134     albertel 7256:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7257:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7258:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7259:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7260:    my $items='';
1.800     albertel 7261:    foreach my $item (keys(%$storehash)) {
                   7262:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7263:    }
1.12      www      7264:    $items=~s/\&$//;
1.134     albertel 7265:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7266: }
                   7267: 
1.631     albertel 7268: # ------------------------------------------------------------ newput interface
                   7269: 
                   7270: sub newput {
                   7271:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7272:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7273:    if (!$uname) { $uname=$env{'user.name'}; }
                   7274:    my $uhome=&homeserver($uname,$udomain);
                   7275:    my $items='';
                   7276:    foreach my $key (keys(%$storehash)) {
                   7277:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7278:    }
                   7279:    $items=~s/\&$//;
                   7280:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7281: }
                   7282: 
                   7283: # ---------------------------------------------------------  putstore interface
                   7284: 
1.524     raeburn  7285: sub putstore {
1.1269    raeburn  7286:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7287:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7288:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7289:    my $uhome=&homeserver($uname,$udomain);
                   7290:    my $items='';
1.715     albertel 7291:    foreach my $key (keys(%$storehash)) {
                   7292:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7293:    }
1.715     albertel 7294:    $items=~s/\&$//;
1.716     albertel 7295:    my $esc_symb=&escape($symb);
                   7296:    my $esc_v=&escape($version);
1.715     albertel 7297:    my $reply =
1.716     albertel 7298:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7299: 	      $uhome);
1.1269    raeburn  7300:    if (($tolog) && ($reply eq 'ok')) {
                   7301:        my $namevalue='';
                   7302:        foreach my $key (keys(%{$storehash})) {
                   7303:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7304:        }
1.1434    raeburn  7305:        my $ip = &get_requestor_ip();
                   7306:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7307:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7308:                      '&version='.$esc_v.
                   7309:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7310:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7311:    }
1.715     albertel 7312:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7313:        # gfall back to way things use to be done
1.715     albertel 7314:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7315: 			    $uname);
1.524     raeburn  7316:    }
1.715     albertel 7317:    return $reply;
                   7318: }
                   7319: 
                   7320: sub old_putstore {
1.716     albertel 7321:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7322:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7323:     if (!$uname) { $uname=$env{'user.name'}; }
                   7324:     my $uhome=&homeserver($uname,$udomain);
                   7325:     my %newstorehash;
1.800     albertel 7326:     foreach my $item (keys(%$storehash)) {
                   7327: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7328: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7329:     }
                   7330:     my $items='';
                   7331:     my %allitems = ();
1.800     albertel 7332:     foreach my $item (keys(%newstorehash)) {
                   7333: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7334: 	    my $key = $1.':keys:'.$2;
                   7335: 	    $allitems{$key} .= $3.':';
                   7336: 	}
1.800     albertel 7337: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7338:     }
1.800     albertel 7339:     foreach my $item (keys(%allitems)) {
                   7340: 	$allitems{$item} =~ s/\:$//;
                   7341: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7342:     }
                   7343:     $items=~s/\&$//;
                   7344:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7345: }
                   7346: 
1.47      www      7347: # ------------------------------------------------------ critical put interface
                   7348: 
                   7349: sub cput {
1.134     albertel 7350:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7351:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7352:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7353:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7354:    my $items='';
1.800     albertel 7355:    foreach my $item (keys(%$storehash)) {
                   7356:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7357:    }
1.47      www      7358:    $items=~s/\&$//;
1.134     albertel 7359:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7360: }
                   7361: 
                   7362: # -------------------------------------------------------------- eget interface
                   7363: 
                   7364: sub eget {
1.133     albertel 7365:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7366:    my $items='';
1.800     albertel 7367:    foreach my $item (@$storearr) {
                   7368:        $items.=&escape($item).'&';
1.191     harris41 7369:    }
1.12      www      7370:    $items=~s/\&$//;
1.620     albertel 7371:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7372:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7373:    my $uhome=&homeserver($uname,$udomain);
                   7374:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7375:    my @pairs=split(/\&/,$rep);
                   7376:    my %returnhash=();
1.42      www      7377:    my $i=0;
1.800     albertel 7378:    foreach my $item (@$storearr) {
                   7379:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7380:       $i++;
1.191     harris41 7381:    }
1.12      www      7382:    return %returnhash;
                   7383: }
                   7384: 
1.667     albertel 7385: # ------------------------------------------------------------ tmpput interface
                   7386: sub tmpput {
1.802     raeburn  7387:     my ($storehash,$server,$context)=@_;
1.667     albertel 7388:     my $items='';
1.800     albertel 7389:     foreach my $item (keys(%$storehash)) {
                   7390: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7391:     }
                   7392:     $items=~s/\&$//;
1.802     raeburn  7393:     if (defined($context)) {
                   7394:         $items .= ':'.&escape($context);
                   7395:     }
1.667     albertel 7396:     return &reply("tmpput:$items",$server);
                   7397: }
                   7398: 
                   7399: # ------------------------------------------------------------ tmpget interface
                   7400: sub tmpget {
1.688     albertel 7401:     my ($token,$server)=@_;
                   7402:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7403:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7404:     my %returnhash;
1.1328    raeburn  7405:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7406:         return %returnhash;
                   7407:     }
1.667     albertel 7408:     foreach my $item (split(/\&/,$rep)) {
                   7409: 	my ($key,$value)=split(/=/,$item);
                   7410: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7411:     }
                   7412:     return %returnhash;
                   7413: }
                   7414: 
1.1113    raeburn  7415: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7416: sub tmpdel {
                   7417:     my ($token,$server)=@_;
                   7418:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7419:     return &reply("tmpdel:$token",$server);
                   7420: }
                   7421: 
1.1198    raeburn  7422: # ------------------------------------------------------------ get_timebased_id 
                   7423: 
                   7424: sub get_timebased_id {
                   7425:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7426:         $maxtries) = @_;
                   7427:     my ($newid,$error,$dellock);
                   7428:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7429:         return ('','ok','invalid call to get suffix');
                   7430:     }
                   7431: 
                   7432: # set defaults for any optional args for which values were not supplied
                   7433:     if ($who eq '') {
                   7434:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7435:     }
                   7436:     if (!$locktries) {
                   7437:         $locktries = 3;
                   7438:     }
                   7439:     if (!$maxtries) {
                   7440:         $maxtries = 10;
                   7441:     }
                   7442:     
                   7443:     if (($cdom eq '') || ($cnum eq '')) {
                   7444:         if ($env{'request.course.id'}) {
                   7445:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7446:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7447:         }
                   7448:         if (($cdom eq '') || ($cnum eq '')) {
                   7449:             return ('','ok','call to get suffix not in course context');
                   7450:         }
                   7451:     }
                   7452: 
                   7453: # construct locking item
                   7454:     my $lockhash = {
                   7455:                       $prefix."\0".'locked_'.$keyid => $who,
                   7456:                    };
                   7457:     my $tries = 0;
                   7458: 
                   7459: # attempt to get lock on nohist_$namespace file
                   7460:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7461:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7462:         $tries ++;
                   7463:         sleep 1;
                   7464:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7465:     }
                   7466: 
                   7467: # attempt to get unique identifier, based on current timestamp
                   7468:     if ($gotlock eq 'ok') {
                   7469:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7470:         my $id = time;
                   7471:         $newid = $id;
1.1268    raeburn  7472:         if ($idtype eq 'addcode') {
                   7473:             $newid .= &sixnum_code();
                   7474:         }
1.1198    raeburn  7475:         my $idtries = 0;
                   7476:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7477:             if ($idtype eq 'concat') {
                   7478:                 $newid = $id.$idtries;
1.1268    raeburn  7479:             } elsif ($idtype eq 'addcode') {
                   7480:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7481:             } else {
                   7482:                 $newid ++;
                   7483:             }
                   7484:             $idtries ++;
                   7485:         }
                   7486:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7487:             my %new_item =  (
                   7488:                               $prefix."\0".$newid => $who,
                   7489:                             );
                   7490:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7491:                                                  $cdom,$cnum);
                   7492:             if ($putresult ne 'ok') {
                   7493:                 undef($newid);
                   7494:                 $error = 'error saving new item: '.$putresult;
                   7495:             }
                   7496:         } else {
1.1268    raeburn  7497:              undef($newid);
1.1198    raeburn  7498:              $error = ('error: no unique suffix available for the new item ');
                   7499:         }
                   7500: #  remove lock
                   7501:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7502:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7503:     } else {
                   7504:         $error = "error: could not obtain lockfile\n";
                   7505:         $dellock = 'ok';
1.1276    raeburn  7506:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7507:             $dellock = 'nolock';
                   7508:         }
1.1198    raeburn  7509:     }
                   7510:     return ($newid,$dellock,$error);
                   7511: }
                   7512: 
1.1268    raeburn  7513: sub sixnum_code {
                   7514:     my $code;
                   7515:     for (0..6) {
                   7516:         $code .= int( rand(9) );
                   7517:     }
                   7518:     return $code;
                   7519: }
                   7520: 
1.765     albertel 7521: # -------------------------------------------------- portfolio access checking
                   7522: 
                   7523: sub portfolio_access {
1.1270    raeburn  7524:     my ($requrl,$clientip) = @_;
1.765     albertel 7525:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7526:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7527:     if ($result) {
                   7528:         my %setters;
                   7529:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7530:             my ($startblock,$endblock) =
                   7531:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7532:             if ($startblock && $endblock) {
                   7533:                 return 'B';
                   7534:             }
                   7535:         } else {
                   7536:             my ($startblock,$endblock) =
                   7537:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7538:             if ($startblock && $endblock) {
                   7539:                 return 'B';
                   7540:             }
                   7541:         }
                   7542:     }
1.765     albertel 7543:     if ($result eq 'ok') {
1.766     albertel 7544:        return 'F';
1.765     albertel 7545:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7546:        return 'A';
1.765     albertel 7547:     }
1.766     albertel 7548:     return '';
1.765     albertel 7549: }
                   7550: 
                   7551: sub get_portfolio_access {
1.1270    raeburn  7552:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7553: 
                   7554:     if (!ref($access_hash)) {
                   7555: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7556: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7557: 						   $file_name);
                   7558: 	$access_hash = $access_controls{$file_name};
                   7559:     }
                   7560: 
1.1270    raeburn  7561:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7562:     my $now = time;
                   7563:     if (ref($access_hash) eq 'HASH') {
                   7564:         foreach my $key (keys(%{$access_hash})) {
                   7565:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7566:             if ($start > $now) {
                   7567:                 next;
                   7568:             }
                   7569:             if ($end && $end<$now) {
                   7570:                 next;
                   7571:             }
                   7572:             if ($scope eq 'public') {
                   7573:                 $public = $key;
                   7574:                 last;
                   7575:             } elsif ($scope eq 'guest') {
                   7576:                 $guest = $key;
                   7577:             } elsif ($scope eq 'domains') {
                   7578:                 push(@domains,$key);
                   7579:             } elsif ($scope eq 'users') {
                   7580:                 push(@users,$key);
                   7581:             } elsif ($scope eq 'course') {
                   7582:                 push(@courses,$key);
                   7583:             } elsif ($scope eq 'group') {
                   7584:                 push(@groups,$key);
1.1270    raeburn  7585:             } elsif ($scope eq 'ip') {
                   7586:                 push(@ips,$key);
1.765     albertel 7587:             }
                   7588:         }
                   7589:         if ($public) {
                   7590:             return 'ok';
1.1270    raeburn  7591:         } elsif (@ips > 0) {
                   7592:             my $allowed;
                   7593:             foreach my $ipkey (@ips) {
                   7594:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7595:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7596:                         $allowed = 1;
                   7597:                         last; 
                   7598:                     }
                   7599:                 }
                   7600:             }
                   7601:             if ($allowed) {
                   7602:                 return 'ok';
                   7603:             }
1.765     albertel 7604:         }
                   7605:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7606:             if ($guest) {
                   7607:                 return $guest;
                   7608:             }
                   7609:         } else {
                   7610:             if (@domains > 0) {
                   7611:                 foreach my $domkey (@domains) {
                   7612:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7613:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7614:                             return 'ok';
                   7615:                         }
                   7616:                     }
                   7617:                 }
                   7618:             }
                   7619:             if (@users > 0) {
                   7620:                 foreach my $userkey (@users) {
1.865     raeburn  7621:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7622:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7623:                             if (ref($item) eq 'HASH') {
                   7624:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7625:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7626:                                     return 'ok';
                   7627:                                 }
                   7628:                             }
                   7629:                         }
                   7630:                     } 
1.765     albertel 7631:                 }
                   7632:             }
                   7633:             my %roleshash;
                   7634:             my @courses_and_groups = @courses;
                   7635:             push(@courses_and_groups,@groups); 
                   7636:             if (@courses_and_groups > 0) {
                   7637:                 my (%allgroups,%allroles); 
                   7638:                 my ($start,$end,$role,$sec,$group);
                   7639:                 foreach my $envkey (%env) {
1.1060    raeburn  7640:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7641:                         my $cid = $2.'_'.$3; 
                   7642:                         if ($1 eq 'gr') {
                   7643:                             $group = $4;
                   7644:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7645:                         } else {
                   7646:                             if ($4 eq '') {
                   7647:                                 $sec = 'none';
                   7648:                             } else {
                   7649:                                 $sec = $4;
                   7650:                             }
                   7651:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7652:                         }
1.811     albertel 7653:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7654:                         my $cid = $2.'_'.$3;
                   7655:                         if ($4 eq '') {
                   7656:                             $sec = 'none';
                   7657:                         } else {
                   7658:                             $sec = $4;
                   7659:                         }
                   7660:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7661:                     }
                   7662:                 }
                   7663:                 if (keys(%allroles) == 0) {
                   7664:                     return;
                   7665:                 }
                   7666:                 foreach my $key (@courses_and_groups) {
                   7667:                     my %content = %{$$access_hash{$key}};
                   7668:                     my $cnum = $content{'number'};
                   7669:                     my $cdom = $content{'domain'};
                   7670:                     my $cid = $cdom.'_'.$cnum;
                   7671:                     if (!exists($allroles{$cid})) {
                   7672:                         next;
                   7673:                     }    
                   7674:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7675:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7676:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7677:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7678:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7679:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7680:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7681:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7682:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7683:                                         if (grep/^all$/,@sections) {
                   7684:                                             return 'ok';
                   7685:                                         } else {
                   7686:                                             if (grep/^$sec$/,@sections) {
                   7687:                                                 return 'ok';
                   7688:                                             }
                   7689:                                         }
                   7690:                                     }
                   7691:                                 }
                   7692:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7693:                                     if (grep/^none$/,@groups) {
                   7694:                                         return 'ok';
                   7695:                                     }
                   7696:                                 } else {
                   7697:                                     if (grep/^all$/,@groups) {
                   7698:                                         return 'ok';
                   7699:                                     } 
                   7700:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7701:                                         if (grep/^$group$/,@groups) {
                   7702:                                             return 'ok';
                   7703:                                         }
                   7704:                                     }
                   7705:                                 } 
                   7706:                             }
                   7707:                         }
                   7708:                     }
                   7709:                 }
                   7710:             }
                   7711:             if ($guest) {
                   7712:                 return $guest;
                   7713:             }
                   7714:         }
                   7715:     }
                   7716:     return;
                   7717: }
                   7718: 
                   7719: sub course_group_datechecker {
                   7720:     my ($dates,$now,$status) = @_;
                   7721:     my ($start,$end) = split(/\./,$dates);
                   7722:     if (!$start && !$end) {
                   7723:         return 'ok';
                   7724:     }
                   7725:     if (grep/^active$/,@{$status}) {
                   7726:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7727:             return 'ok';
                   7728:         }
                   7729:     }
                   7730:     if (grep/^previous$/,@{$status}) {
                   7731:         if ($end > $now ) {
                   7732:             return 'ok';
                   7733:         }
                   7734:     }
                   7735:     if (grep/^future$/,@{$status}) {
                   7736:         if ($start > $now) {
                   7737:             return 'ok';
                   7738:         }
                   7739:     }
                   7740:     return; 
                   7741: }
                   7742: 
                   7743: sub parse_portfolio_url {
                   7744:     my ($url) = @_;
                   7745: 
                   7746:     my ($type,$udom,$unum,$group,$file_name);
                   7747:     
1.823     albertel 7748:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7749: 	$type = 1;
                   7750:         $udom = $1;
                   7751:         $unum = $2;
                   7752:         $file_name = $3;
1.823     albertel 7753:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7754: 	$type = 2;
                   7755:         $udom = $1;
                   7756:         $unum = $2;
                   7757:         $group = $3;
                   7758:         $file_name = $3.'/'.$4;
                   7759:     }
                   7760:     if (wantarray) {
                   7761: 	return ($type,$udom,$unum,$file_name,$group);
                   7762:     }
                   7763:     return $type;
                   7764: }
                   7765: 
                   7766: sub is_portfolio_url {
                   7767:     my ($url) = @_;
                   7768:     return scalar(&parse_portfolio_url($url));
                   7769: }
                   7770: 
1.798     raeburn  7771: sub is_portfolio_file {
                   7772:     my ($file) = @_;
1.820     raeburn  7773:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7774:         return 1;
                   7775:     }
                   7776:     return;
                   7777: }
                   7778: 
1.976     raeburn  7779: sub usertools_access {
1.1084    raeburn  7780:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7781:     my ($access,%tools);
                   7782:     if ($context eq '') {
                   7783:         $context = 'tools';
                   7784:     }
                   7785:     if ($context eq 'requestcourses') {
                   7786:         %tools = (
                   7787:                       official   => 1,
                   7788:                       unofficial => 1,
1.1006    raeburn  7789:                       community  => 1,
1.1246    raeburn  7790:                       textbook   => 1,
1.1305    raeburn  7791:                       placement  => 1,
1.1368    raeburn  7792:                       lti        => 1,
1.985     raeburn  7793:                  );
1.1183    raeburn  7794:     } elsif ($context eq 'requestauthor') {
                   7795:         %tools = (
                   7796:                       requestauthor => 1,
                   7797:                  );
1.985     raeburn  7798:     } else {
                   7799:         %tools = (
                   7800:                       aboutme   => 1,
                   7801:                       blog      => 1,
1.1177    raeburn  7802:                       webdav    => 1,
1.985     raeburn  7803:                       portfolio => 1,
                   7804:                  );
                   7805:     }
1.976     raeburn  7806:     return if (!defined($tools{$tool}));
                   7807: 
1.1242    raeburn  7808:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7809:         $udom = $env{'user.domain'};
                   7810:         $uname = $env{'user.name'};
                   7811:     }
                   7812: 
1.978     raeburn  7813:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7814:         if ($action ne 'reload') {
1.985     raeburn  7815:             if ($context eq 'requestcourses') {
                   7816:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7817:             } elsif ($context eq 'requestauthor') {
                   7818:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7819:             } else {
                   7820:                 return $env{'environment.availabletools.'.$tool};
                   7821:             }
                   7822:         }
1.976     raeburn  7823:     }
                   7824: 
1.1183    raeburn  7825:     my ($toolstatus,$inststatus,$envkey);
                   7826:     if ($context eq 'requestauthor') {
                   7827:         $envkey = $context; 
                   7828:     } else {
                   7829:         $envkey = $context.'.'.$tool;
                   7830:     }
1.976     raeburn  7831: 
1.985     raeburn  7832:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7833:          ($action ne 'reload')) {
1.1183    raeburn  7834:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7835:         $inststatus = $env{'environment.inststatus'};
                   7836:     } else {
1.1084    raeburn  7837:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7838:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7839:             $inststatus = $userenvref->{'inststatus'};
                   7840:         } else {
1.1183    raeburn  7841:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7842:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7843:             $inststatus = $userenv{'inststatus'};
                   7844:         }
1.976     raeburn  7845:     }
                   7846: 
                   7847:     if ($toolstatus ne '') {
                   7848:         if ($toolstatus) {
                   7849:             $access = 1;
                   7850:         } else {
                   7851:             $access = 0;
                   7852:         }
                   7853:         return $access;
                   7854:     }
                   7855: 
1.1084    raeburn  7856:     my ($is_adv,%domdef);
                   7857:     if (ref($is_advref) eq 'HASH') {
                   7858:         $is_adv = $is_advref->{'is_adv'};
                   7859:     } else {
                   7860:         $is_adv = &is_advanced_user($udom,$uname);
                   7861:     }
                   7862:     if (ref($domdefref) eq 'HASH') {
                   7863:         %domdef = %{$domdefref};
                   7864:     } else {
                   7865:         %domdef = &get_domain_defaults($udom);
                   7866:     }
1.976     raeburn  7867:     if (ref($domdef{$tool}) eq 'HASH') {
                   7868:         if ($is_adv) {
                   7869:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7870:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7871:                     $access = 1;
                   7872:                 } else {
                   7873:                     $access = 0;
                   7874:                 }
                   7875:                 return $access;
                   7876:             }
                   7877:         }
                   7878:         if ($inststatus ne '') {
                   7879:             my ($hasaccess,$hasnoaccess);
                   7880:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7881:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7882:                     if ($domdef{$tool}{$affiliation}) {
                   7883:                         $hasaccess = 1;
                   7884:                     } else {
                   7885:                         $hasnoaccess = 1;
                   7886:                     }
                   7887:                 }
                   7888:             }
                   7889:             if ($hasaccess || $hasnoaccess) {
                   7890:                 if ($hasaccess) {
                   7891:                     $access = 1;
                   7892:                 } elsif ($hasnoaccess) {
                   7893:                     $access = 0; 
                   7894:                 }
                   7895:                 return $access;
                   7896:             }
                   7897:         } else {
                   7898:             if ($domdef{$tool}{'default'} ne '') {
                   7899:                 if ($domdef{$tool}{'default'}) {
                   7900:                     $access = 1;
                   7901:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7902:                     $access = 0;
                   7903:                 }
                   7904:                 return $access;
                   7905:             }
                   7906:         }
                   7907:     } else {
1.1177    raeburn  7908:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7909:             $access = 1;
                   7910:         } else {
                   7911:             $access = 0;
                   7912:         }
1.976     raeburn  7913:         return $access;
                   7914:     }
                   7915: }
                   7916: 
1.1050    raeburn  7917: sub is_course_owner {
                   7918:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7919:     if (($udom eq '') || ($uname eq '')) {
                   7920:         $udom = $env{'user.domain'};
                   7921:         $uname = $env{'user.name'};
                   7922:     }
                   7923:     unless (($udom eq '') || ($uname eq '')) {
                   7924:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7925:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7926:                 return 1;
                   7927:             } else {
                   7928:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7929:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7930:                     return 1;
                   7931:                 }
                   7932:             }
                   7933:         }
                   7934:     }
                   7935:     return;
                   7936: }
                   7937: 
1.976     raeburn  7938: sub is_advanced_user {
                   7939:     my ($udom,$uname) = @_;
1.1085    raeburn  7940:     if ($udom ne '' && $uname ne '') {
                   7941:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7942:             if (wantarray) {
                   7943:                 return ($env{'user.adv'},$env{'user.author'});
                   7944:             } else {
                   7945:                 return $env{'user.adv'};
                   7946:             }
1.1085    raeburn  7947:         }
                   7948:     }
1.976     raeburn  7949:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7950:     my %allroles;
1.1128    raeburn  7951:     my ($is_adv,$is_author);
1.976     raeburn  7952:     foreach my $role (keys(%roleshash)) {
                   7953:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7954:         my $area = '/'.$tdomain.'/'.$trest;
                   7955:         if ($sec ne '') {
                   7956:             $area .= '/'.$sec;
                   7957:         }
                   7958:         if (($area ne '') && ($trole ne '')) {
                   7959:             my $spec=$trole.'.'.$area;
                   7960:             if ($trole =~ /^cr\//) {
                   7961:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7962:             } elsif ($trole ne 'gr') {
                   7963:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7964:             }
1.1128    raeburn  7965:             if ($trole eq 'au') {
                   7966:                 $is_author = 1;
                   7967:             }
1.976     raeburn  7968:         }
                   7969:     }
                   7970:     foreach my $role (keys(%allroles)) {
                   7971:         last if ($is_adv);
                   7972:         foreach my $item (split(/:/,$allroles{$role})) {
                   7973:             if ($item ne '') {
                   7974:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7975:                 if ($privilege eq 'adv') {
                   7976:                     $is_adv = 1;
                   7977:                     last;
                   7978:                 }
                   7979:             }
                   7980:         }
                   7981:     }
1.1128    raeburn  7982:     if (wantarray) {
                   7983:         return ($is_adv,$is_author);
                   7984:     }
1.976     raeburn  7985:     return $is_adv;
                   7986: }
1.798     raeburn  7987: 
1.1035    raeburn  7988: sub check_can_request {
1.1368    raeburn  7989:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7990:     my $canreq = 0;
1.1368    raeburn  7991:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7992:         $uname = $env{'user.name'};
                   7993:         $udom = $env{'user.domain'};
                   7994:     }
1.1035    raeburn  7995:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7996:     my @options = ('approval','validate','autolimit');
                   7997:     my $optregex = join('|',@options);
                   7998:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7999:         foreach my $type (@{$types}) {
1.1368    raeburn  8000:             if (&usertools_access($uname,$udom,$type,undef,
                   8001:                                   'requestcourses')) {
1.1035    raeburn  8002:                 $canreq ++;
1.1036    raeburn  8003:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  8004:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8005:                 }
1.1368    raeburn  8006:                 if ($dom eq $udom) {
1.1035    raeburn  8007:                     $can_request->{$type} = 1;
                   8008:                 }
                   8009:             }
1.1368    raeburn  8010:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8011:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8012:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8013:                 if (@curr > 0) {
1.1036    raeburn  8014:                     foreach my $item (@curr) {
                   8015:                         if (ref($request_domains) eq 'HASH') {
                   8016:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8017:                             if ($otherdom ne '') {
                   8018:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8019:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8020:                                         push(@{$request_domains->{$type}},$otherdom);
                   8021:                                     }
                   8022:                                 } else {
                   8023:                                     push(@{$request_domains->{$type}},$otherdom);
                   8024:                                 }
                   8025:                             }
                   8026:                         }
                   8027:                     }
1.1368    raeburn  8028:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8029:                         $canreq ++;
1.1035    raeburn  8030:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8031:                             $can_request->{$type} = 1;
                   8032:                         }
                   8033:                     }
                   8034:                 }
                   8035:             }
                   8036:         }
                   8037:     }
                   8038:     return $canreq;
                   8039: }
                   8040: 
1.341     www      8041: # ---------------------------------------------- Custom access rule evaluation
                   8042: 
                   8043: sub customaccess {
                   8044:     my ($priv,$uri)=@_;
1.807     albertel 8045:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8046:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8047:     $udom = &LONCAPA::clean_domain($udom);
                   8048:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8049:     my $access=0;
1.800     albertel 8050:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8051: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8052: 	if ($type eq 'user') {
                   8053: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8054: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8055: 		if ($tdom) {
                   8056: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8057: 		}
1.896     albertel 8058: 		if ($tuname) {
                   8059: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8060: 		}
                   8061: 		$access=($effect eq 'allow');
                   8062: 		last;
                   8063: 	    }
                   8064: 	} else {
                   8065: 	    if ($role) {
                   8066: 		if ($role ne $urole) { next; }
                   8067: 	    }
                   8068: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8069: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8070: 		if ($tdom) {
                   8071: 		    if ($tdom ne $udom) { next; }
                   8072: 		}
                   8073: 		if ($tcrs) {
                   8074: 		    if ($tcrs ne $ucrs) { next; }
                   8075: 		}
                   8076: 		if ($tsec) {
                   8077: 		    if ($tsec ne $usec) { next; }
                   8078: 		}
                   8079: 		$access=($effect eq 'allow');
                   8080: 		last;
                   8081: 	    }
                   8082: 	    if ($realm eq '' && $role eq '') {
                   8083: 		$access=($effect eq 'allow');
                   8084: 	    }
1.402     bowersj2 8085: 	}
1.341     www      8086:     }
                   8087:     return $access;
                   8088: }
                   8089: 
1.103     harris41 8090: # ------------------------------------------------- Check for a user privilege
1.12      www      8091: 
                   8092: sub allowed {
1.1424    raeburn  8093:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 8094:     my $ver_orguri=$uri;
1.439     www      8095:     $uri=&deversion($uri);
1.152     www      8096:     my $orguri=$uri;
1.52      www      8097:     $uri=&declutter($uri);
1.809     raeburn  8098: 
1.810     raeburn  8099:     if ($priv eq 'evb') {
                   8100: # Evade communication block restrictions for specified role in a course
                   8101:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8102:             return $1;
                   8103:         } else {
                   8104:             return;
                   8105:         }
                   8106:     }
                   8107: 
1.620     albertel 8108:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8109: # Free bre access to adm and meta resources
1.1436    raeburn  8110:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8111: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8112: 	&& ($priv eq 'bre')) {
1.14      www      8113: 	return 'F';
1.159     www      8114:     }
                   8115: 
1.545     banghart 8116: # Free bre access to user's own portfolio contents
1.714     raeburn  8117:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8118:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8119: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8120:         my %setters;
                   8121:         my ($startblock,$endblock) = 
                   8122:             &Apache::loncommon::blockcheck(\%setters,'port');
                   8123:         if ($startblock && $endblock) {
                   8124:             return 'B';
                   8125:         } else {
                   8126:             return 'F';
                   8127:         }
1.545     banghart 8128:     }
                   8129: 
1.762     raeburn  8130: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8131:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8132:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8133:         if (exists($env{'request.course.id'})) {
                   8134:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8135:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8136:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8137:                 my $courseprivid=$env{'request.course.id'};
                   8138:                 $courseprivid=~s/\_/\//;
                   8139:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8140:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8141:                     return $1; 
1.762     raeburn  8142:                 } else {
                   8143:                     if ($env{'request.course.sec'}) {
                   8144:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8145:                     }
                   8146:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8147:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8148:                         return $2;
                   8149:                     }
1.714     raeburn  8150:                 }
                   8151:             }
                   8152:         }
                   8153:     }
                   8154: 
1.159     www      8155: # Free bre to public access
                   8156: 
                   8157:     if ($priv eq 'bre') {
1.1362    raeburn  8158:         my $copyright;
                   8159:         unless ($uri =~ /ext\.tool/) {
                   8160:             $copyright=&metadata($uri,'copyright');
                   8161:         }
1.620     albertel 8162: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8163:            return 'F'; 
                   8164:         }
1.238     www      8165:         if ($copyright eq 'priv') {
                   8166:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8167: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8168: 		return '';
                   8169:             }
                   8170:         }
                   8171:         if ($copyright eq 'domain') {
                   8172:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8173: 	    unless (($env{'user.domain'} eq $1) ||
                   8174:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8175: 		return '';
                   8176:             }
1.262     matthew  8177:         }
1.620     albertel 8178:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8179:             # Library role, so allow browsing of resources in this domain.
                   8180:             return 'F';
1.238     www      8181:         }
1.341     www      8182:         if ($copyright eq 'custom') {
                   8183: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8184:         }
1.14      www      8185:     }
1.264     matthew  8186:     # Domain coordinator is trying to create a course
1.620     albertel 8187:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8188:         # uri is the requested domain in this case.
                   8189:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8190:         # a role of dc for the domain in question.
1.620     albertel 8191:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8192:     }
1.29      www      8193: 
1.52      www      8194:     my $thisallowed='';
                   8195:     my $statecond=0;
                   8196:     my $courseprivid='';
                   8197: 
1.1039    raeburn  8198:     my $ownaccess;
1.1043    raeburn  8199:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8200:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8201:         if ($uri eq '') {
                   8202:             $ownaccess = 1;
                   8203:         } else {
                   8204:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8205:                 my $udom = $env{'user.domain'};
                   8206:                 my $uname = $env{'user.name'};
                   8207:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8208:                     $ownaccess = 1;
1.1040    raeburn  8209:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8210:                     unless ($uri =~ m{\.\./}) {
                   8211:                         $ownaccess = 1;
                   8212:                     }
                   8213:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8214:                     my $now = time;
                   8215:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8216:                         my $adom = $1;
                   8217:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8218:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  8219:                                 my ($start,$end) = split('.',$env{$key});
                   8220:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8221:                                     $ownaccess = 1;
                   8222:                                     last;
                   8223:                                 }
                   8224:                             }
                   8225:                         }
                   8226:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8227:                         my $adom = $1;
                   8228:                         my $aname = $2;
1.1042    raeburn  8229:                         foreach my $role ('ca','aa') { 
                   8230:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8231:                                 my ($start,$end) =
                   8232:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   8233:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8234:                                     $ownaccess = 1;
                   8235:                                     last;
                   8236:                                 }
1.1039    raeburn  8237:                             }
                   8238:                         }
                   8239:                     }
                   8240:                 }
                   8241:             }
                   8242:         }
                   8243:     }
                   8244: 
1.52      www      8245: # Course
                   8246: 
1.620     albertel 8247:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8248:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8249:             $thisallowed.=$1;
                   8250:         }
1.52      www      8251:     }
1.29      www      8252: 
1.52      www      8253: # Domain
                   8254: 
1.620     albertel 8255:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8256:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8257:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8258:             $thisallowed.=$1;
                   8259:         }
1.12      www      8260:     }
1.52      www      8261: 
1.1141    raeburn  8262: # User who is not author or co-author might still be able to edit
                   8263: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8264:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8265:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8266:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8267:             $thisallowed.=$1;
                   8268:         }
                   8269:     }
                   8270: 
1.52      www      8271: # Course: uri itself is a course
1.66      www      8272:     my $courseuri=$uri;
                   8273:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8274:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8275: 
1.620     albertel 8276:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8277:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8278:         if ($priv eq 'mip') {
                   8279:             my $rem = $1;
                   8280:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8281:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8282:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8283:                 if ($cdom ne '') {
1.1410    raeburn  8284:                     my %passwdconf = &get_passwdconf($cdom);
                   8285:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8286:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8287:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8288:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8289:                                 unless (@inststatuses) {
                   8290:                                     @inststatuses = ('default');
                   8291:                                 }
                   8292:                                 foreach my $status (@inststatuses) {
                   8293:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8294:                                         $thisallowed.=$rem;
                   8295:                                     }
                   8296:                                 }
                   8297:                             }
                   8298:                         }
1.1409    raeburn  8299:                     }
                   8300:                 }
                   8301:             }
                   8302:         } else {
                   8303:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8304:                 $thisallowed.=$1;
                   8305:             }
1.1039    raeburn  8306:         }
1.12      www      8307:     }
1.29      www      8308: 
1.665     albertel 8309: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8310: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8311:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8312: 	$thisallowed='';
1.671     raeburn  8313:         my ($match)=&is_on_map($uri);
                   8314:         if ($match) {
                   8315:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8316:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8317:                 my $value = $1;
1.1402    raeburn  8318:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8319:                 if ($deeplinkblock) {
                   8320:                     $thisallowed='D';
                   8321:                 } elsif ($noblockcheck) {
1.1281    raeburn  8322:                     $thisallowed.=$value;
1.1162    raeburn  8323:                 } else {
1.1424    raeburn  8324:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8325:                     if (@blockers > 0) {
                   8326:                         $thisallowed = 'B';
                   8327:                     } else {
                   8328:                         $thisallowed.=$value;
                   8329:                     }
1.1162    raeburn  8330:                 }
1.671     raeburn  8331:             }
                   8332:         } else {
1.705     albertel 8333:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8334:             if ($refuri) {
                   8335:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8336:                     $thisallowed='F';
1.671     raeburn  8337:                 } else {
                   8338:                     $refuri=&declutter($refuri);
                   8339:                     my ($match) = &is_on_map($refuri);
                   8340:                     if ($match) {
1.1402    raeburn  8341:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8342:                         if ($deeplinkblock) {
                   8343:                             $thisallowed='D';
                   8344:                         } elsif ($noblockcheck) {
1.1281    raeburn  8345:                             $thisallowed='F';
1.1162    raeburn  8346:                         } else {
1.1426    raeburn  8347:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8348:                             if (@blockers > 0) {
                   8349:                                 $thisallowed = 'B';
                   8350:                             } else {
                   8351:                                 $thisallowed='F';
                   8352:                             }
1.1162    raeburn  8353:                         }
1.671     raeburn  8354:                     }
1.669     raeburn  8355:                 }
1.671     raeburn  8356:             }
                   8357:         }
1.314     www      8358:     }
1.492     albertel 8359: 
1.766     albertel 8360:     if ($priv eq 'bre'
                   8361: 	&& $thisallowed ne 'F' 
                   8362: 	&& $thisallowed ne '2'
                   8363: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8364: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8365:     }
1.1250    raeburn  8366: 
1.52      www      8367: # Full access at system, domain or course-wide level? Exit.
1.29      www      8368:     if ($thisallowed=~/F/) {
                   8369: 	return 'F';
                   8370:     }
                   8371: 
1.52      www      8372: # If this is generating or modifying users, exit with special codes
1.29      www      8373: 
1.643     www      8374:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8375: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8376: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8377: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8378: 	    unless ($auname) { return $thisallowed; }
                   8379: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8380: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8381: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8382: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8383: 	}
1.52      www      8384: 	return $thisallowed;
                   8385:     }
                   8386: #
1.103     harris41 8387: # Gathered so far: system, domain and course wide privileges
1.52      www      8388: #
                   8389: # Course: See if uri or referer is an individual resource that is part of 
                   8390: # the course
                   8391: 
1.620     albertel 8392:     if ($env{'request.course.id'}) {
1.232     www      8393: 
1.1409    raeburn  8394: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8395: 
                   8396:         if ($priv eq 'mip') {
                   8397:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8398:                 return $thisallowed;
                   8399:             } else {
                   8400:                 return '';
                   8401:             }
                   8402:         }
                   8403: 
1.620     albertel 8404:        $courseprivid=$env{'request.course.id'};
                   8405:        if ($env{'request.course.sec'}) {
                   8406:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8407:        }
                   8408:        $courseprivid=~s/\_/\//;
                   8409:        my $checkreferer=1;
1.232     www      8410:        my ($match,$cond)=&is_on_map($uri);
                   8411:        if ($match) {
                   8412:            $statecond=$cond;
1.620     albertel 8413:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8414:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8415:                my $value = $1;
                   8416:                if ($priv eq 'bre') {
1.1281    raeburn  8417:                    if ($noblockcheck) {
                   8418:                        $thisallowed.=$value;
1.1162    raeburn  8419:                    } else {
1.1424    raeburn  8420:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8421:                        if (@blockers > 0) {
                   8422:                            $thisallowed = 'B';
                   8423:                        } else {
                   8424:                            $thisallowed.=$value;
                   8425:                        }
1.1162    raeburn  8426:                    }
                   8427:                } else {
                   8428:                    $thisallowed.=$value;
                   8429:                }
1.52      www      8430:                $checkreferer=0;
                   8431:            }
1.29      www      8432:        }
1.1424    raeburn  8433: 
1.148     www      8434:        if ($checkreferer) {
1.620     albertel 8435: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8436:             unless ($refuri) {
1.800     albertel 8437:                 foreach my $key (keys(%env)) {
                   8438: 		    if ($key=~/^httpref\..*\*/) {
                   8439: 			my $pattern=$key;
1.156     www      8440:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8441:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8442:                         $pattern=~s/\//\\\//g;
1.152     www      8443:                         if ($orguri=~/$pattern/) {
1.800     albertel 8444: 			    $refuri=$env{$key};
1.148     www      8445:                         }
                   8446:                     }
1.191     harris41 8447:                 }
1.148     www      8448:             }
1.232     www      8449: 
1.148     www      8450:          if ($refuri) { 
1.152     www      8451: 	  $refuri=&declutter($refuri);
1.232     www      8452:           my ($match,$cond)=&is_on_map($refuri);
                   8453:             if ($match) {
                   8454:               my $refstatecond=$cond;
1.620     albertel 8455:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8456:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8457:                   my $value = $1;
                   8458:                   if ($priv eq 'bre') {
1.1402    raeburn  8459:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8460:                       if ($deeplinkblock) {
                   8461:                           $thisallowed = 'D';
                   8462:                       } elsif ($noblockcheck) {
1.1281    raeburn  8463:                           $thisallowed.=$value;
1.1162    raeburn  8464:                       } else {
1.1426    raeburn  8465:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8466:                           if (@blockers > 0) {
                   8467:                               $thisallowed = 'B';
                   8468:                           } else {
                   8469:                               $thisallowed.=$value;
                   8470:                           }
1.1162    raeburn  8471:                       }
                   8472:                   } else {
                   8473:                       $thisallowed.=$value;
                   8474:                   }
1.53      www      8475:                   $uri=$refuri;
                   8476:                   $statecond=$refstatecond;
1.52      www      8477:               }
                   8478:           }
1.148     www      8479:         }
1.29      www      8480:        }
1.52      www      8481:    }
1.29      www      8482: 
1.52      www      8483: #
1.103     harris41 8484: # Gathered now: all privileges that could apply, and condition number
1.52      www      8485: # 
                   8486: #
                   8487: # Full or no access?
                   8488: #
1.29      www      8489: 
1.52      www      8490:     if ($thisallowed=~/F/) {
                   8491: 	return 'F';
                   8492:     }
1.29      www      8493: 
1.52      www      8494:     unless ($thisallowed) {
                   8495:         return '';
                   8496:     }
1.29      www      8497: 
1.52      www      8498: # Restrictions exist, deal with them
                   8499: #
                   8500: #   C:according to course preferences
                   8501: #   R:according to resource settings
                   8502: #   L:unless locked
                   8503: #   X:according to user session state
                   8504: #
                   8505: 
                   8506: # Possibly locked functionality, check all courses
1.54      www      8507: # Locks might take effect only after 10 minutes cache expiration for other
                   8508: # courses, and 2 minutes for current course
1.52      www      8509: 
                   8510:     my $envkey;
                   8511:     if ($thisallowed=~/L/) {
1.1000    raeburn  8512:         foreach $envkey (keys(%env)) {
1.54      www      8513:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8514:                my $courseid=$2;
                   8515:                my $roleid=$1.'.'.$2;
1.92      www      8516:                $courseid=~s/^\///;
1.54      www      8517:                my $expiretime=600;
1.620     albertel 8518:                if ($env{'request.role'} eq $roleid) {
1.54      www      8519: 		  $expiretime=120;
                   8520:                }
                   8521: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8522:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8523:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8524: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8525:                }
1.620     albertel 8526:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8527:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8528: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8529:                        &log($env{'user.domain'},$env{'user.name'},
                   8530:                             $env{'user.home'},
1.57      www      8531:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8532:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8533:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8534: 		       return '';
                   8535:                    }
                   8536:                }
1.620     albertel 8537:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8538:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8539: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8540:                        &log($env{'user.domain'},$env{'user.name'},
                   8541:                             $env{'user.home'},
1.57      www      8542:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8543:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8544:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8545: 		       return '';
                   8546:                    }
                   8547:                }
                   8548: 	   }
1.29      www      8549:        }
1.52      www      8550:     }
1.1424    raeburn  8551: 
1.52      www      8552: #
                   8553: # Rest of the restrictions depend on selected course
                   8554: #
                   8555: 
1.620     albertel 8556:     unless ($env{'request.course.id'}) {
1.766     albertel 8557: 	if ($thisallowed eq 'A') {
                   8558: 	    return 'A';
1.814     raeburn  8559:         } elsif ($thisallowed eq 'B') {
                   8560:             return 'B';
1.766     albertel 8561: 	} else {
                   8562: 	    return '1';
                   8563: 	}
1.52      www      8564:     }
1.29      www      8565: 
1.52      www      8566: #
                   8567: # Now user is definitely in a course
                   8568: #
1.53      www      8569: 
                   8570: 
                   8571: # Course preferences
                   8572: 
                   8573:    if ($thisallowed=~/C/) {
1.620     albertel 8574:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8575:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8576:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8577: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8578: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8579: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8580: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8581: 			$env{'request.course.id'});
                   8582: 	   }
1.237     www      8583:            return '';
                   8584:        }
                   8585: 
1.620     albertel 8586:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8587: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8588: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8589: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8590: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8591: 			$env{'request.course.id'});
                   8592: 	   }
1.54      www      8593:            return '';
                   8594:        }
1.53      www      8595:    }
                   8596: 
                   8597: # Resource preferences
                   8598: 
                   8599:    if ($thisallowed=~/R/) {
1.620     albertel 8600:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8601:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8602: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8603: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8604: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8605: 	   }
                   8606: 	   return '';
1.54      www      8607:        }
1.53      www      8608:    }
1.30      www      8609: 
1.246     www      8610: # Restricted by state or randomout?
1.30      www      8611: 
1.52      www      8612:    if ($thisallowed=~/X/) {
1.620     albertel 8613:       if ($env{'acc.randomout'}) {
1.579     albertel 8614: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8615:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8616:             return ''; 
                   8617:          }
1.247     www      8618:       }
                   8619:       if (&condval($statecond)) {
1.52      www      8620: 	 return '2';
                   8621:       } else {
                   8622:          return '';
                   8623:       }
                   8624:    }
1.30      www      8625: 
1.766     albertel 8626:     if ($thisallowed eq 'A') {
                   8627: 	return 'A';
1.814     raeburn  8628:     } elsif ($thisallowed eq 'B') {
                   8629:         return 'B';
1.1402    raeburn  8630:     } elsif ($thisallowed eq 'D') {
                   8631:         return 'D';
1.766     albertel 8632:     }
1.52      www      8633:    return 'F';
1.232     www      8634: }
1.1162    raeburn  8635: 
1.1192    raeburn  8636: # ------------------------------------------- Check construction space access
                   8637: 
                   8638: sub constructaccess {
                   8639:     my ($url,$setpriv)=@_;
                   8640: 
                   8641: # We do not allow editing of previous versions of files
                   8642:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8643: 
                   8644: # Get username and domain from URL
                   8645:     my ($ownername,$ownerdomain,$ownerhome);
                   8646: 
                   8647:     ($ownerdomain,$ownername) =
1.1325    raeburn  8648:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8649: 
                   8650: # The URL does not really point to any authorspace, forget it
                   8651:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8652: 
                   8653: # Now we need to see if the user has access to the authorspace of
                   8654: # $ownername at $ownerdomain
                   8655: 
                   8656:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8657: # Real author for this?
                   8658:        $ownerhome = $env{'user.home'};
                   8659:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8660:           return ($ownername,$ownerdomain,$ownerhome);
                   8661:        }
                   8662:     } else {
                   8663: # Co-author for this?
                   8664:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8665:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8666:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8667:             return ($ownername,$ownerdomain,$ownerhome);
                   8668:         }
1.1312    raeburn  8669:         if ($env{'request.course.id'}) {
                   8670:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8671:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8672:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8673:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8674:                     return ($ownername,$ownerdomain,$ownerhome);
                   8675:                 }
                   8676:             }
                   8677:         }
1.1192    raeburn  8678:     }
                   8679: 
                   8680: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8681: # we might as well leave
                   8682:    unless ($setpriv) { return ''; }
                   8683: 
                   8684: # Backdoor access?
                   8685:     my $allowed=&allowed('eco',$ownerdomain);
                   8686: # Nope
                   8687:     unless ($allowed) { return ''; }
                   8688: # Looks like we may have access, but could be locked by the owner of the construction space
                   8689:     if ($allowed eq 'U') {
                   8690:         my %blocked=&get('environment',['domcoord.author'],
                   8691:                          $ownerdomain,$ownername);
                   8692: # Is blocked by owner
                   8693:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8694:     }
                   8695:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8696: # Grant temporary access
                   8697:         my $then=$env{'user.login.time'};
1.1209    raeburn  8698:         my $update=$env{'user.update.time'};
1.1192    raeburn  8699:         if (!$update) { $update = $then; }
                   8700:         my $refresh=$env{'user.refresh.time'};
                   8701:         if (!$refresh) { $refresh = $update; }
                   8702:         my $now = time;
                   8703:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8704:                            $now,'ca','constructaccess');
                   8705:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8706:         return($ownername,$ownerdomain,$ownerhome);
                   8707:     }
                   8708: # No business here
                   8709:     return '';
                   8710: }
                   8711: 
1.1282    raeburn  8712: # ----------------------------------------------------------- Content Blocking
                   8713: 
                   8714: {
                   8715: # Caches for faster Course Contents display where content blocking
                   8716: # is in operation (i.e., interval param set) for timed quiz.
                   8717: #
                   8718: # User for whom data are being temporarily cached.
                   8719: my $cacheduser='';
1.1424    raeburn  8720: # Course for which data are being temporarily cached.
                   8721: my $cachedcid='';
1.1282    raeburn  8722: # Cached blockers for this user (a hash of blocking items). 
                   8723: my %cachedblockers=();
                   8724: # When the data were last cached.
                   8725: my $cachedlast='';
                   8726: 
                   8727: sub load_all_blockers {
1.1427    raeburn  8728:     my ($uname,$udom)=@_;
1.1282    raeburn  8729:     if (($uname ne '') && ($udom ne '')) { 
                   8730:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  8731:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  8732:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  8733:             return;
                   8734:         }
                   8735:     }
                   8736:     $cachedlast=time;
                   8737:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  8738:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  8739:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  8740:     return;
1.1282    raeburn  8741: }
                   8742: 
1.1162    raeburn  8743: sub get_comm_blocks {
                   8744:     my ($cdom,$cnum) = @_;
                   8745:     if ($cdom eq '' || $cnum eq '') {
                   8746:         return unless ($env{'request.course.id'});
                   8747:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8748:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8749:     }
                   8750:     my %commblocks;
                   8751:     my $hashid=$cdom.'_'.$cnum;
                   8752:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8753:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8754:         %commblocks = %{$blocksref};
                   8755:     } else {
                   8756:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8757:         my $cachetime = 600;
                   8758:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8759:     }
                   8760:     return %commblocks;
                   8761: }
                   8762: 
1.1282    raeburn  8763: sub get_commblock_resources {
                   8764:     my ($blocks) = @_;
                   8765:     my %blockers = ();
                   8766:     return %blockers unless ($env{'request.course.id'});
                   8767:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8768:     my %commblocks;
                   8769:     if (ref($blocks) eq 'HASH') {
                   8770:         %commblocks = %{$blocks};
                   8771:     } else {
                   8772:         %commblocks = &get_comm_blocks();
                   8773:     }
1.1282    raeburn  8774:     return %blockers unless (keys(%commblocks) > 0); 
                   8775:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8776:     return %blockers unless (ref($navmap));
1.1162    raeburn  8777:     my $now = time;
                   8778:     foreach my $block (keys(%commblocks)) {
                   8779:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8780:             my ($start,$end) = ($1,$2);
                   8781:             if ($start <= $now && $end >= $now) {
                   8782:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8783:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8784:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8785:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8786:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8787:                             }
                   8788:                         }
                   8789:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8790:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8791:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8792:                             }
                   8793:                         }
                   8794:                     }
                   8795:                 }
                   8796:             }
                   8797:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8798:             my $item = $1;
1.1163    raeburn  8799:             my @to_test;
1.1162    raeburn  8800:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8801:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8802:                     my @interval;
                   8803:                     my $type = 'map';
                   8804:                     if ($item eq 'course') {
                   8805:                         $type = 'course';
                   8806:                         @interval=&EXT("resource.0.interval");
                   8807:                     } else {
                   8808:                         if ($item =~ /___\d+___/) {
                   8809:                             $type = 'resource';
                   8810:                             @interval=&EXT("resource.0.interval",$item);
                   8811:                             if (ref($navmap)) {                        
                   8812:                                 my $res = $navmap->getBySymb($item); 
                   8813:                                 push(@to_test,$res);
                   8814:                             }
1.1162    raeburn  8815:                         } else {
1.1282    raeburn  8816:                             my $mapsymb = &symbread($item,1);
                   8817:                             if ($mapsymb) {
                   8818:                                 if (ref($navmap)) {
                   8819:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1428    raeburn  8820:                                     if (ref($mapres)) {
                   8821:                                         my $first = $mapres->map_start();
                   8822:                                         my $finish = $mapres->map_finish();
                   8823:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
1.1429    raeburn  8824:                                         if (ref($it)) {
                   8825:                                             my $res;
                   8826:                                             while ($res = $it->next(undef,1)) {
                   8827:                                                 next unless (ref($res));
                   8828:                                                 my $symb = $res->symb();
                   8829:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8830:                                                 @interval=&EXT("resource.0.interval",$symb);
                   8831:                                                 if ($interval[1] eq 'map') {
                   8832:                                                     if ($res->answerable()) {
                   8833:                                                         push(@to_test,$res);
                   8834:                                                         last;
                   8835:                                                     }
1.1428    raeburn  8836:                                                 }
1.1162    raeburn  8837:                                             }
                   8838:                                         }
                   8839:                                     }
                   8840:                                 }
                   8841:                             }
                   8842:                         }
1.1282    raeburn  8843:                     }
1.1310    raeburn  8844:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8845:                         my $timelimit = $1; 
1.1282    raeburn  8846:                         my $first_access;
                   8847:                         if ($type eq 'resource') {
                   8848:                             $first_access=&get_first_access($interval[1],$item);
                   8849:                         } elsif ($type eq 'map') {
                   8850:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8851:                         } else {
                   8852:                             $first_access=&get_first_access($interval[1]);
                   8853:                         }
                   8854:                         if ($first_access) {
1.1292    raeburn  8855:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8856:                             if ($timesup > $now) {
                   8857:                                 my $activeblock;
                   8858:                                 foreach my $res (@to_test) {
1.1283    raeburn  8859:                                     if ($res->answerable()) {
1.1282    raeburn  8860:                                         $activeblock = 1;
                   8861:                                         last;
                   8862:                                     }
                   8863:                                 }
                   8864:                                 if ($activeblock) {
                   8865:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8866:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8867:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8868:                                          }
                   8869:                                     }
                   8870:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8871:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8872:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8873:                                         }
1.1162    raeburn  8874:                                     }
                   8875:                                 }
                   8876:                             }
                   8877:                         }
                   8878:                     }
                   8879:                 }
                   8880:             }
                   8881:         }
                   8882:     }
1.1282    raeburn  8883:     return %blockers;
1.1162    raeburn  8884: }
                   8885: 
1.1282    raeburn  8886: sub has_comm_blocking {
1.1427    raeburn  8887:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  8888:     my @blockers;
                   8889:     return unless ($env{'request.course.id'});
                   8890:     return unless ($priv eq 'bre');
                   8891:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8892:     return if ($env{'request.state'} eq 'construct');
1.1427    raeburn  8893:     my %blockinfo;
                   8894:     if (ref($blocks) eq 'HASH') {
                   8895:         %blockinfo = &get_commblock_resources($blocks);
                   8896:     } else {
                   8897:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8898:         %blockinfo = %cachedblockers;
                   8899:     }
                   8900:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  8901:     my (%possibles,@symbs);
                   8902:     if (!$symb) {
1.1427    raeburn  8903:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8904:     }
1.1282    raeburn  8905:     if ($symb) {
                   8906:         @symbs = ($symb);
                   8907:     } elsif (keys(%possibles)) { 
                   8908:         @symbs = keys(%possibles);
                   8909:     }
                   8910:     my $noblock;
                   8911:     foreach my $symb (@symbs) {
                   8912:         last if ($noblock);
                   8913:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  8914:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  8915:             if ($block =~ /^firstaccess____(.+)$/) {
                   8916:                 my $item = $1;
1.1424    raeburn  8917:                 unless ($blocked) {
                   8918:                     if (($item eq $map) || ($item eq $symb)) {
                   8919:                         $noblock = 1;
                   8920:                         last;
                   8921:                     }
1.1282    raeburn  8922:                 }
                   8923:             }
1.1427    raeburn  8924:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8925:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8926:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  8927:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8928:                             push(@blockers,$block);
                   8929:                         }
                   8930:                     }
                   8931:                 }
1.1427    raeburn  8932:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8933:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  8934:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8935:                             push(@blockers,$block);
                   8936:                         }
1.1282    raeburn  8937:                     }
                   8938:                 }
1.1162    raeburn  8939:             }
                   8940:         }
                   8941:     }
1.1424    raeburn  8942:     unless ($noblock) { 
                   8943:         return @blockers;
                   8944:     }
                   8945:     return;
1.1282    raeburn  8946: }
1.1162    raeburn  8947: }
                   8948: 
1.1402    raeburn  8949: sub deeplink_check {
                   8950:     my ($priv,$symb,$uri) = @_;
                   8951:     return unless ($env{'request.course.id'});
                   8952:     return unless ($priv eq 'bre');
                   8953:     return if ($env{'request.state'} eq 'construct');
                   8954:     return if ($env{'request.role.adv'});
                   8955:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8956:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8957:     my (%possibles,@symbs);
                   8958:     if (!$symb) {
                   8959:         $symb = &symbread($uri,1,1,1,\%possibles);
                   8960:     }
                   8961:     if ($symb) {
                   8962:         @symbs = ($symb);
                   8963:     } elsif (keys(%possibles)) {
                   8964:         @symbs = keys(%possibles);
                   8965:     }
                   8966: 
                   8967:     my ($login,$switchrole,$allow);
                   8968:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   8969:         my $key = $1;
                   8970:         my $tinyurl;
                   8971:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   8972:         if (defined($cached)) {
                   8973:              $tinyurl = $result;
                   8974:         } else {
                   8975:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   8976:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   8977:              if ($currtiny{$key} ne '') {
                   8978:                  $tinyurl = $currtiny{$key};
                   8979:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   8980:              }
                   8981:         }
                   8982:         if ($tinyurl ne '') {
                   8983:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
                   8984:             if ($cnumreq eq $cnum) {
                   8985:                 $login = $posslogin;
                   8986:             } else {
                   8987:                 $switchrole = 1;
                   8988:             }
                   8989:         }
                   8990:     }
                   8991:     foreach my $symb (@symbs) {
                   8992:         last if ($allow);
                   8993:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8994:         if ($deeplink eq '') {
                   8995:             $allow = 1;
                   8996:         } else {
                   8997:             my ($listed,$scope,$access) = split(/,/,$deeplink);
                   8998:             if ($access eq 'any') {
                   8999:                 $allow = 1;
                   9000:             } elsif ($login) {
                   9001:                 if ($access eq 'only') {
                   9002:                     if ($scope eq 'res') {
                   9003:                         if ($symb eq $login) {
                   9004:                             $allow = 1;
                   9005:                         }
                   9006:                     } elsif ($scope eq 'map') {
                   9007: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
                   9008:                     } elsif ($scope eq 'rec') {
                   9009: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
                   9010:                     }
                   9011:                 } else {
                   9012:                     my ($acctype,$item) = split(/:/,$access);
                   9013:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
                   9014:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
                   9015:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   9016:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
                   9017:                                 $allow = 1;
                   9018:                             }
                   9019:                         }
                   9020:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9021:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9022:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   9023:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
                   9024:                                 $allow = 1;
                   9025:                             }
                   9026:                         }
                   9027:                     }
                   9028:                 }
                   9029:             }
                   9030:         }
                   9031:     }
                   9032:     return if ($allow);
                   9033:     return 1;
                   9034: }
                   9035: 
1.1282    raeburn  9036: # -------------------------------- Deversion and split uri into path an filename   
                   9037: 
1.1133    foxr     9038: #
1.1282    raeburn  9039: #   Removes the version from a URI and
1.1133    foxr     9040: #   splits it in to its filename and path to the filename.
                   9041: #   Seems like File::Basename could have done this more clearly.
                   9042: #   Parameters:
                   9043: #      $uri   - input URI
                   9044: #   Returns:
                   9045: #     Two element list consisting of 
                   9046: #     $pathname  - the URI up to and excluding the trailing /
                   9047: #     $filename  - The part of the URI following the last /
                   9048: #  NOTE:
                   9049: #    Another realization of this is simply:
                   9050: #    use File::Basename;
                   9051: #    ...
                   9052: #    $uri = shift;
                   9053: #    $filename = basename($uri);
                   9054: #    $path     = dirname($uri);
                   9055: #    return ($filename, $path);
                   9056: #
                   9057: #     The implementation below is probably faster however.
                   9058: #
1.710     albertel 9059: sub split_uri_for_cond {
                   9060:     my $uri=&deversion(&declutter(shift));
                   9061:     my @uriparts=split(/\//,$uri);
                   9062:     my $filename=pop(@uriparts);
                   9063:     my $pathname=join('/',@uriparts);
                   9064:     return ($pathname,$filename);
                   9065: }
1.232     www      9066: # --------------------------------------------------- Is a resource on the map?
                   9067: 
                   9068: sub is_on_map {
1.710     albertel 9069:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9070:     #Trying to find the conditional for the file
1.620     albertel 9071:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9072: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9073:     if ($match) {
1.289     bowersj2 9074: 	return (1,$1);
                   9075:     } else {
1.434     www      9076: 	return (0,0);
1.289     bowersj2 9077:     }
1.12      www      9078: }
                   9079: 
1.427     www      9080: # --------------------------------------------------------- Get symb from alias
                   9081: 
                   9082: sub get_symb_from_alias {
                   9083:     my $symb=shift;
                   9084:     my ($map,$resid,$url)=&decode_symb($symb);
                   9085: # Already is a symb
                   9086:     if ($url) { return $symb; }
                   9087: # Must be an alias
                   9088:     my $aliassymb='';
                   9089:     my %bighash;
1.620     albertel 9090:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9091:                             &GDBM_READER(),0640)) {
                   9092:         my $rid=$bighash{'mapalias_'.$symb};
                   9093: 	if ($rid) {
                   9094: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9095: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9096: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9097: 	}
                   9098:         untie %bighash;
                   9099:     }
                   9100:     return $aliassymb;
                   9101: }
                   9102: 
1.12      www      9103: # ----------------------------------------------------------------- Define Role
                   9104: 
                   9105: sub definerole {
                   9106:   if (allowed('mcr','/')) {
1.1326    raeburn  9107:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9108:     foreach my $role (split(':',$sysrole)) {
                   9109: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9110:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9111:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9112: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9113:                return "refused:s:$crole&$cqual"; 
                   9114:             }
                   9115:         }
1.191     harris41 9116:     }
1.800     albertel 9117:     foreach my $role (split(':',$domrole)) {
                   9118: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9119:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9120:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9121: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9122:                return "refused:d:$crole&$cqual"; 
                   9123:             }
                   9124:         }
1.191     harris41 9125:     }
1.800     albertel 9126:     foreach my $role (split(':',$courole)) {
                   9127: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9128:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9129:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9130: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9131:                return "refused:c:$crole&$cqual"; 
                   9132:             }
                   9133:         }
1.191     harris41 9134:     }
1.1326    raeburn  9135:     my $uhome;
                   9136:     if (($uname ne '') && ($udom ne '')) {
                   9137:         $uhome = &homeserver($uname,$udom);
                   9138:         return $uhome if ($uhome eq 'no_host');
                   9139:     } else {
                   9140:         $uname = $env{'user.name'};
                   9141:         $udom = $env{'user.domain'};
                   9142:         $uhome = $env{'user.home'};
                   9143:     }
1.620     albertel 9144:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9145:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9146:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9147:     return reply($command,$uhome);
1.12      www      9148:   } else {
                   9149:     return 'refused';
                   9150:   }
1.105     harris41 9151: }
                   9152: 
                   9153: # ---------------- Make a metadata query against the network of library servers
                   9154: 
                   9155: sub metadata_query {
1.1237    raeburn  9156:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9157:     my %rhash;
1.845     albertel 9158:     my %libserv = &all_library();
1.244     matthew  9159:     my @server_list = (defined($server_array) ? @$server_array
                   9160:                                               : keys(%libserv) );
                   9161:     for my $server (@server_list) {
1.1237    raeburn  9162:         my $domains = ''; 
                   9163:         if (ref($domains_hash) eq 'HASH') {
                   9164:             $domains = $domains_hash->{$server}; 
                   9165:         }
1.118     harris41 9166: 	unless ($custom or $customshow) {
1.1237    raeburn  9167: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9168: 	    $rhash{$server}=$reply;
                   9169: 	}
                   9170: 	else {
                   9171: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9172: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9173: 			     $server);
                   9174: 	    $rhash{$server}=$reply;
                   9175: 	}
1.112     harris41 9176:     }
1.118     harris41 9177:     return \%rhash;
1.240     www      9178: }
                   9179: 
                   9180: # ----------------------------------------- Send log queries and wait for reply
                   9181: 
                   9182: sub log_query {
                   9183:     my ($uname,$udom,$query,%filters)=@_;
                   9184:     my $uhome=&homeserver($uname,$udom);
                   9185:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9186:     my $uhost=&hostname($uhome);
1.800     albertel 9187:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9188:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9189:                        $uhome);
1.479     albertel 9190:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9191:     return get_query_reply($queryid);
                   9192: }
                   9193: 
1.818     raeburn  9194: # -------------------------- Update MySQL table for portfolio file
                   9195: 
                   9196: sub update_portfolio_table {
1.821     raeburn  9197:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9198:     if ($group ne '') {
                   9199:         $file_name =~s /^\Q$group\E//;
                   9200:     }
1.818     raeburn  9201:     my $homeserver = &homeserver($uname,$udom);
                   9202:     my $queryid=
1.821     raeburn  9203:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9204:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9205:     my $reply = &get_query_reply($queryid);
                   9206:     return $reply;
                   9207: }
                   9208: 
1.899     raeburn  9209: # -------------------------- Update MySQL allusers table
                   9210: 
                   9211: sub update_allusers_table {
                   9212:     my ($uname,$udom,$names) = @_;
                   9213:     my $homeserver = &homeserver($uname,$udom);
                   9214:     my $queryid=
                   9215:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9216:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9217:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9218:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9219:                'generation='.&escape($names->{'generation'}).'%%'.
                   9220:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9221:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9222:     return;
1.899     raeburn  9223: }
                   9224: 
1.508     raeburn  9225: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9226: 
                   9227: sub fetch_enrollment_query {
1.511     raeburn  9228:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9229:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9230:     my $maxtries = 1;
1.508     raeburn  9231:     if ($context eq 'automated') {
                   9232:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9233:         $sleep = 2;
                   9234:         $loopmax = 100;
1.547     raeburn  9235:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9236:     } else {
                   9237:         $homeserver = &homeserver($cnum,$dom);
                   9238:     }
1.838     albertel 9239:     my $host=&hostname($homeserver);
1.506     raeburn  9240:     my $cmd = '';
1.1000    raeburn  9241:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9242:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9243:     }
                   9244:     $cmd =~ s/%%$//;
                   9245:     $cmd = &escape($cmd);
                   9246:     my $query = 'fetchenrollment';
1.620     albertel 9247:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9248:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9249:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9250:         return 'error: '.$queryid;
                   9251:     }
1.1317    raeburn  9252:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9253:     my $tries = 1;
                   9254:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9255:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9256:         $tries ++;
                   9257:     }
1.526     raeburn  9258:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9259:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9260:     } else {
1.901     albertel 9261:         my @responses = split(/:/,$reply);
1.1322    raeburn  9262:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9263:             foreach my $line (@responses) {
                   9264:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9265:                 $$replyref{$key} = $value;
                   9266:             }
                   9267:         } else {
1.1117    foxr     9268:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9269:             foreach my $line (@responses) {
                   9270:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9271:                 $$replyref{$key} = $value;
                   9272:                 if ($value > 0) {
1.800     albertel 9273:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9274:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9275:                         my $destname = $pathname.'/'.$filename;
                   9276:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9277:                         if ($xml_classlist =~ /^error/) {
                   9278:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9279:                         } else {
1.1359    raeburn  9280:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9281:                                 print FILE &unescape($xml_classlist);
                   9282:                                 close(FILE);
1.526     raeburn  9283:                             } else {
                   9284:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9285:                             }
                   9286:                         }
                   9287:                     }
                   9288:                 }
                   9289:             }
                   9290:         }
                   9291:         return 'ok';
                   9292:     }
                   9293:     return 'error';
                   9294: }
                   9295: 
1.242     www      9296: sub get_query_reply {
1.1317    raeburn  9297:     my ($queryid,$sleep,$loopmax) = @_;;
                   9298:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9299:         $sleep = 0.2;
                   9300:     }
                   9301:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9302:         $loopmax = 100;
                   9303:     }
1.1117    foxr     9304:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9305:     my $reply='';
1.1317    raeburn  9306:     for (1..$loopmax) {
                   9307: 	sleep($sleep);
1.240     www      9308:         if (-e $replyfile.'.end') {
1.1359    raeburn  9309: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9310: 		$reply = join('',<$fh>);
                   9311: 		close($fh);
1.240     www      9312: 	   } else { return 'error: reply_file_error'; }
1.242     www      9313:            return &unescape($reply);
                   9314: 	}
1.240     www      9315:     }
1.242     www      9316:     return 'timeout:'.$queryid;
1.240     www      9317: }
                   9318: 
                   9319: sub courselog_query {
1.241     www      9320: #
                   9321: # possible filters:
                   9322: # url: url or symb
                   9323: # username
                   9324: # domain
                   9325: # action: view, submit, grade
                   9326: # start: timestamp
                   9327: # end: timestamp
                   9328: #
1.240     www      9329:     my (%filters)=@_;
1.620     albertel 9330:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9331:     if ($filters{'url'}) {
                   9332: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9333:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9334:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9335:     }
1.620     albertel 9336:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9337:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9338:     return &log_query($cname,$cdom,'courselog',%filters);
                   9339: }
                   9340: 
                   9341: sub userlog_query {
1.858     raeburn  9342: #
                   9343: # possible filters:
                   9344: # action: log check role
                   9345: # start: timestamp
                   9346: # end: timestamp
                   9347: #
1.240     www      9348:     my ($uname,$udom,%filters)=@_;
                   9349:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9350: }
                   9351: 
1.506     raeburn  9352: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9353: 
                   9354: sub auto_run {
1.508     raeburn  9355:     my ($cnum,$cdom) = @_;
1.876     raeburn  9356:     my $response = 0;
                   9357:     my $settings;
                   9358:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9359:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9360:         $settings = $domconfig{'autoenroll'};
                   9361:         if ($settings->{'run'} eq '1') {
                   9362:             $response = 1;
                   9363:         }
                   9364:     } else {
1.934     raeburn  9365:         my $homeserver;
                   9366:         if (&is_course($cdom,$cnum)) {
                   9367:             $homeserver = &homeserver($cnum,$cdom);
                   9368:         } else {
                   9369:             $homeserver = &domain($cdom,'primary');
                   9370:         }
                   9371:         if ($homeserver ne 'no_host') {
                   9372:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9373:         }
1.876     raeburn  9374:     }
1.506     raeburn  9375:     return $response;
                   9376: }
1.776     albertel 9377: 
1.506     raeburn  9378: sub auto_get_sections {
1.508     raeburn  9379:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9380:     my $homeserver;
                   9381:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9382:         $homeserver = &homeserver($cnum,$cdom);
                   9383:     }
                   9384:     if (!defined($homeserver)) { 
                   9385:         if ($cdom =~ /^$match_domain$/) {
                   9386:             $homeserver = &domain($cdom,'primary');
                   9387:         }
                   9388:     }
                   9389:     my @secs;
                   9390:     if (defined($homeserver)) {
                   9391:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9392:         unless ($response eq 'refused') {
                   9393:             @secs = split(/:/,$response);
                   9394:         }
1.506     raeburn  9395:     }
                   9396:     return @secs;
                   9397: }
1.776     albertel 9398: 
1.506     raeburn  9399: sub auto_new_course {
1.1099    raeburn  9400:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9401:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9402:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9403:     return $response;
                   9404: }
1.776     albertel 9405: 
1.506     raeburn  9406: sub auto_validate_courseID {
1.508     raeburn  9407:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9408:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9409:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9410:     return $response;
                   9411: }
1.776     albertel 9412: 
1.1007    raeburn  9413: sub auto_validate_instcode {
1.1020    raeburn  9414:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9415:     my ($homeserver,$response);
                   9416:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9417:         $homeserver = &homeserver($cnum,$cdom);
                   9418:     }
                   9419:     if (!defined($homeserver)) {
                   9420:         if ($cdom =~ /^$match_domain$/) {
                   9421:             $homeserver = &domain($cdom,'primary');
                   9422:         }
                   9423:     }
1.1065    raeburn  9424:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9425:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9426:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9427:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9428: }
                   9429: 
1.506     raeburn  9430: sub auto_create_password {
1.873     raeburn  9431:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9432:     my ($homeserver,$response);
1.506     raeburn  9433:     my $create_passwd = 0;
                   9434:     my $authchk = '';
1.873     raeburn  9435:     if ($udom =~ /^$match_domain$/) {
                   9436:         $homeserver = &domain($udom,'primary');
                   9437:     }
                   9438:     if ($homeserver eq '') {
                   9439:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9440:             $homeserver = &homeserver($cnum,$cdom);
                   9441:         }
                   9442:     }
                   9443:     if ($homeserver eq '') {
                   9444:         $authchk = 'nodomain';
1.506     raeburn  9445:     } else {
1.873     raeburn  9446:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9447:         if ($response eq 'refused') {
                   9448:             $authchk = 'refused';
                   9449:         } else {
1.901     albertel 9450:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9451:         }
1.506     raeburn  9452:     }
                   9453:     return ($authparam,$create_passwd,$authchk);
                   9454: }
                   9455: 
1.706     raeburn  9456: sub auto_photo_permission {
                   9457:     my ($cnum,$cdom,$students) = @_;
                   9458:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9459:     my ($outcome,$perm_reqd,$conditions) = 
                   9460: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9461:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9462: 	return (undef,undef);
                   9463:     }
1.706     raeburn  9464:     return ($outcome,$perm_reqd,$conditions);
                   9465: }
                   9466: 
                   9467: sub auto_checkphotos {
                   9468:     my ($uname,$udom,$pid) = @_;
                   9469:     my $homeserver = &homeserver($uname,$udom);
                   9470:     my ($result,$resulttype);
                   9471:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9472: 				   &escape($uname).':'.&escape($pid),
                   9473: 				   $homeserver));
1.709     albertel 9474:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9475: 	return (undef,undef);
                   9476:     }
1.706     raeburn  9477:     if ($outcome) {
                   9478:         ($result,$resulttype) = split(/:/,$outcome);
                   9479:     } 
                   9480:     return ($result,$resulttype);
                   9481: }
                   9482: 
                   9483: sub auto_photochoice {
                   9484:     my ($cnum,$cdom) = @_;
                   9485:     my $homeserver = &homeserver($cnum,$cdom);
                   9486:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9487: 						       &escape($cdom),
                   9488: 						       $homeserver)));
1.709     albertel 9489:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9490: 	return (undef,undef);
                   9491:     }
1.706     raeburn  9492:     return ($update,$comment);
                   9493: }
                   9494: 
                   9495: sub auto_photoupdate {
                   9496:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9497:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9498:     my $host=&hostname($homeserver);
1.706     raeburn  9499:     my $cmd = '';
                   9500:     my $maxtries = 1;
1.800     albertel 9501:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9502:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9503:     }
                   9504:     $cmd =~ s/%%$//;
                   9505:     $cmd = &escape($cmd);
                   9506:     my $query = 'institutionalphotos';
                   9507:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9508:     unless ($queryid=~/^\Q$host\E\_/) {
                   9509:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9510:         return 'error: '.$queryid;
                   9511:     }
                   9512:     my $reply = &get_query_reply($queryid);
                   9513:     my $tries = 1;
                   9514:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9515:         $reply = &get_query_reply($queryid);
                   9516:         $tries ++;
                   9517:     }
                   9518:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9519:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9520:     } else {
                   9521:         my @responses = split(/:/,$reply);
                   9522:         my $outcome = shift(@responses); 
                   9523:         foreach my $item (@responses) {
                   9524:             my ($key,$value) = split(/=/,$item);
                   9525:             $$photo{$key} = $value;
                   9526:         }
                   9527:         return $outcome;
                   9528:     }
                   9529:     return 'error';
                   9530: }
                   9531: 
1.521     raeburn  9532: sub auto_instcode_format {
1.793     albertel 9533:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9534: 	$cat_order) = @_;
1.521     raeburn  9535:     my $courses = '';
1.772     raeburn  9536:     my @homeservers;
1.521     raeburn  9537:     if ($caller eq 'global') {
1.841     albertel 9538: 	my %servers = &get_servers($codedom,'library');
                   9539: 	foreach my $tryserver (keys(%servers)) {
                   9540: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9541: 		push(@homeservers,$tryserver);
                   9542: 	    }
1.584     raeburn  9543:         }
1.1022    raeburn  9544:     } elsif ($caller eq 'requests') {
                   9545:         if ($codedom =~ /^$match_domain$/) {
                   9546:             my $chome = &domain($codedom,'primary');
                   9547:             unless ($chome eq 'no_host') {
                   9548:                 push(@homeservers,$chome);
                   9549:             }
                   9550:         }
1.521     raeburn  9551:     } else {
1.772     raeburn  9552:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9553:     }
1.793     albertel 9554:     foreach my $code (keys(%{$instcodes})) {
                   9555:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9556:     }
                   9557:     chop($courses);
1.772     raeburn  9558:     my $ok_response = 0;
                   9559:     my $response;
                   9560:     while (@homeservers > 0 && $ok_response == 0) {
                   9561:         my $server = shift(@homeservers); 
                   9562:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9563:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9564:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9565: 		split(/:/,$response);
1.772     raeburn  9566:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9567:             push(@{$codetitles},&str2array($codetitles_str));
                   9568:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9569:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9570:             $ok_response = 1;
                   9571:         }
                   9572:     }
                   9573:     if ($ok_response) {
1.521     raeburn  9574:         return 'ok';
1.772     raeburn  9575:     } else {
                   9576:         return $response;
1.521     raeburn  9577:     }
                   9578: }
                   9579: 
1.792     raeburn  9580: sub auto_instcode_defaults {
                   9581:     my ($domain,$returnhash,$code_order) = @_;
                   9582:     my @homeservers;
1.841     albertel 9583: 
                   9584:     my %servers = &get_servers($domain,'library');
                   9585:     foreach my $tryserver (keys(%servers)) {
                   9586: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9587: 	    push(@homeservers,$tryserver);
                   9588: 	}
1.792     raeburn  9589:     }
1.841     albertel 9590: 
1.792     raeburn  9591:     my $response;
1.841     albertel 9592:     foreach my $server (@homeservers) {
1.792     raeburn  9593:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9594:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9595: 	
                   9596: 	foreach my $pair (split(/\&/,$response)) {
                   9597: 	    my ($name,$value)=split(/\=/,$pair);
                   9598: 	    if ($name eq 'code_order') {
                   9599: 		@{$code_order} = split(/\&/,&unescape($value));
                   9600: 	    } else {
                   9601: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9602: 	    }
                   9603: 	}
                   9604: 	return 'ok';
1.792     raeburn  9605:     }
1.841     albertel 9606: 
                   9607:     return $response;
1.1003    raeburn  9608: }
                   9609: 
                   9610: sub auto_possible_instcodes {
1.1007    raeburn  9611:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9612:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9613:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9614:         return;
                   9615:     }
1.1003    raeburn  9616:     my (@homeservers,$uhome);
                   9617:     if (defined(&domain($domain,'primary'))) {
                   9618:         $uhome=&domain($domain,'primary');
                   9619:         push(@homeservers,&domain($domain,'primary'));
                   9620:     } else {
                   9621:         my %servers = &get_servers($domain,'library');
                   9622:         foreach my $tryserver (keys(%servers)) {
                   9623:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9624:                 push(@homeservers,$tryserver);
                   9625:             }
                   9626:         }
                   9627:     }
                   9628:     my $response;
                   9629:     foreach my $server (@homeservers) {
                   9630:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9631:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9632:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9633:             split(':',$response);
                   9634:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9635:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9636:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9637:             my ($name,$value)=split('=',$item);
                   9638:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9639:         }
                   9640:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9641:             my ($name,$value)=split('=',$item);
                   9642:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9643:         }
                   9644:         return 'ok';
                   9645:     }
                   9646:     return $response;
                   9647: }
1.792     raeburn  9648: 
1.1010    raeburn  9649: sub auto_courserequest_checks {
                   9650:     my ($dom) = @_;
1.1020    raeburn  9651:     my ($homeserver,%validations);
                   9652:     if ($dom =~ /^$match_domain$/) {
                   9653:         $homeserver = &domain($dom,'primary');
                   9654:     }
                   9655:     unless ($homeserver eq 'no_host') {
                   9656:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9657:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9658:             my @items = split(/&/,$response);
                   9659:             foreach my $item (@items) {
                   9660:                 my ($key,$value) = split('=',$item);
                   9661:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9662:             }
                   9663:         }
                   9664:     }
1.1010    raeburn  9665:     return %validations; 
                   9666: }
                   9667: 
1.1020    raeburn  9668: sub auto_courserequest_validation {
1.1255    raeburn  9669:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9670:     my ($homeserver,$response);
                   9671:     if ($dom =~ /^$match_domain$/) {
                   9672:         $homeserver = &domain($dom,'primary');
                   9673:     }
1.1255    raeburn  9674:     unless ($homeserver eq 'no_host') {
                   9675:         my $customdata;
                   9676:         if (ref($custominfo) eq 'HASH') {
                   9677:             $customdata = &freeze_escape($custominfo);
                   9678:         }
1.1020    raeburn  9679:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9680:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9681:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9682:                                     $customdata,$homeserver));
1.1020    raeburn  9683:     }
                   9684:     return $response;
                   9685: }
                   9686: 
1.777     albertel 9687: sub auto_validate_class_sec {
1.918     raeburn  9688:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9689:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9690:     my $ownerlist;
                   9691:     if (ref($owners) eq 'ARRAY') {
                   9692:         $ownerlist = join(',',@{$owners});
                   9693:     } else {
                   9694:         $ownerlist = $owners;
                   9695:     }
1.773     raeburn  9696:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9697:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9698:     return $response;
                   9699: }
                   9700: 
1.1367    raeburn  9701: sub auto_validate_instclasses {
                   9702:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9703:     my ($homeserver,%validations);
                   9704:     $homeserver = &homeserver($cnum,$cdom);
                   9705:     unless ($homeserver eq 'no_host') {
                   9706:         my $ownerlist;
                   9707:         if (ref($owners) eq 'ARRAY') {
                   9708:             $ownerlist = join(',',@{$owners});
                   9709:         } else {
                   9710:             $ownerlist = $owners;
                   9711:         }
                   9712:         if (ref($classesref) eq 'HASH') {
                   9713:             my $classes = &freeze_escape($classesref);
                   9714:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9715:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9716:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9717:                 my @items = split(/&/,$response);
                   9718:                 foreach my $item (@items) {
                   9719:                     my ($key,$value) = split('=',$item);
                   9720:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9721:                 }
                   9722:             }
                   9723:         }
                   9724:     }
                   9725:     return %validations;
                   9726: }
                   9727: 
1.1248    raeburn  9728: sub auto_crsreq_update {
                   9729:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9730:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9731:     my ($homeserver,%crsreqresponse);
                   9732:     if ($cdom =~ /^$match_domain$/) {
                   9733:         $homeserver = &domain($cdom,'primary');
                   9734:     }
                   9735:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9736:         my $info;
                   9737:         if (ref($inbound) eq 'HASH') {
                   9738:             $info = &freeze_escape($inbound);
                   9739:         }
                   9740:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9741:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9742:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9743:                             &escape($title).':'.&escape($code).':'.
                   9744:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9745:                             $homeserver);
1.1248    raeburn  9746:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9747:             my @items = split(/&/,$response);
                   9748:             foreach my $item (@items) {
                   9749:                 my ($key,$value) = split('=',$item);
                   9750:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9751:             }
                   9752:         }
                   9753:     }
                   9754:     return \%crsreqresponse;
                   9755: }
                   9756: 
1.1305    raeburn  9757: sub auto_export_grades {
1.1309    raeburn  9758:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9759:     my ($homeserver,%exportresponse);
                   9760:     if ($cdom =~ /^$match_domain$/) {
                   9761:         $homeserver = &domain($cdom,'primary');
                   9762:     }
                   9763:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9764:         my $info;
                   9765:         if (ref($inforef) eq 'HASH') {
                   9766:             $info = &freeze_escape($inforef);
                   9767:         }
                   9768:         if (ref($gradesref) eq 'HASH') {
                   9769:             my $grades = &freeze_escape($gradesref);
                   9770:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9771:                                 $info.':'.$grades,$homeserver);
                   9772:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9773:                 my @items = split(/&/,$response);
                   9774:                 foreach my $item (@items) {
                   9775:                     my ($key,$value) = split('=',$item);
                   9776:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9777:                 }
                   9778:             }
                   9779:         }
                   9780:     }
                   9781:     return \%exportresponse;
1.1305    raeburn  9782: }
                   9783: 
1.1287    raeburn  9784: sub check_instcode_cloning {
                   9785:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9786:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9787:         return;
                   9788:     }
                   9789:     my $canclone;
                   9790:     if (@{$code_order} > 0) {
                   9791:         my $instcoderegexp ='^';
                   9792:         my @clonecodes = split(/\&/,$cloner);
                   9793:         foreach my $item (@{$code_order}) {
                   9794:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9795:                 foreach my $pair (@clonecodes) {
                   9796:                     my ($key,$val) = split(/\=/,$pair,2);
                   9797:                     $val = &unescape($val);
                   9798:                     if ($key eq $item) {
                   9799:                         $instcoderegexp .= '('.$val.')';
                   9800:                         last;
                   9801:                     }
                   9802:                 }
                   9803:             } else {
                   9804:                 $instcoderegexp .= $codedefaults->{$item};
                   9805:             }
                   9806:         }
                   9807:         $instcoderegexp .= '$';
                   9808:         my (@from,@to);
                   9809:         eval {
                   9810:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9811:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9812:         };
                   9813:         if ((@from > 0) && (@to > 0)) {
                   9814:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9815:             if (!@diffs) {
                   9816:                 $canclone = 1;
                   9817:             }
                   9818:         }
                   9819:     }
                   9820:     return $canclone;
                   9821: }
                   9822: 
                   9823: sub default_instcode_cloning {
                   9824:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9825:     my (%codedefaults,@code_order,$canclone);
                   9826:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9827:         %codedefaults = %{$codedefaultsref};
                   9828:         @code_order = @{$codeorderref};
                   9829:     } elsif ($clonedom) {
                   9830:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9831:     }
                   9832:     if (($domdefclone) && (@code_order)) {
                   9833:         my @clonecodes = split(/\+/,$domdefclone);
                   9834:         my $instcoderegexp ='^';
                   9835:         foreach my $item (@code_order) {
                   9836:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9837:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9838:             } else {
                   9839:                 $instcoderegexp .= $codedefaults{$item};
                   9840:             }
                   9841:         }
                   9842:         $instcoderegexp .= '$';
                   9843:         my (@from,@to);
                   9844:         eval {
                   9845:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9846:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9847:         };
                   9848:         if ((@from > 0) && (@to > 0)) {
                   9849:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9850:             if (!@diffs) {
                   9851:                 $canclone = 1;
                   9852:             }
                   9853:         }
                   9854:     }
                   9855:     return $canclone;
                   9856: }
                   9857: 
1.679     raeburn  9858: # ------------------------------------------------------- Course Group routines
                   9859: 
                   9860: sub get_coursegroups {
1.809     raeburn  9861:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9862:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9863: }
                   9864: 
1.679     raeburn  9865: sub modify_coursegroup {
                   9866:     my ($cdom,$cnum,$groupsettings) = @_;
                   9867:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9868: }
                   9869: 
1.809     raeburn  9870: sub toggle_coursegroup_status {
                   9871:     my ($cdom,$cnum,$group,$action) = @_;
                   9872:     my ($from_namespace,$to_namespace);
                   9873:     if ($action eq 'delete') {
                   9874:         $from_namespace = 'coursegroups';
                   9875:         $to_namespace = 'deleted_groups';
                   9876:     } else {
                   9877:         $from_namespace = 'deleted_groups';
                   9878:         $to_namespace = 'coursegroups';
                   9879:     }
                   9880:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9881:     if (my $tmp = &error(%curr_group)) {
                   9882:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9883:         return ('read error',$tmp);
                   9884:     } else {
                   9885:         my %savedsettings = %curr_group; 
1.809     raeburn  9886:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9887:         my $deloutcome;
                   9888:         if ($result eq 'ok') {
1.809     raeburn  9889:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9890:         } else {
                   9891:             return ('write error',$result);
                   9892:         }
                   9893:         if ($deloutcome eq 'ok') {
                   9894:             return 'ok';
                   9895:         } else {
                   9896:             return ('delete error',$deloutcome);
                   9897:         }
                   9898:     }
                   9899: }
                   9900: 
1.679     raeburn  9901: sub modify_group_roles {
1.957     raeburn  9902:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9903:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9904:     my $role = 'gr/'.&escape($userprivs);
                   9905:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9906:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9907:     if ($result eq 'ok') {
                   9908:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9909:     }
1.679     raeburn  9910:     return $result;
                   9911: }
                   9912: 
                   9913: sub modify_coursegroup_membership {
                   9914:     my ($cdom,$cnum,$membership) = @_;
                   9915:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9916:     return $result;
                   9917: }
                   9918: 
1.682     raeburn  9919: sub get_active_groups {
                   9920:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9921:     my $now = time;
                   9922:     my %groups = ();
                   9923:     foreach my $key (keys(%env)) {
1.811     albertel 9924:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9925:             my ($start,$end) = split(/\./,$env{$key});
                   9926:             if (($end!=0) && ($end<$now)) { next; }
                   9927:             if (($start!=0) && ($start>$now)) { next; }
                   9928:             if ($1 eq $cdom && $2 eq $cnum) {
                   9929:                 $groups{$3} = $env{$key} ;
                   9930:             }
                   9931:         }
                   9932:     }
                   9933:     return %groups;
                   9934: }
                   9935: 
1.683     raeburn  9936: sub get_group_membership {
                   9937:     my ($cdom,$cnum,$group) = @_;
                   9938:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9939: }
                   9940: 
                   9941: sub get_users_groups {
                   9942:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9943:     my @usersgroups;
1.683     raeburn  9944:     my $cachetime=1800;
                   9945: 
                   9946:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9947:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9948:     if (defined($cached)) {
1.734     albertel 9949:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9950:     } else {  
                   9951:         $grouplist = '';
1.816     raeburn  9952:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9953:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9954:         my $access_end = $env{'course.'.$courseid.
                   9955:                               '.default_enrollment_end_date'};
                   9956:         my $now = time;
                   9957:         foreach my $key (keys(%roleshash)) {
                   9958:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9959:                 my $group = $1;
                   9960:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9961:                     my $start = $2;
                   9962:                     my $end = $1;
                   9963:                     if ($start == -1) { next; } # deleted from group
                   9964:                     if (($start!=0) && ($start>$now)) { next; }
                   9965:                     if (($end!=0) && ($end<$now)) {
                   9966:                         if ($access_end && $access_end < $now) {
                   9967:                             if ($access_end - $end < 86400) {
                   9968:                                 push(@usersgroups,$group);
1.733     raeburn  9969:                             }
                   9970:                         }
1.817     raeburn  9971:                         next;
1.733     raeburn  9972:                     }
1.817     raeburn  9973:                     push(@usersgroups,$group);
1.683     raeburn  9974:                 }
                   9975:             }
                   9976:         }
1.817     raeburn  9977:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9978:         $grouplist = join(':',@usersgroups);
                   9979:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9980:     }
1.733     raeburn  9981:     return @usersgroups;
1.683     raeburn  9982: }
                   9983: 
                   9984: sub devalidate_getgroups_cache {
                   9985:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9986:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9987: 
1.683     raeburn  9988:     my $hashid="$udom:$uname:$courseid";
                   9989:     &devalidate_cache_new('getgroups',$hashid);
                   9990: }
                   9991: 
1.12      www      9992: # ------------------------------------------------------------------ Plain Text
                   9993: 
                   9994: sub plaintext {
1.988     raeburn  9995:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9996:     if ($short =~ m{^cr/}) {
1.758     albertel 9997: 	return (split('/',$short))[-1];
                   9998:     }
1.742     raeburn  9999:     if (!defined($cid)) {
                   10000:         $cid = $env{'request.course.id'};
                   10001:     }
                   10002:     my %rolenames = (
1.1008    raeburn  10003:                       Course    => 'std',
                   10004:                       Community => 'alt1',
1.1305    raeburn  10005:                       Placement => 'std',
1.742     raeburn  10006:                     );
1.1037    raeburn  10007:     if ($cid ne '') {
                   10008:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10009:             unless ($forcedefault) {
                   10010:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10011:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10012:                 return &Apache::lonlocal::mt($roletext);
                   10013:             }
                   10014:         }
                   10015:     }
                   10016:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10017:         (defined($rolenames{$type})) && 
                   10018:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10019:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10020:     } elsif ($cid ne '') {
                   10021:         my $crstype = $env{'course.'.$cid.'.type'};
                   10022:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10023:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10024:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10025:         }
1.742     raeburn  10026:     }
1.1037    raeburn  10027:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10028: }
                   10029: 
                   10030: # ----------------------------------------------------------------- Assign Role
                   10031: 
                   10032: sub assignrole {
1.957     raeburn  10033:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10034:         $context)=@_;
1.21      www      10035:     my $mrole;
                   10036:     if ($role =~ /^cr\//) {
1.393     www      10037:         my $cwosec=$url;
1.811     albertel 10038:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10039: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10040:            my $refused = 1;
                   10041:            if ($context eq 'requestcourses') {
                   10042:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10043:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10044:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10045:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10046:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10047:                            if ($crsenv{'internal.courseowner'} eq
                   10048:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10049:                                $refused = '';
                   10050:                            }
                   10051:                        }
                   10052:                    }
                   10053:                }
                   10054:            }
                   10055:            if ($refused) {
                   10056:                &logthis('Refused custom assignrole: '.
                   10057:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10058:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10059:                return 'refused';
                   10060:            }
1.104     www      10061:         }
1.21      www      10062:         $mrole='cr';
1.678     raeburn  10063:     } elsif ($role =~ /^gr\//) {
                   10064:         my $cwogrp=$url;
1.811     albertel 10065:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10066:         unless (&allowed('mdg',$cwogrp)) {
                   10067:             &logthis('Refused group assignrole: '.
                   10068:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10069:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10070:             return 'refused';
                   10071:         }
                   10072:         $mrole='gr';
1.21      www      10073:     } else {
1.82      www      10074:         my $cwosec=$url;
1.811     albertel 10075:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10076:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10077:             my $refused;
                   10078:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10079:                 if (!(&allowed('c'.$role,$url))) {
                   10080:                     $refused = 1;
                   10081:                 }
                   10082:             } else {
                   10083:                 $refused = 1;
                   10084:             }
1.947     raeburn  10085:             if ($refused) {
1.1045    raeburn  10086:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  10087:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10088:                     my %crsenv;
                   10089:                     if ($role eq 'cc' || $role eq 'co') {
                   10090:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10091:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10092:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10093:                                 if ($crsenv{'internal.courseowner'} eq 
                   10094:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10095:                                     $refused = '';
                   10096:                                 }
                   10097:                             }
                   10098:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10099:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10100:                                 if ($crsenv{'internal.courseowner'} eq 
                   10101:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10102:                                     $refused = '';
                   10103:                                 }
                   10104:                             }
                   10105:                         }
                   10106:                     }
1.1368    raeburn  10107:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10108:                     if ($role eq 'st') {
                   10109:                         $refused = '';
1.1377    raeburn  10110:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10111:                         $refused = '';
                   10112:                     }
1.1017    raeburn  10113:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10114:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10115:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10116:                         my $wrongcc;
                   10117:                         if ($cnum =~ /^$match_community$/) {
                   10118:                             $wrongcc = 1 if ($role eq 'cc');
                   10119:                         } else {
                   10120:                             $wrongcc = 1 if ($role eq 'co');
                   10121:                         }
                   10122:                         unless ($wrongcc) {
                   10123:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10124:                             if ($crsenv{'internal.courseowner'} eq 
                   10125:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10126:                                 $refused = '';
                   10127:                             }
1.1017    raeburn  10128:                         }
                   10129:                     }
1.1183    raeburn  10130:                 } elsif ($context eq 'requestauthor') {
                   10131:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10132:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10133:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10134:                             $refused = '';
                   10135:                         } else {
                   10136:                             my %domdefaults = &get_domain_defaults($udom);
                   10137:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10138:                                 my $checkbystatus;
                   10139:                                 if ($env{'user.adv'}) { 
                   10140:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10141:                                     if ($disposition eq 'automatic') {
                   10142:                                         $refused = '';
                   10143:                                     } elsif ($disposition eq '') {
                   10144:                                         $checkbystatus = 1;
                   10145:                                     } 
                   10146:                                 } else {
                   10147:                                     $checkbystatus = 1;
                   10148:                                 }
                   10149:                                 if ($checkbystatus) {
                   10150:                                     if ($env{'environment.inststatus'}) {
                   10151:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10152:                                         foreach my $type (@inststatuses) {
                   10153:                                             if (($type ne '') &&
                   10154:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10155:                                                 $refused = '';
                   10156:                                             }
                   10157:                                         }
                   10158:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10159:                                         $refused = '';
                   10160:                                     }
                   10161:                                 }
                   10162:                             }
                   10163:                         }
                   10164:                     }
1.1017    raeburn  10165:                 }
                   10166:                 if ($refused) {
1.947     raeburn  10167:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10168:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10169: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10170:                     return 'refused';
                   10171:                 }
1.932     raeburn  10172:             }
1.1131    raeburn  10173:         } elsif ($role eq 'au') {
                   10174:             if ($url ne '/'.$udom.'/') {
                   10175:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10176:                          ' to assign author role for '.$uname.':'.$udom.
                   10177:                          ' in domain: '.$url.' refused (wrong domain).');
                   10178:                 return 'refused';
                   10179:             }
1.104     www      10180:         }
1.21      www      10181:         $mrole=$role;
                   10182:     }
1.620     albertel 10183:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10184:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10185:     if ($end) { $command.='_'.$end; }
1.21      www      10186:     if ($start) {
                   10187: 	if ($end) { 
1.81      www      10188:            $command.='_'.$start; 
1.21      www      10189:         } else {
1.81      www      10190:            $command.='_0_'.$start;
1.21      www      10191:         }
                   10192:     }
1.739     raeburn  10193:     my $origstart = $start;
                   10194:     my $origend = $end;
1.957     raeburn  10195:     my $delflag;
1.357     www      10196: # actually delete
                   10197:     if ($deleteflag) {
1.373     www      10198: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10199: # modify command to delete the role
1.620     albertel 10200:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10201:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10202: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10203: # set start and finish to negative values for userrolelog
                   10204:            $start=-1;
                   10205:            $end=-1;
1.957     raeburn  10206:            $delflag = 1;
1.357     www      10207:         }
                   10208:     }
                   10209: # send command
1.349     www      10210:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10211: # log new user role if status is ok
1.349     www      10212:     if ($answer eq 'ok') {
1.663     raeburn  10213: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10214:         if (($role eq 'cc') || ($role eq 'in') ||
                   10215:             ($role eq 'ep') || ($role eq 'ad') ||
                   10216:             ($role eq 'ta') || ($role eq 'st') ||
                   10217:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10218:             ($role eq 'co')) {
1.1200    raeburn  10219: # for course roles, perform group memberships changes triggered by role change.
                   10220:             unless ($role =~ /^gr/) {
                   10221:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10222:                                                  $origstart,$selfenroll,$context);
                   10223:             }
1.1184    raeburn  10224:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10225:                            $selfenroll,$context);
                   10226:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10227:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10228:                  ($role eq 'da')) {
1.1184    raeburn  10229:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10230:                            $context);
                   10231:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10232:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10233:                              $context); 
                   10234:         }
1.1053    raeburn  10235:         if ($role eq 'cc') {
                   10236:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10237:         }
1.349     www      10238:     }
                   10239:     return $answer;
1.169     harris41 10240: }
                   10241: 
1.1053    raeburn  10242: sub autoupdate_coowners {
                   10243:     my ($url,$end,$start,$uname,$udom) = @_;
                   10244:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10245:     if (($cdom ne '') && ($cnum ne '')) {
                   10246:         my $now = time;
                   10247:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10248:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10249:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10250:             my $instcode = $coursehash{'internal.coursecode'};
                   10251:             if ($instcode ne '') {
1.1056    raeburn  10252:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10253:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10254:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10255:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   10256:                         if ($result eq 'valid') {
                   10257:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10258:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10259:                                     push(@newcoowners,$coowner);
                   10260:                                 }
                   10261:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10262:                                     push(@newcoowners,$uname.':'.$udom);
                   10263:                                 }
                   10264:                                 @newcoowners = sort(@newcoowners);
                   10265:                             } else {
                   10266:                                 push(@newcoowners,$uname.':'.$udom);
                   10267:                             }
                   10268:                         } else {
                   10269:                             if ($coursehash{'internal.co-owners'}) {
                   10270:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10271:                                     unless ($coowner eq $uname.':'.$udom) {
                   10272:                                         push(@newcoowners,$coowner);
                   10273:                                     }
                   10274:                                 }
                   10275:                                 unless (@newcoowners > 0) {
                   10276:                                     $delcoowners = 1;
                   10277:                                     $coowners = '';
                   10278:                                 }
                   10279:                             }
                   10280:                         }
                   10281:                         if (@newcoowners || $delcoowners) {
                   10282:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10283:                                             $delcoowners,@newcoowners);
                   10284:                         }
                   10285:                     }
                   10286:                 }
                   10287:             }
                   10288:         }
                   10289:     }
                   10290: }
                   10291: 
                   10292: sub store_coowners {
                   10293:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10294:     my $cid = $cdom.'_'.$cnum;
                   10295:     my ($coowners,$delresult,$putresult);
                   10296:     if (@newcoowners) {
                   10297:         $coowners = join(',',@newcoowners);
                   10298:         my %coownershash = (
                   10299:                             'internal.co-owners' => $coowners,
                   10300:                            );
                   10301:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10302:         if ($putresult eq 'ok') {
                   10303:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10304:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10305:             }
                   10306:         }
                   10307:     }
                   10308:     if ($delcoowners) {
                   10309:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10310:         if ($delresult eq 'ok') {
                   10311:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10312:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10313:             }
                   10314:         }
                   10315:     }
                   10316:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10317:         my %crsinfo =
                   10318:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10319:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10320:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10321:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10322:         }
                   10323:     }
                   10324: }
                   10325: 
1.169     harris41 10326: # -------------------------------------------------- Modify user authentication
1.197     www      10327: # Overrides without validation
                   10328: 
1.169     harris41 10329: sub modifyuserauth {
                   10330:     my ($udom,$uname,$umode,$upass)=@_;
                   10331:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10332:     my $allowed;
                   10333:     if (&allowed('mau',$udom)) {
                   10334:         $allowed = 1;
                   10335:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10336:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10337:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10338:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10339:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10340:         if (($cdom ne '') && ($cnum ne '')) {
                   10341:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10342:             if ($is_owner) {
                   10343:                 $allowed = 1;
                   10344:             }
                   10345:         }
                   10346:     }
                   10347:     unless ($allowed) { return 'refused'; }
1.197     www      10348:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10349:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10350:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10351:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10352: 		     &escape($upass),$uhome);
1.1434    raeburn  10353:     my $ip = &get_requestor_ip();
1.620     albertel 10354:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10355:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  10356:          '(Remote '.$ip.'): '.$reply);
1.197     www      10357:     &log($udom,,$uname,$uhome,
1.620     albertel 10358:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10359:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  10360:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10361:     unless ($reply eq 'ok') {
1.197     www      10362:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10363: 	return 'error: '.$reply;
                   10364:     }   
1.170     harris41 10365:     return 'ok';
1.80      www      10366: }
                   10367: 
1.81      www      10368: # --------------------------------------------------------------- Modify a user
1.80      www      10369: 
1.81      www      10370: sub modifyuser {
1.206     matthew  10371:     my ($udom,    $uname, $uid,
                   10372:         $umode,   $upass, $first,
                   10373:         $middle,  $last,  $gene,
1.1058    raeburn  10374:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10375:     $udom= &LONCAPA::clean_domain($udom);
                   10376:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10377:     my $showcandelete = 'none';
                   10378:     if (ref($candelete) eq 'ARRAY') {
                   10379:         if (@{$candelete} > 0) {
                   10380:             $showcandelete = join(', ',@{$candelete});
                   10381:         }
                   10382:     }
1.81      www      10383:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10384:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10385: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10386:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10387:                                      ' desiredhome not specified'). 
1.620     albertel 10388:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10389:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10390:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10391:     my $newuser;
                   10392:     if ($uhome eq 'no_host') {
                   10393:         $newuser = 1;
1.1368    raeburn  10394:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10395:                 ($umode eq 'lti')) {
                   10396:             return 'error: more information needed to create new user';
                   10397:         }
1.1075    raeburn  10398:     }
1.80      www      10399: # ----------------------------------------------------------------- Create User
1.406     albertel 10400:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10401: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10402:         my $unhome='';
1.844     albertel 10403:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10404:             $unhome = $desiredhome;
1.620     albertel 10405: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10406: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10407:         } else { # load balancing routine for determining $unhome
1.81      www      10408:             my $loadm=10000000;
1.841     albertel 10409: 	    my %servers = &get_servers($udom,'library');
                   10410: 	    foreach my $tryserver (keys(%servers)) {
                   10411: 		my $answer=reply('load',$tryserver);
                   10412: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10413: 		    $loadm=$answer;
                   10414: 		    $unhome=$tryserver;
                   10415: 		}
1.80      www      10416: 	    }
                   10417:         }
                   10418:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10419: 	    return 'error: unable to find a home server for '.$uname.
                   10420:                    ' in domain '.$udom;
1.80      www      10421:         }
                   10422:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10423:                          &escape($upass),$unhome);
                   10424: 	unless ($reply eq 'ok') {
                   10425:             return 'error: '.$reply;
                   10426:         }   
1.230     stredwic 10427:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10428:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10429: 	    return 'error: unable verify users home machine.';
1.80      www      10430:         }
1.209     matthew  10431:     }   # End of creation of new user
1.80      www      10432: # ---------------------------------------------------------------------- Add ID
                   10433:     if ($uid) {
                   10434:        $uid=~tr/A-Z/a-z/;
                   10435:        my %uidhash=&idrget($udom,$uname);
1.196     www      10436:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10437:          && (!$forceid)) {
1.80      www      10438: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10439: 	      return 'error: user id "'.$uid.'" does not match '.
                   10440:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10441:           }
                   10442:        } else {
1.1300    raeburn  10443: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10444:        }
                   10445:     }
                   10446: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10447:     my @tmp=&get('environment',
1.899     raeburn  10448: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10449:                     'permanentemail','inststatus'],
1.134     albertel 10450: 		   $udom,$uname);
1.1075    raeburn  10451:     my (%names,%oldnames);
1.313     matthew  10452:     if ($tmp[0] =~ m/^error:.*/) { 
                   10453:         %names=(); 
                   10454:     } else {
                   10455:         %names = @tmp;
1.1075    raeburn  10456:         %oldnames = %names;
1.313     matthew  10457:     }
1.388     www      10458: #
1.1058    raeburn  10459: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10460: # of users did not contain them), do not overwrite existing values
                   10461: # unless field is in $candelete array ref.  
                   10462: #
                   10463: 
                   10464:     my @fields = ('firstname','middlename','lastname','generation',
                   10465:                   'permanentemail','id');
                   10466:     my %newvalues;
                   10467:     if (ref($candelete) eq 'ARRAY') {
                   10468:         foreach my $field (@fields) {
                   10469:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10470:                 if ($field eq 'firstname') {
                   10471:                     $names{$field} = $first;
                   10472:                 } elsif ($field eq 'middlename') {
                   10473:                     $names{$field} = $middle;
                   10474:                 } elsif ($field eq 'lastname') {
                   10475:                     $names{$field} = $last;
                   10476:                 } elsif ($field eq 'generation') { 
                   10477:                     $names{$field} = $gene;
                   10478:                 } elsif ($field eq 'permanentemail') {
                   10479:                     $names{$field} = $email;
                   10480:                 } elsif ($field eq 'id') {
                   10481:                     $names{$field}  = $uid;
                   10482:                 }
                   10483:             }
                   10484:         }
                   10485:     }
1.388     www      10486:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10487:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10488:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10489:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10490:     if ($email) {
                   10491:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10492:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10493:     }
1.899     raeburn  10494:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10495:     if (defined($inststatus)) {
                   10496:         $names{'inststatus'} = '';
                   10497:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10498:         if (ref($usertypes) eq 'HASH') {
                   10499:             my @okstatuses; 
                   10500:             foreach my $item (split(/:/,$inststatus)) {
                   10501:                 if (defined($usertypes->{$item})) {
                   10502:                     push(@okstatuses,$item);  
                   10503:                 }
                   10504:             }
                   10505:             if (@okstatuses) {
                   10506:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10507:             }
                   10508:         }
                   10509:     }
1.1075    raeburn  10510:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10511:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10512:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10513:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10514:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10515:     } else {
                   10516:         $logmsg .= ' during self creation';
                   10517:     }
1.1075    raeburn  10518:     my $changed;
                   10519:     if ($newuser) {
                   10520:         $changed = 1;
                   10521:     } else {
                   10522:         foreach my $field (@fields) {
                   10523:             if ($names{$field} ne $oldnames{$field}) {
                   10524:                 $changed = 1;
                   10525:                 last;
                   10526:             }
                   10527:         }
                   10528:     }
                   10529:     unless ($changed) {
                   10530:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10531:         &logthis($logmsg);
                   10532:         return 'ok';
                   10533:     }
                   10534:     my $reply = &put('environment', \%names, $udom,$uname);
                   10535:     if ($reply ne 'ok') { 
                   10536:         return 'error: '.$reply;
                   10537:     }
1.1087    raeburn  10538:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10539:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10540:     }
1.1075    raeburn  10541:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10542:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10543:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10544:     &logthis($logmsg);
1.134     albertel 10545:     return 'ok';
1.80      www      10546: }
                   10547: 
1.81      www      10548: # -------------------------------------------------------------- Modify student
1.80      www      10549: 
1.81      www      10550: sub modifystudent {
                   10551:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10552:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10553:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10554:     if (!$cid) {
1.620     albertel 10555: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10556: 	    return 'not_in_class';
                   10557: 	}
1.80      www      10558:     }
                   10559: # --------------------------------------------------------------- Make the user
1.81      www      10560:     my $reply=&modifyuser
1.209     matthew  10561: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10562:          $desiredhome,$email,$inststatus);
1.80      www      10563:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10564:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10565:     # student's environment
1.297     matthew  10566:     $uid = undef if (!$forceid);
1.455     albertel 10567:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10568:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10569:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10570:     return $reply;
                   10571: }
                   10572: 
                   10573: sub modify_student_enrollment {
1.1216    raeburn  10574:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10575:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10576:     my ($cdom,$cnum,$chome);
                   10577:     if (!$cid) {
1.620     albertel 10578: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10579: 	    return 'not_in_class';
                   10580: 	}
1.620     albertel 10581: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10582: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10583:     } else {
                   10584: 	($cdom,$cnum)=split(/_/,$cid);
                   10585:     }
1.620     albertel 10586:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10587:     if (!$chome) {
1.457     raeburn  10588: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10589:     }
1.455     albertel 10590:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10591:     # Make sure the user exists
1.81      www      10592:     my $uhome=&homeserver($uname,$udom);
                   10593:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10594: 	return 'error: no such user';
                   10595:     }
1.297     matthew  10596:     # Get student data if we were not given enough information
                   10597:     if (!defined($first)  || $first  eq '' || 
                   10598:         !defined($last)   || $last   eq '' || 
                   10599:         !defined($uid)    || $uid    eq '' || 
                   10600:         !defined($middle) || $middle eq '' || 
                   10601:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10602:         # They did not supply us with enough data to enroll the student, so
                   10603:         # we need to pick up more information.
1.297     matthew  10604:         my %tmp = &get('environment',
1.294     matthew  10605:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10606:                        ,$udom,$uname);
                   10607: 
1.800     albertel 10608:         #foreach my $key (keys(%tmp)) {
                   10609:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10610:         #}
1.294     matthew  10611:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10612:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10613:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10614:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10615:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10616:     }
1.556     albertel 10617:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10618:     my $user = "$uname:$udom";
                   10619:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10620:     my $reply=cput('classlist',
1.1148    raeburn  10621: 		   {$user => 
1.1314    raeburn  10622: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10623: 		   $cdom,$cnum);
1.1148    raeburn  10624:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10625:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10626:     } else { 
1.81      www      10627: 	return 'error: '.$reply;
                   10628:     }
1.297     matthew  10629:     # Add student role to user
1.83      www      10630:     my $uurl='/'.$cid;
1.81      www      10631:     $uurl=~s/\_/\//g;
                   10632:     if ($usec) {
                   10633: 	$uurl.='/'.$usec;
                   10634:     }
1.1148    raeburn  10635:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10636:                              $selfenroll,$context);
                   10637:     if ($result ne 'ok') {
                   10638:         if ($old_entry{$user} ne '') {
                   10639:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10640:         } else {
                   10641:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10642:         }
                   10643:     }
                   10644:     return $result; 
1.21      www      10645: }
                   10646: 
1.556     albertel 10647: sub format_name {
                   10648:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10649:     my $name;
                   10650:     if ($first ne 'lastname') {
                   10651: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10652:     } else {
                   10653: 	if ($lastname=~/\S/) {
                   10654: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10655: 	    $name=~s/\s+,/,/;
                   10656: 	} else {
                   10657: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10658: 	}
                   10659:     }
                   10660:     $name=~s/^\s+//;
                   10661:     $name=~s/\s+$//;
                   10662:     $name=~s/\s+/ /g;
                   10663:     return $name;
                   10664: }
                   10665: 
1.84      www      10666: # ------------------------------------------------- Write to course preferences
                   10667: 
                   10668: sub writecoursepref {
                   10669:     my ($courseid,%prefs)=@_;
                   10670:     $courseid=~s/^\///;
                   10671:     $courseid=~s/\_/\//g;
                   10672:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10673:     my $chome=homeserver($cnum,$cdomain);
                   10674:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10675: 	return 'error: no such course';
                   10676:     }
                   10677:     my $cstring='';
1.800     albertel 10678:     foreach my $pref (keys(%prefs)) {
                   10679: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10680:     }
1.84      www      10681:     $cstring=~s/\&$//;
                   10682:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10683: }
                   10684: 
                   10685: # ---------------------------------------------------------- Make/modify course
                   10686: 
                   10687: sub createcourse {
1.741     raeburn  10688:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  10689:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10690:     $url=&declutter($url);
                   10691:     my $cid='';
1.1028    raeburn  10692:     if ($context eq 'requestcourses') {
                   10693:         my $can_create = 0;
                   10694:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10695:         if ($udom eq $ownerdom) {
1.1423    raeburn  10696:             my $reload;
                   10697:             if (($callercontext eq 'auto') &&
                   10698:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10699:                 $reload = 'reload';
                   10700:             }
                   10701:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10702:                                   $context)) {
                   10703:                 $can_create = 1;
                   10704:             }
                   10705:         } else {
                   10706:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10707:                                            $category);
                   10708:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10709:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10710:                 if (@curr > 0) {
                   10711:                     my @options = qw(approval validate autolimit);
                   10712:                     my $optregex = join('|',@options);
                   10713:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10714:                         $can_create = 1;
                   10715:                     }
                   10716:                 }
                   10717:             }
                   10718:         }
                   10719:         if ($can_create) {
                   10720:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10721:                 unless (&allowed('ccc',$udom)) {
                   10722:                     return 'refused'; 
                   10723:                 }
1.1017    raeburn  10724:             }
                   10725:         } else {
                   10726:             return 'refused';
                   10727:         }
1.1028    raeburn  10728:     } elsif (!&allowed('ccc',$udom)) {
                   10729:         return 'refused';
1.84      www      10730:     }
1.1011    raeburn  10731: # --------------------------------------------------------------- Get Unique ID
                   10732:     my $uname;
                   10733:     if ($cnum =~ /^$match_courseid$/) {
                   10734:         my $chome=&homeserver($cnum,$udom,'true');
                   10735:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10736:             $uname = $cnum;
                   10737:         } else {
1.1038    raeburn  10738:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10739:         }
                   10740:     } else {
1.1038    raeburn  10741:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10742:     }
                   10743:     return $uname if ($uname =~ /^error/);
                   10744: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10745:     if (!defined($course_server)) {
                   10746:         if (defined(&domain($udom,'primary'))) {
                   10747:             $course_server = &domain($udom,'primary');
                   10748:         } else {
                   10749:             $course_server = $env{'user.home'}; 
                   10750:         }
                   10751:     }
                   10752:     my %host_servers =
                   10753:         &Apache::lonnet::get_servers($udom,'library');
                   10754:     unless ($host_servers{$course_server}) {
                   10755:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10756:     }
1.84      www      10757: # ------------------------------------------------------------- Make the course
                   10758:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10759:                       $course_server);
1.84      www      10760:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10761:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10762:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10763: 	return 'error: no such course';
                   10764:     }
1.271     www      10765: # ----------------------------------------------------------------- Course made
1.516     raeburn  10766: # log existence
1.1029    raeburn  10767:     my $now = time;
1.918     raeburn  10768:     my $newcourse = {
                   10769:                     $udom.'_'.$uname => {
1.921     raeburn  10770:                                      description => $description,
                   10771:                                      inst_code   => $inst_code,
                   10772:                                      owner       => $course_owner,
                   10773:                                      type        => $crstype,
1.1029    raeburn  10774:                                      creator     => $env{'user.name'}.':'.
                   10775:                                                     $env{'user.domain'},
                   10776:                                      created     => $now,
                   10777:                                      context     => $context,
1.918     raeburn  10778:                                                 },
                   10779:                     };
1.921     raeburn  10780:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10781: # set toplevel url
1.271     www      10782:     my $topurl=$url;
                   10783:     unless ($nonstandard) {
                   10784: # ------------------------------------------ For standard courses, make top url
                   10785:         my $mapurl=&clutter($url);
1.278     www      10786:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10787:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10788: <map>
                   10789: <resource id="1" type="start"></resource>
                   10790: <resource id="2" src="$mapurl"></resource>
                   10791: <resource id="3" type="finish"></resource>
                   10792: <link index="1" from="1" to="2"></link>
                   10793: <link index="2" from="2" to="3"></link>
                   10794: </map>
                   10795: ENDINITMAP
                   10796:         $topurl=&declutter(
1.638     albertel 10797:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10798:                           );
                   10799:     }
                   10800: # ----------------------------------------------------------- Write preferences
1.84      www      10801:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10802:                      ('description'              => $description,
                   10803:                       'url'                      => $topurl,
                   10804:                       'internal.creator'         => $env{'user.name'}.':'.
                   10805:                                                     $env{'user.domain'},
                   10806:                       'internal.created'         => $now,
                   10807:                       'internal.creationcontext' => $context)
                   10808:                     );
1.84      www      10809:     return '/'.$udom.'/'.$uname;
                   10810: }
                   10811: 
1.1011    raeburn  10812: # ------------------------------------------------------------------- Create ID
                   10813: sub generate_coursenum {
1.1038    raeburn  10814:     my ($udom,$crstype) = @_;
1.1011    raeburn  10815:     my $domdesc = &domain($udom);
                   10816:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10817:     my $first;
                   10818:     if ($crstype eq 'Community') {
                   10819:         $first = '0';
                   10820:     } else {
                   10821:         $first = int(1+rand(9)); 
                   10822:     } 
                   10823:     my $uname=$first.
1.1011    raeburn  10824:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10825:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10826:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10827: # ----------------------------------------------- Make sure that does not exist
                   10828:     my $uhome=&homeserver($uname,$udom,'true');
                   10829:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10830:         if ($crstype eq 'Community') {
                   10831:             $first = '0';
                   10832:         } else {
                   10833:             $first = int(1+rand(9));
                   10834:         }
                   10835:         $uname=$first.
1.1011    raeburn  10836:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10837:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10838:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10839:         $uhome=&homeserver($uname,$udom,'true');
                   10840:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10841:             return 'error: unable to generate unique course-ID';
                   10842:         }
                   10843:     }
                   10844:     return $uname;
                   10845: }
                   10846: 
1.813     albertel 10847: sub is_course {
1.1167    droeschl 10848:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10849:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10850: 
1.1381    raeburn  10851:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10852:     my $uhome=&homeserver($cnum,$cdom);
                   10853:     my $iscourse;
                   10854:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10855:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10856:     } else {
                   10857:         my $hashid = $cdom.':'.$cnum;
                   10858:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10859:         unless (defined($cached)) {
                   10860:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10861:                                         $cnum,undef,undef,'.');
                   10862:             $iscourse = 0;
                   10863:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10864:                 $iscourse = 1;
                   10865:             }
                   10866:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10867:         }
                   10868:     }
                   10869:     return unless ($iscourse);
1.1167    droeschl 10870:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10871: }
                   10872: 
1.1015    raeburn  10873: sub store_userdata {
                   10874:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10875:     my $result;
1.1016    raeburn  10876:     if ($datakey ne '') {
1.1013    raeburn  10877:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10878:             if ($udom eq '' || $uname eq '') {
                   10879:                 $udom = $env{'user.domain'};
                   10880:                 $uname = $env{'user.name'};
                   10881:             }
                   10882:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10883:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10884:                 $result = 'error: no_host';
                   10885:             } else {
1.1434    raeburn  10886:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10887:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10888: 
                   10889:                 my $namevalue='';
                   10890:                 foreach my $key (keys(%{$storehash})) {
                   10891:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10892:                 }
                   10893:                 $namevalue=~s/\&$//;
1.1224    raeburn  10894:                 unless ($namespace eq 'courserequests') {
                   10895:                     $datakey = &escape($datakey);
                   10896:                 }
1.1105    raeburn  10897:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10898:                                   $namevalue,$uhome);
1.1013    raeburn  10899:             }
                   10900:         } else {
                   10901:             $result = 'error: data to store was not a hash reference'; 
                   10902:         }
                   10903:     } else {
                   10904:         $result= 'error: invalid requestkey'; 
                   10905:     }
                   10906:     return $result;
                   10907: }
                   10908: 
1.21      www      10909: # ---------------------------------------------------------- Assign Custom Role
                   10910: 
                   10911: sub assigncustomrole {
1.957     raeburn  10912:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10913:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10914:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10915: }
                   10916: 
                   10917: # ----------------------------------------------------------------- Revoke Role
                   10918: 
                   10919: sub revokerole {
1.957     raeburn  10920:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10921:     my $now=time;
1.965     raeburn  10922:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10923: }
                   10924: 
                   10925: # ---------------------------------------------------------- Revoke Custom Role
                   10926: 
                   10927: sub revokecustomrole {
1.957     raeburn  10928:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10929:     my $now=time;
1.357     www      10930:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10931:            $deleteflag,$selfenroll,$context);
1.17      www      10932: }
                   10933: 
1.533     banghart 10934: # ------------------------------------------------------------ Disk usage
1.535     albertel 10935: sub diskusage {
1.955     raeburn  10936:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10937:     $directorypath =~ s/\/$//;
                   10938:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10939:                        .&escape($getpropath).':'.&escape($uname).':'
                   10940:                        .&escape($udom),homeserver($uname,$udom));
                   10941:     if ($listing eq 'unknown_cmd') {
                   10942:         if ($getpropath) {
                   10943:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10944:         }
                   10945:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10946:     }
1.514     albertel 10947:     return $listing;
1.512     banghart 10948: }
                   10949: 
1.566     banghart 10950: sub is_locked {
1.1096    raeburn  10951:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10952:     my @check;
                   10953:     my $is_locked;
1.1093    raeburn  10954:     push (@check,$file_name);
1.613     albertel 10955:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10956: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10957:     my ($tmp)=keys(%locked);
                   10958:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10959:     
1.566     banghart 10960:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10961:         $is_locked = 'false';
                   10962:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10963:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10964:                $is_locked = 'true';
1.1096    raeburn  10965:                if (ref($which) eq 'ARRAY') {
                   10966:                    push(@{$which},$entry);
                   10967:                } else {
                   10968:                    last;
                   10969:                }
1.745     raeburn  10970:            }
                   10971:        }
1.566     banghart 10972:     } else {
                   10973:         $is_locked = 'false';
                   10974:     }
1.1093    raeburn  10975:     return $is_locked;
1.566     banghart 10976: }
                   10977: 
1.759     albertel 10978: sub declutter_portfile {
                   10979:     my ($file) = @_;
1.833     albertel 10980:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10981:     return $file;
                   10982: }
                   10983: 
1.559     banghart 10984: # ------------------------------------------------------------- Mark as Read Only
                   10985: 
                   10986: sub mark_as_readonly {
                   10987:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10988:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10989:     my ($tmp)=keys(%current_permissions);
                   10990:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10991:     foreach my $file (@{$files}) {
1.759     albertel 10992: 	$file = &declutter_portfile($file);
1.561     banghart 10993:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10994:     }
1.613     albertel 10995:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10996:     return;
                   10997: }
                   10998: 
1.572     banghart 10999: # ------------------------------------------------------------Save Selected Files
                   11000: 
                   11001: sub save_selected_files {
                   11002:     my ($user, $path, @files) = @_;
                   11003:     my $filename = $user."savedfiles";
1.573     banghart 11004:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  11005:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11006:     foreach my $file (@files) {
1.620     albertel 11007:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11008:     }
                   11009:     foreach my $file (@other_files) {
1.574     banghart 11010:         print (OUT $file."\n");
1.572     banghart 11011:     }
1.574     banghart 11012:     close (OUT);
1.572     banghart 11013:     return 'ok';
                   11014: }
                   11015: 
1.574     banghart 11016: sub clear_selected_files {
                   11017:     my ($user) = @_;
                   11018:     my $filename = $user."savedfiles";
1.1359    raeburn  11019:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11020:     print (OUT undef);
                   11021:     close (OUT);
                   11022:     return ("ok");    
                   11023: }
                   11024: 
1.572     banghart 11025: sub files_in_path {
                   11026:     my ($user, $path) = @_;
                   11027:     my $filename = $user."savedfiles";
                   11028:     my %return_files;
1.1359    raeburn  11029:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11030:     while (my $line_in = <IN>) {
1.574     banghart 11031:         chomp ($line_in);
                   11032:         my @paths_and_file = split (m!/!, $line_in);
                   11033:         my $file_part = pop (@paths_and_file);
                   11034:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11035:         $path_part.='/';
                   11036:         my $path_and_file = $path_part.$file_part;
                   11037:         if ($path_part eq $path) {
                   11038:             $return_files{$file_part}= 'selected';
                   11039:         }
                   11040:     }
1.574     banghart 11041:     close (IN);
                   11042:     return (\%return_files);
1.572     banghart 11043: }
                   11044: 
                   11045: # called in portfolio select mode, to show files selected NOT in current directory
                   11046: sub files_not_in_path {
                   11047:     my ($user, $path) = @_;
                   11048:     my $filename = $user."savedfiles";
                   11049:     my @return_files;
                   11050:     my $path_part;
1.1359    raeburn  11051:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11052:     while (my $line = <IN>) {
1.572     banghart 11053:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11054:         my @paths_and_file = split(m|/|, $line);
                   11055:         my $file_part = pop(@paths_and_file);
                   11056:         chomp($file_part);
                   11057:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11058:         $path_part .= '/';
                   11059:         my $path_and_file = $path_part.$file_part;
                   11060:         if ($path_part ne $path) {
1.800     albertel 11061:             push(@return_files, ($path_and_file));
1.572     banghart 11062:         }
                   11063:     }
1.800     albertel 11064:     close(OUT);
1.574     banghart 11065:     return (@return_files);
1.572     banghart 11066: }
                   11067: 
1.1273    raeburn  11068: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11069:  
                   11070: sub portfiles_versioning {
                   11071:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11072:     my $portfolio_root = '/userfiles/portfolio';
                   11073:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11074:     foreach my $file (@{$portfiles}) {
                   11075:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11076:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11077:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11078:         my $getpropath = 1;
                   11079:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11080:                                              $stu_name,$getpropath);
                   11081:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11082:         my $new_answer = 
                   11083:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11084:         if ($new_answer ne 'problem getting file') {
                   11085:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11086:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11087:                               [$symb,$env{'request.course.id'},'graded']);
                   11088:         }
                   11089:     }
                   11090: }
                   11091: 
                   11092: sub get_next_version {
                   11093:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11094:     my $version;
                   11095:     if (ref($dir_list) eq 'ARRAY') {
                   11096:         foreach my $row (@{$dir_list}) {
                   11097:             my ($file) = split(/\&/,$row,2);
                   11098:             my ($file_name,$file_version,$file_ext) =
                   11099:                 &file_name_version_ext($file);
                   11100:             if (($file_name eq $answer_name) &&
                   11101:                 ($file_ext eq $answer_ext)) {
                   11102:                      # gets here if filename and extension match,
                   11103:                      # regardless of version
                   11104:                 if ($file_version ne '') {
                   11105:                     # a versioned file is found  so save it for later
                   11106:                     if ($file_version > $version) {
                   11107:                         $version = $file_version;
                   11108:                     }
                   11109:                 }
                   11110:             }
                   11111:         }
                   11112:     }
                   11113:     $version ++;
                   11114:     return($version);
                   11115: }
                   11116: 
                   11117: sub version_selected_portfile {
                   11118:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11119:     my ($answer_name,$answer_ver,$answer_ext) =
                   11120:         &file_name_version_ext($file_name);
                   11121:     my $new_answer;
                   11122:     $env{'form.copy'} =
                   11123:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11124:     if($env{'form.copy'} eq '-1') {
                   11125:         $new_answer = 'problem getting file';
                   11126:     } else {
                   11127:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11128:         my $copy_result = 
                   11129:             &finishuserfileupload($stu_name,$domain,'copy',
                   11130:                                   '/portfolio'.$directory.$new_answer);
                   11131:     }
                   11132:     undef($env{'form.copy'});
                   11133:     return ($new_answer);
                   11134: }
                   11135: 
                   11136: sub file_name_version_ext {
                   11137:     my ($file)=@_;
                   11138:     my @file_parts = split(/\./, $file);
                   11139:     my ($name,$version,$ext);
                   11140:     if (@file_parts > 1) {
                   11141:         $ext=pop(@file_parts);
                   11142:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11143:             $version=pop(@file_parts);
                   11144:         }
                   11145:         $name=join('.',@file_parts);
                   11146:     } else {
                   11147:         $name=join('.',@file_parts);
                   11148:     }
                   11149:     return($name,$version,$ext);
                   11150: }
                   11151: 
1.745     raeburn  11152: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11153: 
1.745     raeburn  11154: sub get_portfile_permissions {
                   11155:     my ($domain,$user) = @_;
1.613     albertel 11156:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11157:     my ($tmp)=keys(%current_permissions);
                   11158:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11159:     return \%current_permissions;
                   11160: }
                   11161: 
                   11162: #---------------------------------------------Get portfolio file access controls
                   11163: 
1.749     raeburn  11164: sub get_access_controls {
1.745     raeburn  11165:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11166:     my %access;
                   11167:     my $real_file = $file;
                   11168:     $file =~ s/\.meta$//;
1.745     raeburn  11169:     if (defined($file)) {
1.749     raeburn  11170:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11171:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11172:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11173:             }
                   11174:         }
1.745     raeburn  11175:     } else {
1.749     raeburn  11176:         foreach my $key (keys(%{$current_permissions})) {
                   11177:             if ($key =~ /\0accesscontrol$/) {
                   11178:                 if (defined($group)) {
                   11179:                     if ($key !~ m-^\Q$group\E/-) {
                   11180:                         next;
                   11181:                     }
                   11182:                 }
                   11183:                 my ($fullpath) = split(/\0/,$key);
                   11184:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11185:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11186:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11187:                     }
                   11188:                 }
                   11189:             }
                   11190:         }
                   11191:     }
                   11192:     return %access;
                   11193: }
                   11194: 
                   11195: sub modify_access_controls {
                   11196:     my ($file_name,$changes,$domain,$user)=@_;
                   11197:     my ($outcome,$deloutcome);
                   11198:     my %store_permissions;
                   11199:     my %new_values;
                   11200:     my %new_control;
                   11201:     my %translation;
                   11202:     my @deletions = ();
                   11203:     my $now = time;
                   11204:     if (exists($$changes{'activate'})) {
                   11205:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11206:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11207:             my $numnew = scalar(@newitems);
                   11208:             for (my $i=0; $i<$numnew; $i++) {
                   11209:                 my $newkey = $newitems[$i];
                   11210:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11211:                 if ($newkey =~ /^\d+:/) { 
                   11212:                     $newkey =~ s/^(\d+)/$newid/;
                   11213:                     $translation{$1} = $newid;
                   11214:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11215:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11216:                     $translation{$1} = $newid;
                   11217:                 }
1.749     raeburn  11218:                 $new_values{$file_name."\0".$newkey} = 
                   11219:                                           $$changes{'activate'}{$newitems[$i]};
                   11220:                 $new_control{$newkey} = $now;
                   11221:             }
                   11222:         }
                   11223:     }
                   11224:     my %todelete;
                   11225:     my %changed_items;
                   11226:     foreach my $action ('delete','update') {
                   11227:         if (exists($$changes{$action})) {
                   11228:             if (ref($$changes{$action}) eq 'HASH') {
                   11229:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11230:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11231:                     if ($action eq 'delete') { 
                   11232:                         $todelete{$itemnum} = 1;
                   11233:                     } else {
                   11234:                         $changed_items{$itemnum} = $key;
                   11235:                     }
                   11236:                 }
1.745     raeburn  11237:             }
                   11238:         }
1.749     raeburn  11239:     }
                   11240:     # get lock on access controls for file.
                   11241:     my $lockhash = {
                   11242:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11243:                                                        ':'.$env{'user.domain'},
                   11244:                    }; 
                   11245:     my $tries = 0;
                   11246:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11247:    
1.1288    damieng  11248:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11249:         $tries ++;
1.1289    damieng  11250:         sleep(0.1);
1.749     raeburn  11251:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11252:     }
                   11253:     if ($gotlock eq 'ok') {
                   11254:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11255:         my ($tmp)=keys(%curr_permissions);
                   11256:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11257:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11258:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11259:             if (ref($curr_controls) eq 'HASH') {
                   11260:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11261:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11262:                     if (defined($todelete{$itemnum})) {
                   11263:                         push(@deletions,$file_name."\0".$control_item);
                   11264:                     } else {
                   11265:                         if (defined($changed_items{$itemnum})) {
                   11266:                             $new_control{$changed_items{$itemnum}} = $now;
                   11267:                             push(@deletions,$file_name."\0".$control_item);
                   11268:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11269:                         } else {
                   11270:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11271:                         }
                   11272:                     }
1.745     raeburn  11273:                 }
                   11274:             }
                   11275:         }
1.970     raeburn  11276:         my ($group);
                   11277:         if (&is_course($domain,$user)) {
                   11278:             ($group,my $file) = split(/\//,$file_name,2);
                   11279:         }
1.749     raeburn  11280:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11281:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11282:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11283:         #  remove lock
                   11284:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11285:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11286:         my $sqlresult =
1.970     raeburn  11287:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11288:                                     $group);
1.749     raeburn  11289:     } else {
                   11290:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11291:     }
1.749     raeburn  11292:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11293: }
                   11294: 
1.827     raeburn  11295: sub make_public_indefinitely {
1.1271    raeburn  11296:     my (@requrl) = @_;
                   11297:     return &automated_portfile_access('public',\@requrl);
                   11298: }
                   11299: 
                   11300: sub automated_portfile_access {
                   11301:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11302:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11303:         return 'invalid';
                   11304:     }
1.1271    raeburn  11305:     my %urls;
                   11306:     if (ref($addsref) eq 'ARRAY') {
                   11307:         foreach my $requrl (@{$addsref}) {
                   11308:             if (&is_portfolio_url($requrl)) {
                   11309:                 unless (exists($urls{$requrl})) {
                   11310:                     $urls{$requrl} = 'add';
                   11311:                 }
                   11312:             }
                   11313:         }
                   11314:     }
                   11315:     if (ref($delsref) eq 'ARRAY') {
                   11316:         foreach my $requrl (@{$delsref}) { 
                   11317:             if (&is_portfolio_url($requrl)) {
                   11318:                 unless (exists($urls{$requrl})) {
                   11319:                     $urls{$requrl} = 'delete'; 
                   11320:                 }
                   11321:             }
                   11322:         }
                   11323:     }
                   11324:     unless (keys(%urls)) {
                   11325:         return 'invalid';
                   11326:     }
                   11327:     my $ip;
                   11328:     if ($accesstype eq 'ip') {
                   11329:         if (ref($info) eq 'HASH') {
                   11330:             if ($info->{'ip'} ne '') {
                   11331:                 $ip = $info->{'ip'};
                   11332:             }
                   11333:         }
                   11334:         if ($ip eq '') {
                   11335:             return 'invalid';
                   11336:         }
                   11337:     }
                   11338:     my $errors;
1.827     raeburn  11339:     my $now = time;
1.1271    raeburn  11340:     my %current_perms;
                   11341:     foreach my $requrl (sort(keys(%urls))) {
                   11342:         my $action;
                   11343:         if ($urls{$requrl} eq 'add') {
                   11344:             $action = 'activate';
                   11345:         } else {
                   11346:             $action = 'none';
                   11347:         }
                   11348:         my $aclnum = 0;
1.827     raeburn  11349:         my (undef,$udom,$unum,$file_name,$group) =
                   11350:             &parse_portfolio_url($requrl);
1.1271    raeburn  11351:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11352:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11353:         }
                   11354:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11355:                                                    $group,$file_name);
                   11356:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11357:             my ($num,$scope,$end,$start) = 
                   11358:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11359:             if ($scope eq $accesstype) {
                   11360:                 if (($start <= $now) && ($end == 0)) {
                   11361:                     if ($accesstype eq 'ip') {
                   11362:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11363:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11364:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11365:                                     if ($urls{$requrl} eq 'add') {
                   11366:                                         $action = 'none';
                   11367:                                         last;
                   11368:                                     } else {
                   11369:                                         $action = 'delete';
                   11370:                                         $aclnum = $num;
                   11371:                                         last;
                   11372:                                     }
                   11373:                                 }
                   11374:                             }
                   11375:                         }
                   11376:                     } elsif ($accesstype eq 'public') {
                   11377:                         if ($urls{$requrl} eq 'add') {
                   11378:                             $action = 'none';
                   11379:                             last;
                   11380:                         } else {
                   11381:                             $action = 'delete';
                   11382:                             $aclnum = $num;
                   11383:                             last;
                   11384:                         }
                   11385:                     }
                   11386:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11387:                     $action = 'update';
                   11388:                     $aclnum = $num;
1.1271    raeburn  11389:                     last;
1.827     raeburn  11390:                 }
                   11391:             }
                   11392:         }
                   11393:         if ($action eq 'none') {
1.1271    raeburn  11394:             next;
1.827     raeburn  11395:         } else {
                   11396:             my %changes;
                   11397:             my $newend = 0;
                   11398:             my $newstart = $now;
1.1271    raeburn  11399:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11400:             $changes{$action}{$newkey} = {
1.1271    raeburn  11401:                 type => $accesstype,
1.827     raeburn  11402:                 time => {
                   11403:                     start => $newstart,
                   11404:                     end   => $newend,
                   11405:                 },
                   11406:             };
1.1271    raeburn  11407:             if ($accesstype eq 'ip') {
                   11408:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11409:             }
1.827     raeburn  11410:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11411:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11412:             unless ($outcome eq 'ok') {
                   11413:                 $errors .= $outcome.' ';
                   11414:             }
1.827     raeburn  11415:         }
1.1271    raeburn  11416:     }
                   11417:     if ($errors) {
                   11418:         $errors =~ s/\s$//;
                   11419:         return $errors;
1.827     raeburn  11420:     } else {
1.1271    raeburn  11421:         return 'ok';
1.827     raeburn  11422:     }
                   11423: }
                   11424: 
1.745     raeburn  11425: #------------------------------------------------------Get Marked as Read Only
                   11426: 
                   11427: sub get_marked_as_readonly {
                   11428:     my ($domain,$user,$what,$group) = @_;
                   11429:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11430:     my @readonly_files;
1.629     banghart 11431:     my $cmp1=$what;
                   11432:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11433:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11434:         if (defined($group)) {
                   11435:             if ($file_name !~ m-^\Q$group\E/-) {
                   11436:                 next;
                   11437:             }
                   11438:         }
1.561     banghart 11439:         if (ref($value) eq "ARRAY"){
                   11440:             foreach my $stored_what (@{$value}) {
1.629     banghart 11441:                 my $cmp2=$stored_what;
1.759     albertel 11442:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11443:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11444:                 }
1.629     banghart 11445:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11446:                     push(@readonly_files, $file_name);
1.745     raeburn  11447:                     last;
1.563     banghart 11448:                 } elsif (!defined($what)) {
                   11449:                     push(@readonly_files, $file_name);
1.745     raeburn  11450:                     last;
1.561     banghart 11451:                 }
                   11452:             }
1.745     raeburn  11453:         }
1.561     banghart 11454:     }
                   11455:     return @readonly_files;
                   11456: }
1.577     banghart 11457: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11458: 
1.577     banghart 11459: sub get_marked_as_readonly_hash {
1.745     raeburn  11460:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11461:     my %readonly_files;
1.745     raeburn  11462:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11463:         if (defined($group)) {
                   11464:             if ($file_name !~ m-^\Q$group\E/-) {
                   11465:                 next;
                   11466:             }
                   11467:         }
1.577     banghart 11468:         if (ref($value) eq "ARRAY"){
                   11469:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11470:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11471:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11472:                         if ($lock_descriptor eq 'graded') {
                   11473:                             $readonly_files{$file_name} = 'graded';
                   11474:                         } elsif ($lock_descriptor eq 'handback') {
                   11475:                             $readonly_files{$file_name} = 'handback';
                   11476:                         } else {
                   11477:                             if (!exists($readonly_files{$file_name})) {
                   11478:                                 $readonly_files{$file_name} = 'locked';
                   11479:                             }
                   11480:                         }
1.745     raeburn  11481:                     }
1.750     banghart 11482:                 } 
1.577     banghart 11483:             }
                   11484:         } 
                   11485:     }
                   11486:     return %readonly_files;
                   11487: }
1.559     banghart 11488: # ------------------------------------------------------------ Unmark as Read Only
                   11489: 
                   11490: sub unmark_as_readonly {
1.629     banghart 11491:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11492:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11493:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11494:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11495:     my $symb_crs = $what;
                   11496:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11497:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11498:     my ($tmp)=keys(%current_permissions);
                   11499:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11500:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11501:     foreach my $file (@readonly_files) {
1.759     albertel 11502: 	my $clean_file = &declutter_portfile($file);
                   11503: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11504: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11505:         my @new_locks;
                   11506:         my @del_keys;
                   11507:         if (ref($current_locks) eq "ARRAY"){
                   11508:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11509:                 my $compare=$locker;
1.749     raeburn  11510:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11511:                     $compare=join('',@{$locker});
1.746     raeburn  11512:                     if ($compare ne $symb_crs) {
                   11513:                         push(@new_locks, $locker);
                   11514:                     }
1.563     banghart 11515:                 }
                   11516:             }
1.650     albertel 11517:             if (scalar(@new_locks) > 0) {
1.563     banghart 11518:                 $current_permissions{$file} = \@new_locks;
                   11519:             } else {
                   11520:                 push(@del_keys, $file);
1.613     albertel 11521:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11522:                 delete($current_permissions{$file});
1.563     banghart 11523:             }
                   11524:         }
1.561     banghart 11525:     }
1.613     albertel 11526:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11527:     return;
                   11528: }
1.512     banghart 11529: 
1.17      www      11530: # ------------------------------------------------------------ Directory lister
                   11531: 
                   11532: sub dirlist {
1.955     raeburn  11533:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11534:     $uri=~s/^\///;
                   11535:     $uri=~s/\/$//;
1.253     stredwic 11536:     my ($udom, $uname);
1.955     raeburn  11537:     if ($getuserdir) {
1.253     stredwic 11538:         $udom = $userdomain;
                   11539:         $uname = $username;
1.955     raeburn  11540:     } else {
                   11541:         (undef,$udom,$uname)=split(/\//,$uri);
                   11542:         if(defined($userdomain)) {
                   11543:             $udom = $userdomain;
                   11544:         }
                   11545:         if(defined($username)) {
                   11546:             $uname = $username;
                   11547:         }
1.253     stredwic 11548:     }
1.955     raeburn  11549:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11550: 
1.955     raeburn  11551:     $dirRoot = $perlvar{'lonDocRoot'};
                   11552:     if (defined($getpropath)) {
                   11553:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11554:         $dirRoot =~ s/\/$//;
1.955     raeburn  11555:     } elsif (defined($getuserdir)) {
                   11556:         my $subdir=$uname.'__';
                   11557:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11558:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11559:                    ."/$udom/$subdir/$uname";
                   11560:     } elsif (defined($alternateRoot)) {
                   11561:         $dirRoot = $alternateRoot;
1.751     banghart 11562:     }
1.253     stredwic 11563: 
                   11564:     if($udom) {
                   11565:         if($uname) {
1.1135    raeburn  11566:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11567:             if ($uhome eq 'no_host') {
                   11568:                 return ([],'no_host');
                   11569:             }
1.955     raeburn  11570:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11571:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11572:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11573:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11574:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11575:             } else {
                   11576:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11577:             }
1.605     matthew  11578:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11579:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11580:                 @listing_results = split(/:/,$listing);
                   11581:             } else {
                   11582:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11583:             }
1.1135    raeburn  11584:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11585:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11586:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11587:                 return ([],$listing);
                   11588:             } else {
                   11589:                 return (\@listing_results);
1.1135    raeburn  11590:             }
1.955     raeburn  11591:         } elsif(!$alternateRoot) {
1.1136    raeburn  11592:             my (%allusers,%listerror);
1.841     albertel 11593: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11594:  	    foreach my $tryserver (keys(%servers)) {
                   11595:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11596:                                   &escape($udom),$tryserver);
                   11597:                 if ($listing eq 'unknown_cmd') {
                   11598: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11599: 				      $udom, $tryserver);
                   11600:                 } else {
                   11601:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11602:                 }
1.841     albertel 11603: 		if ($listing eq 'unknown_cmd') {
                   11604: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11605: 				      $udom, $tryserver);
                   11606: 		    @listing_results = split(/:/,$listing);
                   11607: 		} else {
                   11608: 		    @listing_results =
                   11609: 			map { &unescape($_); } split(/:/,$listing);
                   11610: 		}
1.1136    raeburn  11611:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11612:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11613:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11614:                     $listerror{$tryserver} = $listing;
                   11615:                 } else {
1.841     albertel 11616: 		    foreach my $line (@listing_results) {
                   11617: 			my ($entry) = split(/&/,$line,2);
                   11618: 			$allusers{$entry} = 1;
                   11619: 		    }
                   11620: 		}
1.253     stredwic 11621:             }
1.1136    raeburn  11622:             my @alluserslist=();
1.800     albertel 11623:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11624:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11625:             }
1.1318    droeschl 11626: 
                   11627:             if (!%listerror) {
                   11628:                 # no errors
                   11629:                 return (\@alluserslist);
                   11630:             } elsif (scalar(keys(%servers)) == 1) {
                   11631:                 # one library server, one error 
                   11632:                 my ($key) = keys(%listerror);
                   11633:                 return (\@alluserslist, $listerror{$key});
                   11634:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11635:                 # con_lost indicates that we might miss data from at least one
                   11636:                 # library server
                   11637:                 return (\@alluserslist, 'con_lost');
                   11638:             } else {
                   11639:                 # multiple library servers and no con_lost -> data should be
                   11640:                 # complete. 
                   11641:                 return (\@alluserslist);
                   11642:             }
                   11643: 
1.253     stredwic 11644:         } else {
1.1136    raeburn  11645:             return ([],'missing username');
1.253     stredwic 11646:         }
1.955     raeburn  11647:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11648:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11649:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11650:         return (\@all_domains);
1.955     raeburn  11651:     } else {
1.1136    raeburn  11652:         return ([],'missing domain');
1.275     stredwic 11653:     }
                   11654: }
                   11655: 
                   11656: # --------------------------------------------- GetFileTimestamp
                   11657: # This function utilizes dirlist and returns the date stamp for
                   11658: # when it was last modified.  It will also return an error of -1
                   11659: # if an error occurs
                   11660: 
                   11661: sub GetFileTimestamp {
1.955     raeburn  11662:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11663:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11664:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11665:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11666:                                     undef,$getuserdir);
                   11667:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11668:         return -1;
                   11669:     }
                   11670:     if (ref($fileref) eq 'ARRAY') {
                   11671:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11672:         # @stats contains first the filename, then the stat output
                   11673:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11674:     } else {
                   11675:         return -1;
1.253     stredwic 11676:     }
1.26      www      11677: }
                   11678: 
1.712     albertel 11679: sub stat_file {
                   11680:     my ($uri) = @_;
1.787     albertel 11681:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11682: 
1.955     raeburn  11683:     my ($udom,$uname,$file);
1.712     albertel 11684:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11685: 	($udom,$uname,$file) =
1.811     albertel 11686: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11687: 	$file = 'userfiles/'.$file;
                   11688:     }
                   11689:     if ($uri =~ m-^/res/-) {
                   11690: 	($udom,$uname) = 
1.807     albertel 11691: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11692: 	$file = $uri;
                   11693:     }
                   11694: 
                   11695:     if (!$udom || !$uname || !$file) {
                   11696: 	# unable to handle the uri
                   11697: 	return ();
                   11698:     }
1.956     raeburn  11699:     my $getpropath;
                   11700:     if ($file =~ /^userfiles\//) {
                   11701:         $getpropath = 1;
                   11702:     }
1.1136    raeburn  11703:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11704:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11705:         return ();
                   11706:     } else {
                   11707:         if (ref($listref) eq 'ARRAY') {
                   11708:             my @stats = split('&',$listref->[0]);
                   11709: 	    shift(@stats); #filename is first
                   11710: 	    return @stats;
                   11711:         }
1.712     albertel 11712:     }
                   11713:     return ();
                   11714: }
                   11715: 
1.1313    raeburn  11716: # --------------------------------------------------------- recursedirs
                   11717: # Recursive function to traverse either a specific user's Authoring Space
                   11718: # or corresponding Published Resource Space, and populate the hash ref:
                   11719: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11720: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11721: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11722: # files in Authoring Space.
                   11723: #
                   11724: # Inputs:
                   11725: #
                   11726: # $is_home - true if current server is home server for user's space
                   11727: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11728: # $docroot - Document root (i.e., /home/httpd/html
                   11729: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11730: # $relpath - Current path (relative to top level).
                   11731: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11732: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11733: #
                   11734: # Returns: nothing
                   11735: #
                   11736: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11737: #
                   11738: # Currently used by interface/londocs.pm to create linked select boxes for
                   11739: # directory and filename to import a Course "Author" resource into a course, and
                   11740: # also to create linked select boxes for Authoring Space and Directory to choose
                   11741: # save location for creation of a new "standard" problem from the Course Editor.
                   11742: #
                   11743: 
                   11744: sub recursedirs {
                   11745:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11746:     return unless (ref($dirhashref) eq 'HASH');
                   11747:     my $currpath = $docroot.$toppath;
                   11748:     if ($relpath) {
                   11749:         $currpath .= "/$relpath";
                   11750:     }
                   11751:     my $savefile;
                   11752:     if (ref($filehashref)) {
                   11753:         $savefile = 1;
                   11754:     }
                   11755:     if ($is_home) {
                   11756:         if (opendir(my $dirh,$currpath)) {
                   11757:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11758:                 next if ($item eq '');
                   11759:                 if (-d "$currpath/$item") {
                   11760:                     my $newpath;
                   11761:                     if ($relpath) {
                   11762:                         $newpath = "$relpath/$item";
                   11763:                     } else {
                   11764:                         $newpath = $item;
                   11765:                     }
                   11766:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11767:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11768:                 } elsif ($savefile) {
                   11769:                     if ($context eq 'priv') {
                   11770:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11771:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11772:                         }
                   11773:                     } else {
                   11774:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11775:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11776:                         }
                   11777:                     }
                   11778:                 }
                   11779:             }
                   11780:             closedir($dirh);
                   11781:         }
                   11782:     } else {
                   11783:         my ($dirlistref,$listerror) =
                   11784:             &dirlist($toppath.$relpath);
                   11785:         my @dir_lines;
                   11786:         my $dirptr=16384;
                   11787:         if (ref($dirlistref) eq 'ARRAY') {
                   11788:             foreach my $dir_line (sort
                   11789:                               {
                   11790:                                   my ($afile)=split('&',$a,2);
                   11791:                                   my ($bfile)=split('&',$b,2);
                   11792:                                   return (lc($afile) cmp lc($bfile));
                   11793:                               } (@{$dirlistref})) {
                   11794:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11795:                     split(/\&/,$dir_line,16);
                   11796:                 $item =~ s/\s+$//;
                   11797:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11798:                 if ($dirptr&$testdir) {
                   11799:                     my $newpath;
                   11800:                     if ($relpath) {
                   11801:                         $newpath = "$relpath/$item";
                   11802:                     } else {
                   11803:                         $relpath = '/';
                   11804:                         $newpath = $item;
                   11805:                     }
                   11806:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11807:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11808:                 } elsif ($savefile) {
                   11809:                     if ($context eq 'priv') {
                   11810:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11811:                             $filehashref->{$relpath}{$item} = 1;
                   11812:                         }
                   11813:                     } else {
                   11814:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11815:                             $filehashref->{$relpath}{$item} = 1;
                   11816:                         }
                   11817:                     }
                   11818:                 }
                   11819:             }
                   11820:         }
                   11821:     }
                   11822:     return;
                   11823: }
                   11824: 
1.26      www      11825: # -------------------------------------------------------- Value of a Condition
                   11826: 
1.713     albertel 11827: # gets the value of a specific preevaluated condition
                   11828: #    stored in the string  $env{user.state.<cid>}
                   11829: # or looks up a condition reference in the bighash and if if hasn't
                   11830: # already been evaluated recurses into docondval to get the value of
                   11831: # the condition, then memoizing it to 
                   11832: #   $env{user.state.<cid>.<condition>}
1.40      www      11833: sub directcondval {
                   11834:     my $number=shift;
1.620     albertel 11835:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11836: 	&Apache::lonuserstate::evalstate();
                   11837:     }
1.713     albertel 11838:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11839: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11840:     } elsif ($number =~ /^_/) {
                   11841: 	my $sub_condition;
                   11842: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11843: 		&GDBM_READER(),0640)) {
                   11844: 	    $sub_condition=$bighash{'conditions'.$number};
                   11845: 	    untie(%bighash);
                   11846: 	}
                   11847: 	my $value = &docondval($sub_condition);
1.949     raeburn  11848: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11849: 	return $value;
                   11850:     }
1.620     albertel 11851:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11852:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11853:     } else {
                   11854:        return 2;
                   11855:     }
                   11856: }
                   11857: 
1.713     albertel 11858: # get the collection of conditions for this resource
1.26      www      11859: sub condval {
                   11860:     my $condidx=shift;
1.54      www      11861:     my $allpathcond='';
1.713     albertel 11862:     foreach my $cond (split(/\|/,$condidx)) {
                   11863: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11864: 	    $allpathcond.=
                   11865: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11866: 	}
1.191     harris41 11867:     }
1.54      www      11868:     $allpathcond=~s/\|$//;
1.713     albertel 11869:     return &docondval($allpathcond);
                   11870: }
                   11871: 
                   11872: #evaluates an expression of conditions
                   11873: sub docondval {
                   11874:     my ($allpathcond) = @_;
                   11875:     my $result=0;
                   11876:     if ($env{'request.course.id'}
                   11877: 	&& defined($allpathcond)) {
                   11878: 	my $operand='|';
                   11879: 	my @stack;
                   11880: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11881: 	    if ($chunk eq '(') {
                   11882: 		push @stack,($operand,$result);
                   11883: 	    } elsif ($chunk eq ')') {
                   11884: 		my $before=pop @stack;
                   11885: 		if (pop @stack eq '&') {
                   11886: 		    $result=$result>$before?$before:$result;
                   11887: 		} else {
                   11888: 		    $result=$result>$before?$result:$before;
                   11889: 		}
                   11890: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11891: 		$operand=$chunk;
                   11892: 	    } else {
                   11893: 		my $new=directcondval($chunk);
                   11894: 		if ($operand eq '&') {
                   11895: 		    $result=$result>$new?$new:$result;
                   11896: 		} else {
                   11897: 		    $result=$result>$new?$result:$new;
                   11898: 		}
                   11899: 	    }
                   11900: 	}
1.26      www      11901:     }
                   11902:     return $result;
1.421     albertel 11903: }
                   11904: 
                   11905: # ---------------------------------------------------- Devalidate courseresdata
                   11906: 
                   11907: sub devalidatecourseresdata {
                   11908:     my ($coursenum,$coursedomain)=@_;
                   11909:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11910:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11911: }
                   11912: 
1.763     www      11913: 
1.200     www      11914: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11915: #
                   11916: #  Parameters:
                   11917: #      $coursenum    - Number of the course.
                   11918: #      $coursedomain - Domain at which the course was created.
                   11919: #  Returns:
                   11920: #     A hash of the course parameters along (I think) with timestamps
                   11921: #     and version info.
1.877     foxr     11922: 
1.624     albertel 11923: sub get_courseresdata {
                   11924:     my ($coursenum,$coursedomain)=@_;
1.200     www      11925:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11926:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11927:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11928:     my %dumpreply;
1.417     albertel 11929:     unless (defined($cached)) {
1.624     albertel 11930: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11931: 	$result=\%dumpreply;
1.251     albertel 11932: 	my ($tmp) = keys(%dumpreply);
                   11933: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11934: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11935: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11936: 	    return $tmp;
1.416     albertel 11937: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11938: 	    $result=undef;
1.599     albertel 11939: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11940: 	}
                   11941:     }
1.624     albertel 11942:     return $result;
                   11943: }
                   11944: 
1.633     albertel 11945: sub devalidateuserresdata {
                   11946:     my ($uname,$udom)=@_;
                   11947:     my $hashid="$udom:$uname";
                   11948:     &devalidate_cache_new('userres',$hashid);
                   11949: }
                   11950: 
1.624     albertel 11951: sub get_userresdata {
                   11952:     my ($uname,$udom)=@_;
                   11953:     #most student don\'t have any data set, check if there is some data
                   11954:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11955: 
                   11956:     my $hashid="$udom:$uname";
                   11957:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11958:     if (!defined($cached)) {
                   11959: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11960: 	$result=\%resourcedata;
                   11961: 	&do_cache_new('userres',$hashid,$result,600);
                   11962:     }
                   11963:     my ($tmp)=keys(%$result);
                   11964:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11965: 	return $result;
                   11966:     }
                   11967:     #error 2 occurs when the .db doesn't exist
                   11968:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11969:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11970: 	    &logthis("<font color=\"blue\">WARNING:".
                   11971: 		     " Trying to get resource data for ".
                   11972: 		     $uname." at ".$udom.": ".
                   11973: 		     $tmp."</font>");
                   11974:         }
1.624     albertel 11975:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11976: 	#&EXT_cache_set($udom,$uname);
                   11977: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11978: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11979:     }
                   11980:     return $tmp;
                   11981: }
1.879     foxr     11982: #----------------------------------------------- resdata - return resource data
                   11983: #  Purpose:
                   11984: #    Return resource data for either users or for a course.
                   11985: #  Parameters:
                   11986: #     $name      - Course/user name.
                   11987: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11988: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11989: #     $mapp      - decluttered URL of enclosing map  
                   11990: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11991: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11992: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11993: #     $courseid  - CourseID (first part of param identifier).
                   11994: #     $modifier  - Middle part of param identifier.
                   11995: #     $what      - Last part of param identifier.
1.879     foxr     11996: #     @which     - Array of names of resources desired.
                   11997: #  Returns:
                   11998: #     The value of the first reasource in @which that is found in the
                   11999: #     resource hash.
                   12000: #  Exceptional Conditions:
                   12001: #     If the $type passed in is not valid (not the string 'course' or 
                   12002: #     'user', an undefined  reference is returned.
                   12003: #     If none of the resources are found, an undef is returned
1.624     albertel 12004: sub resdata {
1.1301    raeburn  12005:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   12006:         $modifier,$what,@which)=@_;
1.624     albertel 12007:     my $result;
                   12008:     if ($type eq 'course') {
                   12009: 	$result=&get_courseresdata($name,$domain);
                   12010:     } elsif ($type eq 'user') {
                   12011: 	$result=&get_userresdata($name,$domain);
                   12012:     }
                   12013:     if (!ref($result)) { return $result; }    
1.251     albertel 12014:     foreach my $item (@which) {
1.1301    raeburn  12015:         if ($item->[1] eq 'course') {
                   12016:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12017:                 unless ($$recursed) {
1.1302    raeburn  12018:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12019:                     $$recursed = 1;
                   12020:                 }
                   12021:                 foreach my $item (@${recurseup}) {
                   12022:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12023:                     last if (defined($result->{$norecursechk}));
                   12024:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12025:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12026:                 }
                   12027:             }
                   12028:         }
                   12029:         if (defined($result->{$item->[0]})) {
1.927     albertel 12030: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12031: 	}
1.250     albertel 12032:     }
1.291     albertel 12033:     return undef;
1.200     www      12034: }
                   12035: 
1.1360    raeburn  12036: sub get_domain_lti {
                   12037:     my ($cdom,$context) = @_;
                   12038:     my ($name,%lti);
                   12039:     if ($context eq 'consumer') {
                   12040:         $name = 'ltitools';
                   12041:     } elsif ($context eq 'provider') {
                   12042:         $name = 'lti';
                   12043:     } else {
                   12044:         return %lti;
                   12045:     }
                   12046:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  12047:     if (defined($cached)) {
                   12048:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12049:             %lti = %{$result};
1.1298    raeburn  12050:         }
                   12051:     } else {
1.1360    raeburn  12052:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12053:         if (ref($domconfig{$name}) eq 'HASH') {
                   12054:             %lti = %{$domconfig{$name}};
                   12055:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   12056:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   12057:                 foreach my $id (keys(%lti)) {
                   12058:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  12059:                         foreach my $item ('key','secret') {
1.1360    raeburn  12060:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  12061:                         }
                   12062:                     }
                   12063:                 }
                   12064:             }
1.1298    raeburn  12065:         }
                   12066:         my $cachetime = 24*60*60;
1.1360    raeburn  12067:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  12068:     }
1.1360    raeburn  12069:     return %lti;
1.1298    raeburn  12070: }
                   12071: 
1.1236    raeburn  12072: sub get_numsuppfiles {
                   12073:     my ($cnum,$cdom,$ignorecache)=@_;
                   12074:     my $hashid=$cnum.':'.$cdom;
                   12075:     my ($suppcount,$cached);
                   12076:     unless ($ignorecache) {
                   12077:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   12078:     }
                   12079:     unless (defined($cached)) {
                   12080:         my $chome=&homeserver($cnum,$cdom);
                   12081:         unless ($chome eq 'no_host') {
1.1366    raeburn  12082:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  12083:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  12084:             ($suppcount,$supptools,$errors) =
                   12085:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   12086:                                                          $supptools,$errors);
1.1236    raeburn  12087:         }
                   12088:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   12089:     }
                   12090:     return $suppcount;
                   12091: }
                   12092: 
1.379     matthew  12093: #
                   12094: # EXT resource caching routines
                   12095: #
                   12096: 
1.1302    raeburn  12097: {
                   12098: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12099: #
                   12100: # The course for which we cache
                   12101: my $cachedmapkey='';
                   12102: # The cached recursive maps for this course
                   12103: my %cachedmaps=();
                   12104: # When this was last done
                   12105: my $cachedmaptime='';
                   12106: 
1.379     matthew  12107: sub clear_EXT_cache_status {
1.383     albertel 12108:     &delenv('cache.EXT.');
1.379     matthew  12109: }
                   12110: 
                   12111: sub EXT_cache_status {
                   12112:     my ($target_domain,$target_user) = @_;
1.383     albertel 12113:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12114:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12115:         # We know already the user has no data
                   12116:         return 1;
                   12117:     } else {
                   12118:         return 0;
                   12119:     }
                   12120: }
                   12121: 
                   12122: sub EXT_cache_set {
                   12123:     my ($target_domain,$target_user) = @_;
1.383     albertel 12124:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12125:     #&appenv({$cachename => time});
1.379     matthew  12126: }
                   12127: 
1.28      www      12128: # --------------------------------------------------------- Value of a Variable
1.58      www      12129: sub EXT {
1.715     albertel 12130: 
1.1228    raeburn  12131:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12132:     unless ($varname) { return ''; }
1.218     albertel 12133:     #get real user name/domain, courseid and symb
                   12134:     my $courseid;
1.359     albertel 12135:     my $publicuser;
1.427     www      12136:     if ($symbparm) {
                   12137: 	$symbparm=&get_symb_from_alias($symbparm);
                   12138:     }
1.218     albertel 12139:     if (!($uname && $udom)) {
1.790     albertel 12140:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12141:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12142:     } else {
1.620     albertel 12143: 	$courseid=$env{'request.course.id'};
1.218     albertel 12144:     }
1.48      www      12145:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12146:     my $rest;
1.320     albertel 12147:     if (defined($therest[0])) {
1.48      www      12148:        $rest=join('.',@therest);
                   12149:     } else {
                   12150:        $rest='';
                   12151:     }
1.320     albertel 12152: 
1.57      www      12153:     my $qualifierrest=$qualifier;
                   12154:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12155:     my $spacequalifierrest=$space;
                   12156:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12157:     if ($realm eq 'user') {
1.48      www      12158: # --------------------------------------------------------------- user.resource
                   12159: 	if ($space eq 'resource') {
1.651     albertel 12160: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12161: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12162: 		 &&
1.744     albertel 12163: 		 ($symbparm eq &symbread()) ) {	
                   12164: 		# if we are in the middle of processing the resource the
                   12165: 		# get the value we are planning on committing
                   12166:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12167:                     return $Apache::lonhomework::results{$qualifierrest};
                   12168:                 } else {
                   12169:                     return $Apache::lonhomework::history{$qualifierrest};
                   12170:                 }
1.335     albertel 12171: 	    } else {
1.359     albertel 12172: 		my %restored;
1.620     albertel 12173: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12174: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12175: 		} else {
                   12176: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12177: 		}
1.335     albertel 12178: 		return $restored{$qualifierrest};
                   12179: 	    }
1.48      www      12180: # ----------------------------------------------------------------- user.access
                   12181:         } elsif ($space eq 'access') {
1.218     albertel 12182: 	    # FIXME - not supporting calls for a specific user
1.48      www      12183:             return &allowed($qualifier,$rest);
                   12184: # ------------------------------------------ user.preferences, user.environment
                   12185:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12186: 	    if (($uname eq $env{'user.name'}) &&
                   12187: 		($udom eq $env{'user.domain'})) {
                   12188: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12189: 	    } else {
1.359     albertel 12190: 		my %returnhash;
                   12191: 		if (!$publicuser) {
                   12192: 		    %returnhash=&userenvironment($udom,$uname,
                   12193: 						 $qualifierrest);
                   12194: 		}
1.218     albertel 12195: 		return $returnhash{$qualifierrest};
                   12196: 	    }
1.48      www      12197: # ----------------------------------------------------------------- user.course
                   12198:         } elsif ($space eq 'course') {
1.218     albertel 12199: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12200:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12201: # ------------------------------------------------------------------- user.role
                   12202:         } elsif ($space eq 'role') {
1.218     albertel 12203: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12204:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12205:             if ($qualifier eq 'value') {
                   12206: 		return $role;
                   12207:             } elsif ($qualifier eq 'extent') {
                   12208:                 return $where;
                   12209:             }
                   12210: # ----------------------------------------------------------------- user.domain
                   12211:         } elsif ($space eq 'domain') {
1.218     albertel 12212:             return $udom;
1.48      www      12213: # ------------------------------------------------------------------- user.name
                   12214:         } elsif ($space eq 'name') {
1.218     albertel 12215:             return $uname;
1.48      www      12216: # ---------------------------------------------------- Any other user namespace
1.29      www      12217:         } else {
1.359     albertel 12218: 	    my %reply;
                   12219: 	    if (!$publicuser) {
                   12220: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12221: 	    }
                   12222: 	    return $reply{$qualifierrest};
1.48      www      12223:         }
1.236     www      12224:     } elsif ($realm eq 'query') {
                   12225: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12226:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12227: 						[$spacequalifierrest]);
1.620     albertel 12228: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12229:    } elsif ($realm eq 'request') {
1.48      www      12230: # ------------------------------------------------------------- request.browser
                   12231:         if ($space eq 'browser') {
1.1145    bisitz   12232:             return $env{'browser.'.$qualifier};
1.57      www      12233: # ------------------------------------------------------------ request.filename
                   12234:         } else {
1.620     albertel 12235:             return $env{'request.'.$spacequalifierrest};
1.29      www      12236:         }
1.28      www      12237:     } elsif ($realm eq 'course') {
1.48      www      12238: # ---------------------------------------------------------- course.description
1.620     albertel 12239:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12240:     } elsif ($realm eq 'resource') {
1.165     www      12241: 
1.620     albertel 12242: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12243: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12244: 	}
1.693     albertel 12245: 
1.1232    raeburn  12246:         if ($qualifier eq '') {
                   12247: 	    if ($space eq 'title') {
                   12248: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12249: 	        return &gettitle($symbparm);
                   12250: 	    }
1.693     albertel 12251: 	
1.1232    raeburn  12252: 	    if ($space eq 'map') {
                   12253: 	        my ($map) = &decode_symb($symbparm);
                   12254: 	        return &symbread($map);
                   12255: 	    }
                   12256:             if ($space eq 'maptitle') {
                   12257:                 my ($map) = &decode_symb($symbparm);
                   12258:                 return &gettitle($map);
                   12259:             }
                   12260: 	    if ($space eq 'filename') {
                   12261: 	        if ($symbparm) {
                   12262: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12263: 	        }
                   12264: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12265: 	    }
1.1232    raeburn  12266: 
1.1233    raeburn  12267:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12268:                 if ($space eq 'visibleparts') {
                   12269:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12270:                     my $item;
                   12271:                     if (ref($navmap)) {
                   12272:                         my $res = $navmap->getBySymb($symbparm);
                   12273:                         my $parts = $res->parts();
                   12274:                         if (ref($parts) eq 'ARRAY') {
                   12275:                             $item = join(',',@{$parts});
                   12276:                         }
                   12277:                         undef($navmap);
1.1232    raeburn  12278:                     }
1.1233    raeburn  12279:                     return $item;
1.1232    raeburn  12280:                 }
                   12281:             }
                   12282:         }
1.693     albertel 12283: 
1.1301    raeburn  12284: 	my ($section, $group, @groups, @recurseup, $recursed);
                   12285: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12286:         if (($courseid eq '') && ($cid)) {
                   12287:             $courseid = $cid;
                   12288:         }
                   12289: 	if (($symbparm && $courseid) && 
                   12290: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12291: 
1.218     albertel 12292: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12293: 
1.60      www      12294: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12295: 	    my $symbp=$symbparm;
1.1301    raeburn  12296: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12297: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12298:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12299: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12300: 	    if (($env{'user.name'} eq $uname) &&
                   12301: 		($env{'user.domain'} eq $udom)) {
                   12302: 		$section=$env{'request.course.sec'};
1.733     raeburn  12303:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12304:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12305: 	    } else {
1.539     albertel 12306: 		if (! defined($usection)) {
1.551     albertel 12307: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12308: 		} else {
                   12309: 		    $section = $usection;
                   12310: 		}
1.733     raeburn  12311:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12312: 	    }
                   12313: 
                   12314: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12315: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12316:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12317: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12318: 
1.593     albertel 12319: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12320: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12321:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12322: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12323: 
1.60      www      12324: # ----------------------------------------------------------- first, check user
1.624     albertel 12325: 
1.1301    raeburn  12326: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12327:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12328: 				       ([$courselevelr,'resource'],
                   12329: 					[$courselevelm,'map'     ],
1.1301    raeburn  12330:                                         [$courseleveli,'map'     ],
1.927     albertel 12331: 					[$courselevel, 'course'  ]));
1.931     albertel 12332: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12333: 
1.594     albertel 12334: # ------------------------------------------------ second, check some of course
1.684     raeburn  12335:             my $coursereply;
1.691     raeburn  12336:             if (@groups > 0) {
                   12337:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12338:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12339:                                        $mapp,\$recursed,\@recurseup);
                   12340:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12341:             }
1.96      www      12342: 
1.684     raeburn  12343: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12344: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12345: 				  'course',$mapp,\$recursed,\@recurseup,
                   12346:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12347: 				  ([$seclevelr,   'resource'],
                   12348: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12349:                                    [$secleveli,   'map'     ],
1.927     albertel 12350: 				   [$seclevel,    'course'  ],
                   12351: 				   [$courselevelr,'resource']));
                   12352: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12353: 
1.60      www      12354: # ------------------------------------------------------ third, check map parms
1.218     albertel 12355: 	    my %parmhash=();
                   12356: 	    my $thisparm='';
                   12357: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12358: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12359: 		    &GDBM_READER(),0640)) {
1.218     albertel 12360: 		$thisparm=$parmhash{$symbparm};
                   12361: 		untie(%parmhash);
                   12362: 	    }
1.927     albertel 12363: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12364: 	}
1.594     albertel 12365: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12366:  
                   12367:         my $what = $spacequalifierrest;
                   12368: 	$what=~s/\./\_/;
1.282     albertel 12369: 	my $filename;
                   12370: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12371: 	if ($symbparm) {
1.409     www      12372: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12373: 	} else {
1.620     albertel 12374: 	    $filename=$env{'request.filename'};
1.282     albertel 12375: 	}
1.1362    raeburn  12376:         my $toolsymb;
                   12377:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12378:             $toolsymb = $symbparm;
                   12379:         }
                   12380: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12381: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12382: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12383: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12384: 
1.1301    raeburn  12385: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12386: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12387: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12388: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12389: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12390: 				     'course',$mapp,\$recursed,\@recurseup,
                   12391:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12392: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12393:                                       [$courseleveli,'map'   ],
1.927     albertel 12394: 				      [$courselevel, 'course']));
                   12395: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12396: 	}
1.145     www      12397: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12398: 	unless ($space eq '0') {
1.336     albertel 12399: 	    my @parts=split(/_/,$space);
                   12400: 	    my $id=pop(@parts);
                   12401: 	    my $part=join('_',@parts);
                   12402: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12403: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12404: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12405: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12406: 	}
1.395     albertel 12407: 	if ($recurse) { return undef; }
1.1362    raeburn  12408: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12409: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12410: # ---------------------------------------------------- Any other user namespace
                   12411:     } elsif ($realm eq 'environment') {
                   12412: # ----------------------------------------------------------------- environment
1.620     albertel 12413: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12414: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12415: 	} else {
1.770     albertel 12416: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12417: 		return '';
                   12418: 	    }
1.219     albertel 12419: 	    my %returnhash=&userenvironment($udom,$uname,
                   12420: 					    $spacequalifierrest);
                   12421: 	    return $returnhash{$spacequalifierrest};
                   12422: 	}
1.28      www      12423:     } elsif ($realm eq 'system') {
1.48      www      12424: # ----------------------------------------------------------------- system.time
                   12425: 	if ($space eq 'time') {
                   12426: 	    return time;
                   12427:         }
1.696     albertel 12428:     } elsif ($realm eq 'server') {
                   12429: # ----------------------------------------------------------------- system.time
                   12430: 	if ($space eq 'name') {
                   12431: 	    return $ENV{'SERVER_NAME'};
                   12432:         }
1.1415    raeburn  12433:     } elsif ($realm eq 'client') {
                   12434:         if ($space eq 'remote_addr') {
1.1441    raeburn  12435:             return &get_requestor_ip();
1.1415    raeburn  12436:         }
1.28      www      12437:     }
1.48      www      12438:     return '';
1.61      www      12439: }
                   12440: 
1.927     albertel 12441: sub get_reply {
                   12442:     my ($reply_value) = @_;
1.940     raeburn  12443:     if (ref($reply_value) eq 'ARRAY') {
                   12444:         if (wantarray) {
                   12445: 	    return @$reply_value;
                   12446:         }
                   12447:         return $reply_value->[0];
                   12448:     } else {
                   12449:         return $reply_value;
1.927     albertel 12450:     }
                   12451: }
                   12452: 
1.691     raeburn  12453: sub check_group_parms {
1.1301    raeburn  12454:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12455:         $recursed,$recurseupref) = @_;
                   12456:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12457:                   [$what,'course']);
                   12458:     my $coursereply;
1.691     raeburn  12459:     foreach my $group (@{$groups}) {
1.1301    raeburn  12460:         my @groupitems = ();
1.691     raeburn  12461:         foreach my $level (@levels) {
1.927     albertel 12462:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12463:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12464:         }
1.1301    raeburn  12465:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12466:                                    $env{'course.'.$courseid.'.domain'},
                   12467:                                    'course',$mapp,$recursed,$recurseupref,
                   12468:                                    $courseid,'.['.$group.'].',$what,
                   12469:                                    @groupitems);
                   12470:         last if (defined($coursereply));
1.691     raeburn  12471:     }
                   12472:     return $coursereply;
                   12473: }
                   12474: 
1.1301    raeburn  12475: sub get_map_hierarchy {
1.1302    raeburn  12476:     my ($mapname,$courseid) = @_;
                   12477:     my @recurseup = ();
1.1301    raeburn  12478:     if ($mapname) {
1.1302    raeburn  12479:         if (($cachedmapkey eq $courseid) &&
                   12480:             (abs($cachedmaptime-time)<5)) {
                   12481:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12482:                 return @{$cachedmaps{$mapname}};
                   12483:             }
                   12484:         }
1.1301    raeburn  12485:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12486:         if (ref($navmap)) {
                   12487:             @recurseup = $navmap->recurseup_maps($mapname);
                   12488:             undef($navmap);
1.1302    raeburn  12489:             $cachedmaps{$mapname} = \@recurseup;
                   12490:             $cachedmaptime=time;
                   12491:             $cachedmapkey=$courseid;
1.1301    raeburn  12492:         }
                   12493:     }
                   12494:     return @recurseup;
                   12495: }
                   12496: 
1.1302    raeburn  12497: }
                   12498: 
1.691     raeburn  12499: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12500:     my ($courseid,@groups) = @_;
                   12501:     @groups = sort(@groups);
1.691     raeburn  12502:     return @groups;
                   12503: }
                   12504: 
1.395     albertel 12505: sub packages_tab_default {
1.1362    raeburn  12506:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12507:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12508: 
                   12509:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12510:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12511: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12512: 	if ($pack_type eq 'default') {
                   12513: 	    $do_default=1;
                   12514: 	} elsif ($pack_type eq 'extension') {
                   12515: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12516: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12517: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12518: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12519: 	}
                   12520:     }
                   12521:     # first look for a package that matches the requested part id
                   12522:     foreach my $package (@specifics) {
                   12523: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12524: 	next if ($pack_part ne $part);
                   12525: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12526: 	    return $packagetab{"$pack_type&$name&default"};
                   12527: 	}
                   12528:     }
                   12529:     # look for any possible matching non extension_ package
                   12530:     foreach my $package (@specifics) {
                   12531: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12532: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12533: 	    return $packagetab{"$pack_type&$name&default"};
                   12534: 	}
1.585     albertel 12535: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12536: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12537: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12538: 	}
                   12539:     }
1.738     albertel 12540:     # look for any posible extension_ match
                   12541:     foreach my $package (@extension) {
                   12542: 	my ($package,$pack_type)=@{$package};
                   12543: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12544: 	    return $packagetab{"$pack_type&$name&default"};
                   12545: 	}
                   12546: 	if (defined($packagetab{$package."&$name&default"})) {
                   12547: 	    return $packagetab{$package."&$name&default"};
                   12548: 	}
                   12549:     }
                   12550:     # look for a global default setting
                   12551:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12552: 	return $packagetab{"default&$name&default"};
                   12553:     }
1.395     albertel 12554:     return undef;
                   12555: }
                   12556: 
1.334     albertel 12557: sub add_prefix_and_part {
                   12558:     my ($prefix,$part)=@_;
                   12559:     my $keyroot;
                   12560:     if (defined($prefix) && $prefix !~ /^__/) {
                   12561: 	# prefix that has a part already
                   12562: 	$keyroot=$prefix;
                   12563:     } elsif (defined($prefix)) {
                   12564: 	# prefix that is missing a part
                   12565: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12566:     } else {
                   12567: 	# no prefix at all
                   12568: 	if (defined($part)) { $keyroot='_'.$part; }
                   12569:     }
                   12570:     return $keyroot;
                   12571: }
                   12572: 
1.71      www      12573: # ---------------------------------------------------------------- Get metadata
                   12574: 
1.599     albertel 12575: my %metaentry;
1.1070    www      12576: my %importedpartids;
1.1369    raeburn  12577: my %importedrespids;
1.71      www      12578: sub metadata {
1.1362    raeburn  12579:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12580:     $uri=&declutter($uri);
1.288     albertel 12581:     # if it is a non metadata possible uri return quickly
1.529     albertel 12582:     if (($uri eq '') || 
                   12583: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12584: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12585:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12586: 	return undef;
                   12587:     }
1.1261    raeburn  12588:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12589: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12590: 	return undef;
1.288     albertel 12591:     }
1.73      www      12592:     my $filename=$uri;
                   12593:     $uri=~s/\.meta$//;
1.172     www      12594: #
                   12595: # Is the metadata already cached?
1.177     www      12596: # Look at timestamp of caching
1.172     www      12597: # Everything is cached by the main uri, libraries are never directly cached
                   12598: #
1.428     albertel 12599:     if (!defined($liburi)) {
1.599     albertel 12600: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12601: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12602:     }
1.1362    raeburn  12603: 
                   12604: #
                   12605: # If the uri is for an external tool the file from
                   12606: # which metadata should be retrieved depends on whether
                   12607: # the tool had been configured to be gradable (set in the Course
                   12608: # Editor or Resource Editor).
                   12609: #
                   12610: # If a valid symb has been included as the third arg in the call
                   12611: # to &metadata() that can be used to retrieve the value of
                   12612: # parameter_0_gradable set for the resource, and included in the
                   12613: # uploaded map containing the tool. The value is retrieved via
                   12614: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12615: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12616: # is retrieved via &get().
                   12617: #
                   12618: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12619: # hiddenresource and encrypturl (during course initialization)
                   12620: # the map-level parameter for resource.0.gradable included in the 
                   12621: # uploaded map containing the tool will not yet have been stored
                   12622: # in the user_course_parms.db file for the user's session, so in 
                   12623: # this case fall back to retrieving gradable status from the
                   12624: # exttool_$marker.db file.
1.1362    raeburn  12625: #
                   12626: # In order to avoid an infinite loop, &metadata() will return
                   12627: # before a call to &EXT(), if the uri is for an external tool
                   12628: # and the $what for which metadata is being requested is
                   12629: # parameter_0_gradable or 0_gradable.
                   12630: #
                   12631: 
                   12632:     if ($uri =~ /ext\.tool$/) {
                   12633:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12634:             return;
                   12635:         } else {
                   12636:             my ($checked,$use_passback);
                   12637:             if ($toolsymb ne '') {
                   12638:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12639:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12640:                     $checked = 1;
                   12641:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12642:                         $use_passback = 1;
                   12643:                     }
                   12644:                 }
                   12645:             }
                   12646:             unless ($checked) {
                   12647:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12648:                 $marker=~s/\D//g;
1.1363    raeburn  12649:                 if ($marker) {
1.1362    raeburn  12650:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12651:                     $use_passback = $toolsettings{'gradable'};
                   12652:                 }
                   12653:             }
                   12654:             if ($use_passback) {
                   12655:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12656:             } else {
                   12657:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12658:             }
                   12659:         }
                   12660:     }
                   12661: 
1.428     albertel 12662:     {
1.1069    www      12663: # Imported parts would go here
1.1369    raeburn  12664:         my @origfiletagids=();
1.1069    www      12665:         my $importedparts=0;
1.1369    raeburn  12666: 
                   12667: # Imported responseids would go here
                   12668:         my $importedresponses=0;
1.172     www      12669: #
                   12670: # Is this a recursive call for a library?
                   12671: #
1.599     albertel 12672: #	if (! exists($metacache{$uri})) {
                   12673: #	    $metacache{$uri}={};
                   12674: #	}
1.924     albertel 12675: 	my $cachetime = 60*60;
1.171     www      12676:         if ($liburi) {
                   12677: 	    $liburi=&declutter($liburi);
                   12678:             $filename=$liburi;
1.401     bowersj2 12679:         } else {
1.599     albertel 12680: 	    &devalidate_cache_new('meta',$uri);
                   12681: 	    undef(%metaentry);
1.401     bowersj2 12682: 	}
1.140     www      12683:         my %metathesekeys=();
1.73      www      12684:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12685: 	my $metastring;
1.1140    www      12686: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12687: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12688: 	    $metastring = 
1.929     albertel 12689: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12690: 					  ('grade_target' => 'meta'));
                   12691: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12692: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12693:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12694: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12695: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12696: 	    $metastring=&getfile($file);
1.489     albertel 12697: 	}
1.208     albertel 12698:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12699:         my $token;
1.140     www      12700:         undef %metathesekeys;
1.71      www      12701:         while ($token=$parser->get_token) {
1.339     albertel 12702: 	    if ($token->[0] eq 'S') {
                   12703: 		if (defined($token->[2]->{'package'})) {
1.172     www      12704: #
                   12705: # This is a package - get package info
                   12706: #
1.339     albertel 12707: 		    my $package=$token->[2]->{'package'};
                   12708: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12709: 		    if (defined($token->[2]->{'id'})) { 
                   12710: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12711: 		    }
1.599     albertel 12712: 		    if ($metaentry{':packages'}) {
                   12713: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12714: 		    } else {
1.599     albertel 12715: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12716: 		    }
1.736     albertel 12717: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12718: 			my $part=$keyroot;
                   12719: 			$part=~s/^\_//;
1.736     albertel 12720: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12721: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12722: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12723: 			    # ignore package.tab specified default values
                   12724:                             # here &package_tab_default() will fetch those
                   12725: 			    if ($subp eq 'default') { next; }
1.736     albertel 12726: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12727: 			    my $unikey;
                   12728: 			    if ($pack =~ /_0$/) {
                   12729: 				$unikey='parameter_0_'.$name;
                   12730: 				$part=0;
                   12731: 			    } else {
                   12732: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12733: 			    }
1.339     albertel 12734: 			    if ($subp eq 'display') {
                   12735: 				$value.=' [Part: '.$part.']';
                   12736: 			    }
1.599     albertel 12737: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12738: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12739: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12740: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12741: 			    }
1.599     albertel 12742: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12743: 				$metaentry{':'.$unikey}=
                   12744: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12745: 			    }
1.339     albertel 12746: 			}
                   12747: 		    }
                   12748: 		} else {
1.172     www      12749: #
                   12750: # This is not a package - some other kind of start tag
1.339     albertel 12751: #
                   12752: 		    my $entry=$token->[1];
1.1068    www      12753: 		    my $unikey='';
1.175     www      12754: 
1.339     albertel 12755: 		    if ($entry eq 'import') {
1.175     www      12756: #
                   12757: # Importing a library here
1.339     albertel 12758: #
1.1067    www      12759:                         my $location=$parser->get_text('/import');
                   12760:                         my $dir=$filename;
                   12761:                         $dir=~s|[^/]*$||;
                   12762:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12763: 
                   12764:                         my $importid=$token->[2]->{'id'};
1.1068    www      12765:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12766: #
                   12767: # Check metadata for imported file to
                   12768: # see if it contained response items
                   12769: #
1.1372    raeburn  12770:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12771:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12772:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12773:                                                            $depthcount+1));
                   12774:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12775:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12776:                                                              undef,$depthcount+1);
                   12777:                             if ($libresponseorder ne '') {
                   12778:                                 if ($#origfiletagids<0) {
                   12779:                                     undef(%importedrespids);
                   12780:                                     undef(%importedpartids);
                   12781:                                 }
1.1373    raeburn  12782:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12783:                                 if (@respids) {
                   12784:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12785:                                 }
                   12786:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12787:                                     $importedresponses = 1;
1.1369    raeburn  12788: # We need to get the original file and the imported file to get the response order correct
                   12789: # Load and inspect original file
1.1372    raeburn  12790:                                     if ($#origfiletagids<0) {
                   12791:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12792:                                         $origfile=&getfile($origfilelocation);
                   12793:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12794:                                     }
1.1369    raeburn  12795:                                 }
                   12796:                             }
                   12797:                         }
1.1370    raeburn  12798: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12799: # hash populated for imported library file
                   12800:                         %metaentry = %currmetaentry;
                   12801:                         undef(%currmetaentry);
1.1374    raeburn  12802:                         if ($importmode eq 'part') {
1.1068    www      12803: # Import as part(s)
1.1069    www      12804:                            $importedparts=1;
                   12805: # We need to get the original file and the imported file to get the part order correct
                   12806: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12807: # Load and inspect original file if we didn't do that already
                   12808:                            if ($#origfiletagids<0) {
                   12809:                                undef(%importedrespids);
                   12810:                                undef(%importedpartids);
                   12811:                                if ($origfile eq '') {
                   12812:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12813:                                    $origfile=&getfile($origfilelocation);
                   12814:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12815:                                }
1.1070    www      12816:                            }
1.1372    raeburn  12817:                            my @impfilepartids;
                   12818: # If <partorder> tag is included in metadata for the imported file
                   12819: # get the parts in the imported file from that.
                   12820:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12821:                                %currmetaentry = %metaentry;
                   12822:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12823:                                                             $depthcount+1);
                   12824:                                %metaentry = %currmetaentry;
                   12825:                                undef(%currmetaentry);
                   12826:                                if ($libpartorder ne '') {
                   12827:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12828:                                }
                   12829:                            } else {
                   12830: # If no <partorder> tag available, load and inspect imported file
                   12831:                                my $impfile=&getfile($location);
                   12832:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12833:                            }
1.1069    www      12834:                            if ($#impfilepartids>=0) {
                   12835: # This problem had parts
1.1070    www      12836:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12837:                            } else {
                   12838: # Importing by turning a single problem into a problem part
                   12839: # It gets the import-tags ID as part-ID
                   12840:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12841:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12842:                            }
1.1068    www      12843:                         } else {
1.1374    raeburn  12844: # Import as problem or as normal import
                   12845:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12846:                             unless ($importmode eq 'problem') {
1.1068    www      12847: # Normal import
1.1374    raeburn  12848:                                 if (defined($token->[2]->{'id'})) {
                   12849:                                     $unikey.='_'.$token->[2]->{'id'};
                   12850:                                 }
                   12851:                             }
                   12852: # Check metadata for imported file to
                   12853: # see if it contained parts
                   12854:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12855:                                 %currmetaentry = %metaentry;
                   12856:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12857:                                                              $depthcount+1);
                   12858:                                 %metaentry = %currmetaentry;
                   12859:                                 undef(%currmetaentry);
                   12860:                                 if ($libpartorder ne '') {
                   12861:                                     $importedparts = 1;
                   12862:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12863:                                 }
                   12864:                             }
1.1067    www      12865:                         }
1.339     albertel 12866: 			if ($depthcount<20) {
1.736     albertel 12867: 			    my $metadata = 
1.1362    raeburn  12868: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12869: 					  $depthcount+1);
                   12870: 			    foreach my $meta (split(',',$metadata)) {
                   12871: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12872: 				$metathesekeys{$meta}=1;
1.339     albertel 12873: 			    }
1.1068    www      12874:                         }
1.1067    www      12875: 		    } else {
                   12876: #
                   12877: # Not importing, some other kind of non-package, non-library start tag
                   12878: # 
                   12879:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12880:                         if (defined($token->[2]->{'id'})) {
                   12881:                             $unikey.='_'.$token->[2]->{'id'};
                   12882:                         }
1.339     albertel 12883: 			if (defined($token->[2]->{'name'})) { 
                   12884: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12885: 			}
                   12886: 			$metathesekeys{$unikey}=1;
1.736     albertel 12887: 			foreach my $param (@{$token->[3]}) {
                   12888: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12889: 				$token->[2]->{$param};
1.339     albertel 12890: 			}
                   12891: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12892: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12893: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12894: 		 # only ws inside the tag, and not in default, so use default
                   12895: 		 # as value
1.599     albertel 12896: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12897: 			} elsif ( $internaltext =~ /\S/ ) {
                   12898: 		  # something interesting inside the tag
                   12899: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12900: 			} else {
1.908     albertel 12901: 		  # no interesting values, don't set a default
1.339     albertel 12902: 			}
1.172     www      12903: # end of not-a-package not-a-library import
1.339     albertel 12904: 		    }
1.172     www      12905: # end of not-a-package start tag
1.339     albertel 12906: 		}
1.172     www      12907: # the next is the end of "start tag"
1.339     albertel 12908: 	    }
                   12909: 	}
1.483     albertel 12910: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12911: 	$extension = lc($extension);
                   12912: 	if ($extension eq 'htm') { $extension='html'; }
                   12913: 
1.737     albertel 12914: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12915: 	    #no specific packages #how's our extension
                   12916: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12917: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12918: 					 \%metathesekeys);
                   12919: 	}
1.883     albertel 12920: 
                   12921: 	if (!exists($metaentry{':packages'})
                   12922: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12923: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12924: 		#no specific packages well let's get default then
                   12925: 		if ($key!~/^default&/) { next; }
1.488     albertel 12926: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12927: 					     \%metathesekeys);
                   12928: 	    }
                   12929: 	}
1.338     www      12930: # are there custom rights to evaluate
1.599     albertel 12931: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12932: 
1.338     www      12933:     #
                   12934:     # Importing a rights file here
1.339     albertel 12935:     #
                   12936: 	    unless ($depthcount) {
1.599     albertel 12937: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12938: 		my $dir=$filename;
                   12939: 		$dir=~s|[^/]*$||;
                   12940: 		$location=&filelocation($dir,$location);
1.736     albertel 12941: 		my $rights_metadata =
1.1362    raeburn  12942: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12943: 			      $depthcount+1);
                   12944: 		foreach my $rights (split(',',$rights_metadata)) {
                   12945: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12946: 		    $metathesekeys{$rights}=1;
1.339     albertel 12947: 		}
                   12948: 	    }
                   12949: 	}
1.737     albertel 12950: 	# uniqifiy package listing
                   12951: 	my %seen;
                   12952: 	my @uniq_packages =
                   12953: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12954: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12955: 
1.1369    raeburn  12956:         if (($importedresponses) || ($importedparts)) {
                   12957:             if ($importedparts) {
1.1070    www      12958: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12959:                 $metaentry{':partorder'}='';
                   12960:                 $metathesekeys{'partorder'}=1;
                   12961:             }
                   12962:             if ($importedresponses) {
                   12963: # We had imported responses and need to rebuil responseorder
                   12964:                 $metaentry{':responseorder'}='';
                   12965:                 $metathesekeys{'responseorder'}=1;
                   12966:             }
                   12967:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12968:                 my $origid = $origfiletagids[$index+1];
                   12969:                 if ($origfiletagids[$index] eq 'part') {
                   12970: # Original part, part of the problem
                   12971:                     if ($importedparts) {
                   12972:                         $metaentry{':partorder'}.=','.$origid;
                   12973:                     }
                   12974:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12975:                     if ($importedparts) {
                   12976: # We have imported parts at this position
1.1373    raeburn  12977:                         if ($importedpartids{$origid} ne '') {
                   12978:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12979:                         }
1.1369    raeburn  12980:                     }
                   12981:                     if ($importedresponses) {
                   12982: # We have imported responses at this position
1.1373    raeburn  12983:                         if ($importedrespids{$origid} ne '') {
                   12984:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12985:                         }
                   12986:                     }
                   12987:                 } else {
                   12988: # Original response item, part of the problem
                   12989:                     if ($importedresponses) {
                   12990:                         $metaentry{':responseorder'}.=','.$origid;
                   12991:                     }
                   12992:                 }
                   12993:             }
                   12994:             if ($importedparts) {
                   12995:                 $metaentry{':partorder'}=~s/^\,//;
                   12996:             }
                   12997:             if ($importedresponses) {
                   12998:                 $metaentry{':responseorder'}=~s/^\,//;
                   12999:             }
1.1070    www      13000:         }
1.737     albertel 13001: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13002: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  13003: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  13004:         unless ($liburi) {
                   13005: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   13006:         }
1.177     www      13007: # this is the end of "was not already recently cached
1.71      www      13008:     }
1.599     albertel 13009:     return $metaentry{':'.$what};
1.261     albertel 13010: }
                   13011: 
1.488     albertel 13012: sub metadata_create_package_def {
1.483     albertel 13013:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13014:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13015:     if ($subp eq 'default') { next; }
                   13016:     
1.599     albertel 13017:     if (defined($metaentry{':packages'})) {
                   13018: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13019:     } else {
1.599     albertel 13020: 	$metaentry{':packages'}=$package;
1.483     albertel 13021:     }
                   13022:     my $value=$packagetab{$key};
                   13023:     my $unikey;
                   13024:     $unikey='parameter_0_'.$name;
1.599     albertel 13025:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13026:     $$metathesekeys{$unikey}=1;
1.599     albertel 13027:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13028: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13029:     }
1.599     albertel 13030:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13031: 	$metaentry{':'.$unikey}=
                   13032: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13033:     }
                   13034: }
                   13035: 
1.261     albertel 13036: sub metadata_generate_part0 {
                   13037:     my ($metadata,$metacache,$uri) = @_;
                   13038:     my %allnames;
1.737     albertel 13039:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13040: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13041: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13042: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13043: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13044: 	    $allnames{$name}=$part;
                   13045: 	  }
                   13046: 	}
                   13047:     }
                   13048:     foreach my $name (keys(%allnames)) {
                   13049:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13050:       my $key=":parameter_0_$name";
1.261     albertel 13051:       $$metacache{"$key.part"}='0';
                   13052:       $$metacache{"$key.name"}=$name;
1.428     albertel 13053:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13054: 					   $allnames{$name}.'_'.$name.
                   13055: 					   '.type'};
1.428     albertel 13056:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13057: 			     '.display'};
1.644     www      13058:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13059:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13060:       $$metacache{"$key.display"}=$olddis;
                   13061:     }
1.71      www      13062: }
                   13063: 
1.764     albertel 13064: # ------------------------------------------------------ Devalidate title cache
                   13065: 
                   13066: sub devalidate_title_cache {
                   13067:     my ($url)=@_;
                   13068:     if (!$env{'request.course.id'}) { return; }
                   13069:     my $symb=&symbread($url);
                   13070:     if (!$symb) { return; }
                   13071:     my $key=$env{'request.course.id'}."\0".$symb;
                   13072:     &devalidate_cache_new('title',$key);
                   13073: }
                   13074: 
1.1014    droeschl 13075: # ------------------------------------------------- Get the title of a course
                   13076: 
                   13077: sub current_course_title {
                   13078:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13079: }
1.301     www      13080: # ------------------------------------------------- Get the title of a resource
                   13081: 
                   13082: sub gettitle {
                   13083:     my $urlsymb=shift;
                   13084:     my $symb=&symbread($urlsymb);
1.534     albertel 13085:     if ($symb) {
1.620     albertel 13086: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13087: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13088: 	if (defined($cached)) { 
                   13089: 	    return $result;
                   13090: 	}
1.534     albertel 13091: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13092: 	my $title='';
1.907     albertel 13093: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13094: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13095: 	} else {
                   13096: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13097: 		    &GDBM_READER(),0640)) {
                   13098: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13099: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13100: 		untie(%bighash);
                   13101: 	    }
1.534     albertel 13102: 	}
                   13103: 	$title=~s/\&colon\;/\:/gs;
                   13104: 	if ($title) {
1.1159    www      13105: # Remember both $symb and $title for dynamic metadata
                   13106:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13107:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13108: # Cache this title and then return it
1.599     albertel 13109: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13110: 	}
                   13111: 	$urlsymb=$url;
                   13112:     }
                   13113:     my $title=&metadata($urlsymb,'title');
                   13114:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13115:     return $title;
1.301     www      13116: }
1.613     albertel 13117: 
1.614     albertel 13118: sub get_slot {
                   13119:     my ($which,$cnum,$cdom)=@_;
                   13120:     if (!$cnum || !$cdom) {
1.790     albertel 13121: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13122: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13123: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13124:     }
1.703     albertel 13125:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13126:     my %slotinfo;
                   13127:     if (exists($remembered{$key})) {
                   13128: 	$slotinfo{$which} = $remembered{$key};
                   13129:     } else {
                   13130: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13131: 	&Apache::lonhomework::showhash(%slotinfo);
                   13132: 	my ($tmp)=keys(%slotinfo);
                   13133: 	if ($tmp=~/^error:/) { return (); }
                   13134: 	$remembered{$key} = $slotinfo{$which};
                   13135:     }
1.616     albertel 13136:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13137: 	return %{$slotinfo{$which}};
                   13138:     }
                   13139:     return $slotinfo{$which};
1.614     albertel 13140: }
1.1150    raeburn  13141: 
                   13142: sub get_reservable_slots {
                   13143:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13144:     my $now = time;
                   13145:     my $reservable_info;
                   13146:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13147:     if (exists($remembered{$key})) {
                   13148:         $reservable_info = $remembered{$key};
                   13149:     } else {
                   13150:         my %resv;
                   13151:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13152:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13153:         $reservable_info = \%resv;
                   13154:         $remembered{$key} = $reservable_info;
                   13155:     }
                   13156:     return $reservable_info;
                   13157: }
                   13158: 
                   13159: sub get_course_slots {
                   13160:     my ($cnum,$cdom) = @_;
                   13161:     my $hashid=$cnum.':'.$cdom;
                   13162:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13163:     if (defined($cached)) {
                   13164:         if (ref($result) eq 'HASH') {
                   13165:             return %{$result};
                   13166:         }
                   13167:     } else {
                   13168:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13169:         my ($tmp) = keys(%slots);
                   13170:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13171:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13172:             return %slots;
                   13173:         }
                   13174:     }
                   13175:     return;
                   13176: }
                   13177: 
                   13178: sub devalidate_slots_cache {
                   13179:     my ($cnum,$cdom)=@_;
                   13180:     my $hashid=$cnum.':'.$cdom;
                   13181:     &devalidate_cache_new('allslots',$hashid);
                   13182: }
                   13183: 
1.1181    raeburn  13184: sub get_coursechange {
                   13185:     my ($cdom,$cnum) = @_;
                   13186:     if ($cdom eq '' || $cnum eq '') {
                   13187:         return unless ($env{'request.course.id'});
                   13188:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13189:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13190:     }
                   13191:     my $hashid=$cdom.'_'.$cnum;
                   13192:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13193:     if ((defined($cached)) && ($change ne '')) {
                   13194:         return $change;
                   13195:     } else {
                   13196:         my %crshash;
                   13197:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13198:         if ($crshash{'internal.contentchange'} eq '') {
                   13199:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13200:             if ($change eq '') {
                   13201:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13202:                 $change = $crshash{'internal.created'};
                   13203:             }
                   13204:         } else {
                   13205:             $change = $crshash{'internal.contentchange'};
                   13206:         }
                   13207:         my $cachetime = 600;
                   13208:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13209:     }
                   13210:     return $change;
                   13211: }
                   13212: 
                   13213: sub devalidate_coursechange_cache {
                   13214:     my ($cnum,$cdom)=@_;
                   13215:     my $hashid=$cnum.':'.$cdom;
                   13216:     &devalidate_cache_new('crschange',$hashid);
                   13217: }
                   13218: 
1.31      www      13219: # ------------------------------------------------- Update symbolic store links
                   13220: 
                   13221: sub symblist {
                   13222:     my ($mapname,%newhash)=@_;
1.438     www      13223:     $mapname=&deversion(&declutter($mapname));
1.31      www      13224:     my %hash;
1.620     albertel 13225:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13226:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13227:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13228: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13229: 		next if ($url eq 'last_known'
                   13230: 			 && $env{'form.no_update_last_known'});
                   13231: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13232: 						    $newhash{$url}->[1],
                   13233: 						    $newhash{$url}->[0]);
1.191     harris41 13234:             }
1.31      www      13235:             if (untie(%hash)) {
                   13236: 		return 'ok';
                   13237:             }
                   13238:         }
                   13239:     }
                   13240:     return 'error';
1.212     www      13241: }
                   13242: 
                   13243: # --------------------------------------------------------------- Verify a symb
                   13244: 
                   13245: sub symbverify {
1.1190    raeburn  13246:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13247:     my $thisfn=$thisurl;
1.439     www      13248:     $thisfn=&declutter($thisfn);
1.215     www      13249: # direct jump to resource in page or to a sequence - will construct own symbs
                   13250:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13251: # check URL part
1.409     www      13252:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13253: 
1.431     www      13254:     unless ($url eq $thisfn) { return 0; }
1.213     www      13255: 
1.216     www      13256:     $symb=&symbclean($symb);
1.510     www      13257:     $thisurl=&deversion($thisurl);
1.439     www      13258:     $thisfn=&deversion($thisfn);
1.213     www      13259: 
                   13260:     my %bighash;
                   13261:     my $okay=0;
1.431     www      13262: 
1.620     albertel 13263:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13264:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13265:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13266:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13267:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13268:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13269:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13270:             }
                   13271:         }
                   13272:         my $ids;
1.1419    raeburn  13273:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13274:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  13275:         } else {
                   13276:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13277:         }
1.1102    raeburn  13278:         unless ($ids) {
                   13279:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13280:             $ids=$bighash{$idkey};
1.216     www      13281:         }
                   13282:         if ($ids) {
                   13283: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13284:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13285:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13286:             }
1.800     albertel 13287: 	    foreach my $id (split(/\,/,$ids)) {
                   13288: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13289:                if (
                   13290:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13291:    eq $symb) {
                   13292:                    if (ref($encstate)) {
                   13293:                        $$encstate = $bighash{'encrypted_'.$id};
                   13294:                    }
1.620     albertel 13295: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13296: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13297:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13298: 		       $okay=1;
1.1202    raeburn  13299:                        last;
1.582     albertel 13300: 		   }
                   13301: 	       }
1.216     www      13302: 	   }
                   13303:         }
1.213     www      13304: 	untie(%bighash);
                   13305:     }
                   13306:     return $okay;
1.31      www      13307: }
                   13308: 
1.210     www      13309: # --------------------------------------------------------------- Clean-up symb
                   13310: 
                   13311: sub symbclean {
                   13312:     my $symb=shift;
1.568     albertel 13313:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13314: # remove version from map
                   13315:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13316: 
1.210     www      13317: # remove version from URL
                   13318:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13319: 
1.507     www      13320: # remove wrapper
                   13321: 
1.510     www      13322:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13323:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13324:     return $symb;
1.409     www      13325: }
                   13326: 
                   13327: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13328: 
                   13329: sub encode_symb {
                   13330:     my ($map,$resid,$url)=@_;
                   13331:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13332: }
1.409     www      13333: 
                   13334: sub decode_symb {
1.568     albertel 13335:     my $symb=shift;
                   13336:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13337:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13338:     return (&fixversion($map),$resid,&fixversion($url));
                   13339: }
                   13340: 
                   13341: sub fixversion {
                   13342:     my $fn=shift;
1.609     banghart 13343:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13344:     my %bighash;
                   13345:     my $uri=&clutter($fn);
1.620     albertel 13346:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13347: # is this cached?
1.599     albertel 13348:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13349:     if (defined($cached)) { return $result; }
                   13350: # unfortunately not cached, or expired
1.620     albertel 13351:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13352: 	    &GDBM_READER(),0640)) {
                   13353:  	if ($bighash{'version_'.$uri}) {
                   13354:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13355:  	    unless (($version eq 'mostrecent') || 
                   13356: 		    ($version==&getversion($uri))) {
1.440     www      13357:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13358:  	    }
                   13359:  	}
                   13360:  	untie %bighash;
1.413     www      13361:     }
1.599     albertel 13362:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13363: }
                   13364: 
                   13365: sub deversion {
                   13366:     my $url=shift;
                   13367:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13368:     return $url;
1.210     www      13369: }
                   13370: 
1.31      www      13371: # ------------------------------------------------------ Return symb list entry
                   13372: 
                   13373: sub symbread {
1.1424    raeburn  13374:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  13375:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  13376:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  13377:     if (defined($env{$cache_str})) {
1.1424    raeburn  13378:         unless (ref($possibles) eq 'HASH') {
                   13379:             if ($ignorecachednull) {
                   13380:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13381:             } else {
                   13382:                 return $env{$cache_str};
                   13383:             }
1.1282    raeburn  13384:         }
                   13385:     }
1.242     www      13386: # no filename provided? try from environment
1.1265    raeburn  13387:     unless ($thisfn) {
1.620     albertel 13388:         if ($env{'request.symb'}) {
1.1427    raeburn  13389:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13390: 	}
1.620     albertel 13391: 	$thisfn=$env{'request.filename'};
1.44      www      13392:     }
1.569     albertel 13393:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13394: # is that filename actually a symb? Verify, clean, and return
                   13395:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13396: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  13397: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13398: 	}
1.242     www      13399:     }
1.44      www      13400:     $thisfn=declutter($thisfn);
1.31      www      13401:     my %hash;
1.37      www      13402:     my %bighash;
                   13403:     my $syval='';
1.620     albertel 13404:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13405:         my $targetfn = $thisfn;
1.609     banghart 13406:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13407:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13408:         }
1.687     albertel 13409: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13410: 	    $targetfn=$1;
                   13411: 	}
1.1427    raeburn  13412:         unless ($ignoresymbdb) {
1.1424    raeburn  13413:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13414:                           &GDBM_READER(),0640)) {
                   13415: 	        $syval=$hash{$targetfn};
                   13416:                 untie(%hash);
                   13417:             }
1.1427    raeburn  13418:             if ($syval && $checkforblock) {
                   13419:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  13420:                 if (@blockers) {
                   13421:                     $syval='';
                   13422:                 }
                   13423:             }
1.37      www      13424:         }
                   13425: # ---------------------------------------------------------- There was an entry
                   13426:         if ($syval) {
1.601     albertel 13427: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13428: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13429: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13430: 		    #return $env{$cache_str}='';
1.601     albertel 13431: 		#}    
                   13432: 		#$syval.=$1;
                   13433: 	    #}
1.37      www      13434:         } else {
                   13435: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13436:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13437:                             &GDBM_READER(),0640)) {
1.37      www      13438: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13439:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13440:               unless ($ids) { 
                   13441:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13442:               }
                   13443:               unless ($ids) {
                   13444: # alias?
                   13445: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13446:               }
1.37      www      13447:               if ($ids) {
                   13448: # ------------------------------------------------------------------- Has ID(s)
                   13449:                  my @possibilities=split(/\,/,$ids);
1.39      www      13450:                  if ($#possibilities==0) {
                   13451: # ----------------------------------------------- There is only one possibility
1.37      www      13452: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13453: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13454: 						    $resid,$thisfn);
1.1282    raeburn  13455:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  13456:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13457:                              $possibles->{$syval} = 1;
                   13458:                          }
1.1282    raeburn  13459:                      }
                   13460:                      if ($checkforblock) {
1.1424    raeburn  13461:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  13462:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  13463:                              if (@blockers) {
                   13464:                                  $syval = '';
1.1425    raeburn  13465:                                  untie(%bighash);
                   13466:                                  return $env{$cache_str}='';
1.1424    raeburn  13467:                              }
1.1282    raeburn  13468:                          }
                   13469:                      }
                   13470:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13471: # ------------------------------------------ There is more than one possibility
                   13472:                      my $realpossible=0;
1.800     albertel 13473:                      foreach my $id (@possibilities) {
                   13474: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13475:                          my $canaccess;
                   13476:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13477:                              $canaccess = 1;
                   13478:                          } else { 
                   13479:                              $canaccess = &allowed('bre',$file);
                   13480:                          }
                   13481:                          if ($canaccess) {
                   13482:          		     my ($mapid,$resid)=split(/\./,$id);
                   13483:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13484:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13485: 						             $resid,$thisfn);
1.1424    raeburn  13486:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  13487:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  13488:                                  if ($checkforblock) {
1.1426    raeburn  13489:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  13490:                                      if (@blockers > 0) {
                   13491:                                          $syval = '';
                   13492:                                      } else {
1.1282    raeburn  13493:                                          $syval = $poss_syval;
                   13494:                                          $realpossible++;
                   13495:                                      }
                   13496:                                  } else {
                   13497:                                      $syval = $poss_syval;
                   13498:                                      $realpossible++;
                   13499:                                  }
1.1424    raeburn  13500:                                  if ($syval) {
                   13501:                                      if (ref($possibles) eq 'HASH') {
                   13502:                                          $possibles->{$syval} = 1;
                   13503:                                      }
                   13504:                                  }
1.1282    raeburn  13505:                              }
1.39      www      13506: 			 }
1.191     harris41 13507:                      }
1.39      www      13508: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13509:                  } else {
                   13510:                      $syval='';
1.37      www      13511:                  }
                   13512: 	      }
1.1282    raeburn  13513:               untie(%bighash);
1.481     raeburn  13514:            }
1.31      www      13515:         }
1.62      www      13516:         if ($syval) {
1.1427    raeburn  13517: 	    return $env{$cache_str}=$syval;
1.62      www      13518:         }
1.31      www      13519:     }
1.949     raeburn  13520:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13521:     return $env{$cache_str}='';
1.31      www      13522: }
                   13523: 
                   13524: # ---------------------------------------------------------- Return random seed
                   13525: 
1.32      www      13526: sub numval {
                   13527:     my $txt=shift;
                   13528:     $txt=~tr/A-J/0-9/;
                   13529:     $txt=~tr/a-j/0-9/;
                   13530:     $txt=~tr/K-T/0-9/;
                   13531:     $txt=~tr/k-t/0-9/;
                   13532:     $txt=~tr/U-Z/0-5/;
                   13533:     $txt=~tr/u-z/0-5/;
                   13534:     $txt=~s/\D//g;
1.564     albertel 13535:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13536:     return int($txt);
1.368     albertel 13537: }
                   13538: 
1.484     albertel 13539: sub numval2 {
                   13540:     my $txt=shift;
                   13541:     $txt=~tr/A-J/0-9/;
                   13542:     $txt=~tr/a-j/0-9/;
                   13543:     $txt=~tr/K-T/0-9/;
                   13544:     $txt=~tr/k-t/0-9/;
                   13545:     $txt=~tr/U-Z/0-5/;
                   13546:     $txt=~tr/u-z/0-5/;
                   13547:     $txt=~s/\D//g;
                   13548:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13549:     my $total;
                   13550:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13551:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13552:     return int($total);
                   13553: }
                   13554: 
1.575     albertel 13555: sub numval3 {
                   13556:     use integer;
                   13557:     my $txt=shift;
                   13558:     $txt=~tr/A-J/0-9/;
                   13559:     $txt=~tr/a-j/0-9/;
                   13560:     $txt=~tr/K-T/0-9/;
                   13561:     $txt=~tr/k-t/0-9/;
                   13562:     $txt=~tr/U-Z/0-5/;
                   13563:     $txt=~tr/u-z/0-5/;
                   13564:     $txt=~s/\D//g;
                   13565:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13566:     my $total;
                   13567:     foreach my $val (@txts) { $total+=$val; }
                   13568:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13569:     return $total;
                   13570: }
                   13571: 
1.675     albertel 13572: sub digest {
                   13573:     my ($data)=@_;
                   13574:     my $digest=&Digest::MD5::md5($data);
                   13575:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13576:     my ($e,$f);
                   13577:     {
                   13578:         use integer;
                   13579:         $e=($a+$b);
                   13580:         $f=($c+$d);
                   13581:         if ($_64bit) {
                   13582:             $e=(($e<<32)>>32);
                   13583:             $f=(($f<<32)>>32);
                   13584:         }
                   13585:     }
                   13586:     if (wantarray) {
                   13587: 	return ($e,$f);
                   13588:     } else {
                   13589: 	my $g;
                   13590: 	{
                   13591: 	    use integer;
                   13592: 	    $g=($e+$f);
                   13593: 	    if ($_64bit) {
                   13594: 		$g=(($g<<32)>>32);
                   13595: 	    }
                   13596: 	}
                   13597: 	return $g;
                   13598:     }
                   13599: }
                   13600: 
1.368     albertel 13601: sub latest_rnd_algorithm_id {
1.675     albertel 13602:     return '64bit5';
1.366     albertel 13603: }
1.32      www      13604: 
1.503     albertel 13605: sub get_rand_alg {
                   13606:     my ($courseid)=@_;
1.790     albertel 13607:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13608:     if ($courseid) {
1.620     albertel 13609: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13610:     }
                   13611:     return &latest_rnd_algorithm_id();
                   13612: }
                   13613: 
1.562     albertel 13614: sub validCODE {
                   13615:     my ($CODE)=@_;
                   13616:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13617:     return 0;
                   13618: }
                   13619: 
1.491     albertel 13620: sub getCODE {
1.620     albertel 13621:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13622:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13623: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13624: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13625: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13626:     }
                   13627:     return undef;
                   13628: }
1.1133    foxr     13629: #
                   13630: #  Determines the random seed for a specific context:
                   13631: #
                   13632: # parameters:
                   13633: #   symb      - in course context the symb for the seed.
                   13634: #   course_id - The course id of the form domain_coursenum.
                   13635: #   domain    - Domain for the user.
                   13636: #   course    - Course for the user.
                   13637: #   cenv      - environment of the course.
                   13638: #
                   13639: # NOTE:
                   13640: #   All parameters are picked out of the environment if missing
                   13641: #   or not defined.
                   13642: #   If a symb cannot be determined the current time is used instead.
                   13643: #
                   13644: #  For a given well defined symb, courside, domain, username,
                   13645: #  and course environment, the seed is reproducible.
                   13646: #
1.31      www      13647: sub rndseed {
1.1133    foxr     13648:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13649:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13650:     if (!defined($symb)) {
1.366     albertel 13651: 	unless ($symb=$wsymb) { return time; }
                   13652:     }
1.1146    foxr     13653:     if (!defined $courseid) { 
                   13654: 	$courseid=$wcourseid; 
                   13655:     }
                   13656:     if (!defined $domain) { $domain=$wdomain; }
                   13657:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13658: 
                   13659:     my $which;
                   13660:     if (defined($cenv->{'rndseed'})) {
                   13661: 	$which = $cenv->{'rndseed'};
                   13662:     } else {
                   13663: 	$which =&get_rand_alg($courseid);
                   13664:     }
1.491     albertel 13665:     if (defined(&getCODE())) {
1.1133    foxr     13666: 
1.675     albertel 13667: 	if ($which eq '64bit5') {
                   13668: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13669: 	} elsif ($which eq '64bit4') {
1.575     albertel 13670: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13671: 	} else {
                   13672: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13673: 	}
1.675     albertel 13674:     } elsif ($which eq '64bit5') {
                   13675: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13676:     } elsif ($which eq '64bit4') {
                   13677: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13678:     } elsif ($which eq '64bit3') {
                   13679: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13680:     } elsif ($which eq '64bit2') {
                   13681: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13682:     } elsif ($which eq '64bit') {
                   13683: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13684:     }
                   13685:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13686: }
                   13687: 
                   13688: sub rndseed_32bit {
                   13689:     my ($symb,$courseid,$domain,$username)=@_;
                   13690:     {
                   13691: 	use integer;
                   13692: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13693: 	my $symbseed=numval($symb) << 22;
                   13694: 	my $namechck=unpack("%32C*",$username) << 17;
                   13695: 	my $nameseed=numval($username) << 12;
                   13696: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13697: 	my $courseseed=unpack("%32C*",$courseid);
                   13698: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13699: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13700: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13701: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13702: 	return $num;
                   13703:     }
                   13704: }
                   13705: 
                   13706: sub rndseed_64bit {
                   13707:     my ($symb,$courseid,$domain,$username)=@_;
                   13708:     {
                   13709: 	use integer;
                   13710: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13711: 	my $symbseed=numval($symb) << 10;
                   13712: 	my $namechck=unpack("%32S*",$username);
                   13713: 	
                   13714: 	my $nameseed=numval($username) << 21;
                   13715: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13716: 	my $courseseed=unpack("%32S*",$courseid);
                   13717: 	
                   13718: 	my $num1=$symbchck+$symbseed+$namechck;
                   13719: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13720: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13721: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13722: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13723: 	return "$num1,$num2";
1.155     albertel 13724:     }
1.366     albertel 13725: }
                   13726: 
1.443     albertel 13727: sub rndseed_64bit2 {
                   13728:     my ($symb,$courseid,$domain,$username)=@_;
                   13729:     {
                   13730: 	use integer;
                   13731: 	# strings need to be an even # of cahracters long, it it is odd the
                   13732:         # last characters gets thrown away
                   13733: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13734: 	my $symbseed=numval($symb) << 10;
                   13735: 	my $namechck=unpack("%32S*",$username.' ');
                   13736: 	
                   13737: 	my $nameseed=numval($username) << 21;
1.501     albertel 13738: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13739: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13740: 	
                   13741: 	my $num1=$symbchck+$symbseed+$namechck;
                   13742: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13743: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13744: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13745: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13746: 	return "$num1,$num2";
                   13747:     }
                   13748: }
                   13749: 
                   13750: sub rndseed_64bit3 {
                   13751:     my ($symb,$courseid,$domain,$username)=@_;
                   13752:     {
                   13753: 	use integer;
                   13754: 	# strings need to be an even # of cahracters long, it it is odd the
                   13755:         # last characters gets thrown away
                   13756: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13757: 	my $symbseed=numval2($symb) << 10;
                   13758: 	my $namechck=unpack("%32S*",$username.' ');
                   13759: 	
                   13760: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13761: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13762: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13763: 	
                   13764: 	my $num1=$symbchck+$symbseed+$namechck;
                   13765: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13766: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13767: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13768: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13769: 	
1.503     albertel 13770: 	return "$num1:$num2";
1.443     albertel 13771:     }
                   13772: }
                   13773: 
1.575     albertel 13774: sub rndseed_64bit4 {
                   13775:     my ($symb,$courseid,$domain,$username)=@_;
                   13776:     {
                   13777: 	use integer;
                   13778: 	# strings need to be an even # of cahracters long, it it is odd the
                   13779:         # last characters gets thrown away
                   13780: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13781: 	my $symbseed=numval3($symb) << 10;
                   13782: 	my $namechck=unpack("%32S*",$username.' ');
                   13783: 	
                   13784: 	my $nameseed=numval3($username) << 21;
                   13785: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13786: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13787: 	
                   13788: 	my $num1=$symbchck+$symbseed+$namechck;
                   13789: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13790: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13791: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13792: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13793: 	
1.575     albertel 13794: 	return "$num1:$num2";
                   13795:     }
                   13796: }
                   13797: 
1.675     albertel 13798: sub rndseed_64bit5 {
                   13799:     my ($symb,$courseid,$domain,$username)=@_;
                   13800:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13801:     return "$num1:$num2";
                   13802: }
                   13803: 
1.366     albertel 13804: sub rndseed_CODE_64bit {
                   13805:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13806:     {
1.366     albertel 13807: 	use integer;
1.443     albertel 13808: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13809: 	my $symbseed=numval2($symb);
1.491     albertel 13810: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13811: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13812: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13813: 	my $num1=$symbseed+$CODEchck;
                   13814: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13815: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13816: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13817: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13818: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13819: 	return "$num1:$num2";
1.366     albertel 13820:     }
                   13821: }
                   13822: 
1.575     albertel 13823: sub rndseed_CODE_64bit4 {
                   13824:     my ($symb,$courseid,$domain,$username)=@_;
                   13825:     {
                   13826: 	use integer;
                   13827: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13828: 	my $symbseed=numval3($symb);
                   13829: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13830: 	my $CODEseed=numval3(&getCODE());
                   13831: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13832: 	my $num1=$symbseed+$CODEchck;
                   13833: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13834: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13835: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13836: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13837: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13838: 	return "$num1:$num2";
                   13839:     }
                   13840: }
                   13841: 
1.675     albertel 13842: sub rndseed_CODE_64bit5 {
                   13843:     my ($symb,$courseid,$domain,$username)=@_;
                   13844:     my $code = &getCODE();
                   13845:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13846:     return "$num1:$num2";
                   13847: }
                   13848: 
1.366     albertel 13849: sub setup_random_from_rndseed {
                   13850:     my ($rndseed)=@_;
1.503     albertel 13851:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13852:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13853:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13854:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13855:         } else {
                   13856:             &Math::Random::random_set_seed($num1,$num2);
                   13857:         }
1.366     albertel 13858:     } else {
                   13859: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13860:     }
1.36      albertel 13861: }
                   13862: 
1.474     albertel 13863: sub latest_receipt_algorithm_id {
1.835     albertel 13864:     return 'receipt3';
1.474     albertel 13865: }
                   13866: 
1.480     www      13867: sub recunique {
                   13868:     my $fucourseid=shift;
                   13869:     my $unique;
1.835     albertel 13870:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13871: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13872: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13873:     } else {
                   13874: 	$unique=$perlvar{'lonReceipt'};
                   13875:     }
                   13876:     return unpack("%32C*",$unique);
                   13877: }
                   13878: 
                   13879: sub recprefix {
                   13880:     my $fucourseid=shift;
                   13881:     my $prefix;
1.835     albertel 13882:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13883: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13884: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13885:     } else {
                   13886: 	$prefix=$perlvar{'lonHostID'};
                   13887:     }
                   13888:     return unpack("%32C*",$prefix);
                   13889: }
                   13890: 
1.76      www      13891: sub ireceipt {
1.474     albertel 13892:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13893: 
                   13894:     my $return =&recprefix($fucourseid).'-';
                   13895: 
                   13896:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13897: 	$env{'request.state'} eq 'construct') {
                   13898: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13899: 	return $return;
                   13900:     }
                   13901: 
1.76      www      13902:     my $cuname=unpack("%32C*",$funame);
                   13903:     my $cudom=unpack("%32C*",$fudom);
                   13904:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13905:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13906:     my $cunique=&recunique($fucourseid);
1.474     albertel 13907:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13908:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13909: 
1.790     albertel 13910: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13911: 			       
                   13912: 	$return.= ($cunique%$cuname+
                   13913: 		   $cunique%$cudom+
                   13914: 		   $cusymb%$cuname+
                   13915: 		   $cusymb%$cudom+
                   13916: 		   $cucourseid%$cuname+
                   13917: 		   $cucourseid%$cudom+
                   13918: 		   $cpart%$cuname+
                   13919: 		   $cpart%$cudom);
                   13920:     } else {
                   13921: 	$return.= ($cunique%$cuname+
                   13922: 		   $cunique%$cudom+
                   13923: 		   $cusymb%$cuname+
                   13924: 		   $cusymb%$cudom+
                   13925: 		   $cucourseid%$cuname+
                   13926: 		   $cucourseid%$cudom);
                   13927:     }
                   13928:     return $return;
1.76      www      13929: }
                   13930: 
                   13931: sub receipt {
1.474     albertel 13932:     my ($part)=@_;
1.790     albertel 13933:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13934:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13935: }
1.260     ng       13936: 
1.790     albertel 13937: sub whichuser {
                   13938:     my ($passedsymb)=@_;
                   13939:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13940:     if (defined($env{'form.grade_symb'})) {
                   13941: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13942: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13943: 	if (!$allowed &&
                   13944: 	    exists($env{'request.course.sec'}) &&
                   13945: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13946: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13947: 			      '/'.$env{'request.course.sec'});
                   13948: 	}
                   13949: 	if ($allowed) {
                   13950: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13951: 	    $courseid=$tmp_courseid;
                   13952: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13953: 	    ($name)=&get_env_multiple('form.grade_username');
                   13954: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13955: 	}
                   13956:     }
                   13957:     if (!$passedsymb) {
                   13958: 	$symb=&symbread();
                   13959:     } else {
                   13960: 	$symb=$passedsymb;
                   13961:     }
                   13962:     $courseid=$env{'request.course.id'};
                   13963:     $domain=$env{'user.domain'};
                   13964:     $name=$env{'user.name'};
                   13965:     if ($name eq 'public' && $domain eq 'public') {
                   13966: 	if (!defined($env{'form.username'})) {
                   13967: 	    $env{'form.username'}.=time.rand(10000000);
                   13968: 	}
                   13969: 	$name.=$env{'form.username'};
                   13970:     }
                   13971:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13972: 
                   13973: }
                   13974: 
1.36      albertel 13975: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13976: # returns either the contents of the file or 
                   13977: # -1 if the file doesn't exist
1.481     raeburn  13978: #
                   13979: # if the target is a file that was uploaded via DOCS, 
                   13980: # a check will be made to see if a current copy exists on the local server,
                   13981: # if it does this will be served, otherwise a copy will be retrieved from
                   13982: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13983: # the local server.   
1.472     albertel 13984: 
1.36      albertel 13985: sub getfile {
1.538     albertel 13986:     my ($file) = @_;
1.609     banghart 13987:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13988:     &repcopy($file);
                   13989:     return &readfile($file);
                   13990: }
                   13991: 
                   13992: sub repcopy_userfile {
                   13993:     my ($file)=@_;
1.1142    raeburn  13994:     my $londocroot = $perlvar{'lonDocRoot'};
                   13995:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13996:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13997:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13998: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13999:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14000:     if (-e "$file") {
1.828     www      14001: # we already have a local copy, check it out
1.538     albertel 14002: 	my @fileinfo = stat($file);
1.828     www      14003: 	my $rtncode;
                   14004: 	my $info;
1.538     albertel 14005: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14006: 	if ($lwpresp ne 'ok') {
1.828     www      14007: # there is no such file anymore, even though we had a local copy
1.482     albertel 14008: 	    if ($rtncode eq '404') {
1.538     albertel 14009: 		unlink($file);
1.482     albertel 14010: 	    }
                   14011: 	    return -1;
                   14012: 	}
                   14013: 	if ($info < $fileinfo[9]) {
1.828     www      14014: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14015: 	    return 'ok';
1.828     www      14016: 	} else {
                   14017: # the file is outdated, get rid of it
                   14018: 	    unlink($file);
1.482     albertel 14019: 	}
1.828     www      14020:     }
                   14021: # one way or the other, at this point, we don't have the file
                   14022: # construct the correct path for the file
                   14023:     my @parts = ($cdom,$cnum); 
                   14024:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14025: 	push @parts, split(/\//,$1);
                   14026:     }
                   14027:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14028:     foreach my $part (@parts) {
                   14029: 	$path .= '/'.$part;
                   14030: 	if (!-e $path) {
                   14031: 	    mkdir($path,0770);
1.482     albertel 14032: 	}
                   14033:     }
1.828     www      14034: # now the path exists for sure
                   14035: # get a user agent
                   14036:     my $transferfile=$file.'.in.transfer';
                   14037: # FIXME: this should flock
                   14038:     if (-e $transferfile) { return 'ok'; }
                   14039:     my $request;
                   14040:     $uri=~s/^\///;
1.980     raeburn  14041:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  14042:     my $hostname = &hostname($homeserver);
1.980     raeburn  14043:     my $protocol = $protocol{$homeserver};
                   14044:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14045:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  14046:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      14047: # did it work?
                   14048:     if ($response->is_error()) {
                   14049: 	unlink($transferfile);
                   14050: 	&logthis("Userfile repcopy failed for $uri");
                   14051: 	return -1;
                   14052:     }
                   14053: # worked, rename the transfer file
                   14054:     rename($transferfile,$file);
1.607     raeburn  14055:     return 'ok';
1.481     raeburn  14056: }
                   14057: 
1.517     albertel 14058: sub tokenwrapper {
                   14059:     my $uri=shift;
1.980     raeburn  14060:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14061:     $uri=~s|^/||;
1.620     albertel 14062:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14063:     my $token=$1;
1.552     albertel 14064:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14065:     if ($udom && $uname && $file) {
                   14066: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14067:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14068:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  14069:         my $hostname = &hostname($homeserver);
1.980     raeburn  14070:         my $protocol = $protocol{$homeserver};
                   14071:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14072:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14073:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14074:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14075:     } else {
                   14076:         return '/adm/notfound.html';
                   14077:     }
                   14078: }
                   14079: 
1.828     www      14080: # call with reqtype HEAD: get last modification time
                   14081: # call with reqtype GET: get the file contents
                   14082: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14083: #
1.481     raeburn  14084: sub getuploaded {
                   14085:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14086:     $uri=~s/^\///;
1.980     raeburn  14087:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  14088:     my $hostname = &hostname($homeserver);
1.980     raeburn  14089:     my $protocol = $protocol{$homeserver};
                   14090:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14091:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14092:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  14093:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  14094:     $$rtncode = $response->code;
1.482     albertel 14095:     if (! $response->is_success()) {
                   14096: 	return 'failed';
                   14097:     }      
                   14098:     if ($reqtype eq 'HEAD') {
1.486     www      14099: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14100:     } elsif ($reqtype eq 'GET') {
                   14101: 	$$info = $response->content;
1.472     albertel 14102:     }
1.482     albertel 14103:     return 'ok';
1.36      albertel 14104: }
                   14105: 
1.481     raeburn  14106: sub readfile {
                   14107:     my $file = shift;
                   14108:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14109:     my $fh;
1.1359    raeburn  14110:     open($fh,"<",$file);
1.481     raeburn  14111:     my $a='';
1.800     albertel 14112:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14113:     return $a;
                   14114: }
                   14115: 
1.36      albertel 14116: sub filelocation {
1.590     banghart 14117:     my ($dir,$file) = @_;
                   14118:     my $location;
                   14119:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14120: 
                   14121:     if ($file =~ m-^/adm/-) {
                   14122: 	$file=~s-^/adm/wrapper/-/-;
                   14123: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14124:     }
1.882     albertel 14125: 
1.1139    www      14126:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14127:         $location = $file;
1.609     banghart 14128:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14129:         my ($udom,$uname,$filename)=
1.811     albertel 14130:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14131:         my $home=&homeserver($uname,$udom);
                   14132:         my $is_me=0;
                   14133:         my @ids=&current_machine_ids();
                   14134:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14135:         if ($is_me) {
1.1117    foxr     14136:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14137:         } else {
                   14138:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14139:   	      $udom.'/'.$uname.'/'.$filename;
                   14140:         }
1.882     albertel 14141:     } elsif ($file =~ m-^/adm/-) {
                   14142: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14143:     } else {
                   14144:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14145:         $file=~s:^/(res|priv)/:/:;
                   14146:         my $space=$1;
1.590     banghart 14147:         if ( !( $file =~ m:^/:) ) {
                   14148:             $location = $dir. '/'.$file;
                   14149:         } else {
1.1142    raeburn  14150:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14151:         }
1.59      albertel 14152:     }
1.590     banghart 14153:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14154:     while ($location=~m{/\.\./}) {
                   14155: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14156: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14157: 	} else {
                   14158: 	    $location=~ s{/\.\./}{/}g;
                   14159: 	}
                   14160:     } #remove dir/..
1.590     banghart 14161:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14162:     return $location;
1.46      www      14163: }
1.36      albertel 14164: 
1.46      www      14165: sub hreflocation {
                   14166:     my ($dir,$file)=@_;
1.980     raeburn  14167:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14168: 	$file=filelocation($dir,$file);
1.700     albertel 14169:     } elsif ($file=~m-^/adm/-) {
                   14170: 	$file=~s-^/adm/wrapper/-/-;
                   14171: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14172:     }
                   14173:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14174: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14175:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14176: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14177: 	        {/uploaded/$1/$2/}x;
1.46      www      14178:     }
1.913     albertel 14179:     if ($file=~ m{^/userfiles/}) {
                   14180: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14181:     }
1.462     albertel 14182:     return $file;
1.465     albertel 14183: }
                   14184: 
1.1139    www      14185: 
                   14186: 
                   14187: 
                   14188: 
1.465     albertel 14189: sub current_machine_domains {
1.853     albertel 14190:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14191: }
                   14192: 
                   14193: sub machine_domains {
                   14194:     my ($hostname) = @_;
1.465     albertel 14195:     my @domains;
1.838     albertel 14196:     my %hostname = &all_hostnames();
1.465     albertel 14197:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14198: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14199: 	if ($hostname eq $name) {
1.844     albertel 14200: 	    push(@domains,&host_domain($id));
1.465     albertel 14201: 	}
                   14202:     }
                   14203:     return @domains;
                   14204: }
                   14205: 
                   14206: sub current_machine_ids {
1.853     albertel 14207:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14208: }
                   14209: 
                   14210: sub machine_ids {
                   14211:     my ($hostname) = @_;
                   14212:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14213:     my @ids;
1.888     albertel 14214:     my %name_to_host = &all_names();
1.889     albertel 14215:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14216: 	return @{ $name_to_host{$hostname} };
                   14217:     }
                   14218:     return;
1.31      www      14219: }
                   14220: 
1.824     raeburn  14221: sub additional_machine_domains {
                   14222:     my @domains;
1.1359    raeburn  14223:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  14224:     while( my $line = <$fh>) {
                   14225:         $line =~ s/\s//g;
                   14226:         push(@domains,$line);
                   14227:     }
                   14228:     return @domains;
                   14229: }
                   14230: 
                   14231: sub default_login_domain {
                   14232:     my $domain = $perlvar{'lonDefDomain'};
                   14233:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14234:     foreach my $posdom (&current_machine_domains(),
                   14235:                         &additional_machine_domains()) {
                   14236:         if (lc($posdom) eq lc($testdomain)) {
                   14237:             $domain=$posdom;
                   14238:             last;
                   14239:         }
                   14240:     }
                   14241:     return $domain;
                   14242: }
                   14243: 
1.1414    raeburn  14244: sub shared_institution {
1.1439    raeburn  14245:     my ($dom,$lonhost) = @_;
                   14246:     if ($lonhost eq '') {
                   14247:         $lonhost = $perlvar{'lonHostID'};
                   14248:     }
1.1414    raeburn  14249:     my $same_intdom;
1.1439    raeburn  14250:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  14251:     if ($hostintdom ne '') {
                   14252:         my %iphost = &get_iphost();
                   14253:         my $primary_id = &domain($dom,'primary');
                   14254:         my $primary_ip = &get_host_ip($primary_id);
                   14255:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14256:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14257:                 my $intdom = &internet_dom($id);
                   14258:                 if ($intdom eq $hostintdom) {
                   14259:                     $same_intdom = 1;
                   14260:                     last;
                   14261:                 }
                   14262:             }
                   14263:         }
                   14264:     }
                   14265:     return $same_intdom;
                   14266: }
                   14267: 
1.1398    raeburn  14268: sub uses_sts {
                   14269:     my ($ignore_cache) = @_;
                   14270:     my $lonhost = $perlvar{'lonHostID'};
                   14271:     my $hostname = &hostname($lonhost);
                   14272:     my $sts_on;
                   14273:     if ($protocol{$lonhost} eq 'https') {
                   14274:         my $cachetime = 12*3600;
                   14275:         if (!$ignore_cache) {
                   14276:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14277:             if (defined($cached)) {
                   14278:                 return $sts_on;
                   14279:             }
                   14280:         }
                   14281:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14282:         my $request=new HTTP::Request('HEAD',$url);
                   14283:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14284:         if ($response->is_success) {
                   14285:             my $has_sts = $response->header('Strict-Transport-Security');
                   14286:             if ($has_sts eq '') {
                   14287:                 $sts_on = 0;
                   14288:             } else {
                   14289:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14290:                     my $maxage = $1;
                   14291:                     if ($maxage) {
                   14292:                         $sts_on = 1;
                   14293:                     } else {
                   14294:                         $sts_on = 0;
                   14295:                     }
                   14296:                 } else {
                   14297:                     $sts_on = 0;
                   14298:                 }
                   14299:             }
                   14300:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14301:         }
                   14302:     }
                   14303:     return;
                   14304: }
                   14305: 
1.1434    raeburn  14306: sub get_requestor_ip {
                   14307:     my ($r,$nolookup,$noproxy) = @_;
                   14308:     my $from_ip;
                   14309:     if (ref($r)) {
                   14310:         $from_ip = $r->get_remote_host($nolookup);
                   14311:     } else {
                   14312:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14313:     }
                   14314:     return $from_ip if ($noproxy); 
                   14315:     # Who controls proxy settings for server
                   14316:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14317:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14318:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  14319:         if ($proxyinfo->{'vpnint'}) {
                   14320:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  14321:                 return $from_ip;
                   14322:             }
                   14323:         }
                   14324:         if ($proxyinfo->{'trusted'}) {
                   14325:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14326:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14327:                 my ($ip,$xfor);
                   14328:                 if (ref($r)) {
                   14329:                     if ($ipheader) {
                   14330:                         $ip = $r->headers_in->{$ipheader};
                   14331:                     }
                   14332:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14333:                 } else {
                   14334:                     if ($ipheader) {
                   14335:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14336:                     }
                   14337:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14338:                 }
                   14339:                 if (($ip eq '') && ($xfor ne '')) {
                   14340:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14341:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14342:                             $ip = $poss_ip;
1.1435    raeburn  14343:                             last;
1.1434    raeburn  14344:                         }
                   14345:                     }
                   14346:                 }
                   14347:                 if ($ip ne '') {
                   14348:                     return $ip;
                   14349:                 }
                   14350:             }
                   14351:         }
                   14352:     }
                   14353:     return $from_ip;
                   14354: }
                   14355: 
                   14356: sub get_proxy_settings {
                   14357:     my ($dom_in_use) = @_;
                   14358:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14359:     my $proxyinfo = {
                   14360:                        ipheader => $domdefaults{'waf_ipheader'},
                   14361:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  14362:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  14363:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1434    raeburn  14364:                     };
                   14365:     return $proxyinfo;
                   14366: }
                   14367: 
                   14368: sub ip_match {
                   14369:     my ($ip,$pattern_str) = @_;
                   14370:     $ip=Net::CIDR::cidrvalidate($ip);
                   14371:     if ($ip) {
                   14372:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14373:     }
                   14374:     return;
                   14375: }
                   14376: 
                   14377: sub get_proxy_alias {
                   14378:     my $lonhost = $perlvar{'lonHostID'};
                   14379:     if ($lonhost ne '') {
                   14380:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonhost);
                   14381:         if ($cached) {
                   14382:             return $alias;
                   14383:         }
                   14384:         my $dom = &Apache::lonnet::host_domain($lonhost);
                   14385:         if ($dom ne '') {
                   14386:             my $cachetime = 60*60*24;
                   14387:             my %domconfig =
1.1437    raeburn  14388:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
1.1434    raeburn  14389:             my $alias;
1.1437    raeburn  14390:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14391:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14392:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonhost};
1.1434    raeburn  14393:                 }
                   14394:             }
                   14395:             return &do_cache_new('proxyalias',$lonhost,$alias,$cachetime);
                   14396:         }
                   14397:     }
                   14398:     return;
                   14399: }
                   14400: 
1.31      www      14401: # ------------------------------------------------------------- Declutters URLs
                   14402: 
                   14403: sub declutter {
                   14404:     my $thisfn=shift;
1.569     albertel 14405:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14406:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14407:         $thisfn=~s{^/home/httpd/html}{};
                   14408:     }
1.31      www      14409:     $thisfn=~s/^\///;
1.697     albertel 14410:     $thisfn=~s|^adm/wrapper/||;
                   14411:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14412:     $thisfn=~s/^res\///;
1.1172    bisitz   14413:     $thisfn=~s/^priv\///;
1.1032    raeburn  14414:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14415:         $thisfn=~s/\?.+$//;
                   14416:     }
1.268     www      14417:     return $thisfn;
                   14418: }
                   14419: 
                   14420: # ------------------------------------------------------------- Clutter up URLs
                   14421: 
                   14422: sub clutter {
                   14423:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14424:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14425: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14426:        $thisfn='/res'.$thisfn; 
                   14427:     }
1.1031    raeburn  14428:     if ($thisfn !~m|^/adm|) {
                   14429: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14430: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14431: 	} else {
                   14432: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14433: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14434: 	    if ($embstyle eq 'ssi'
                   14435: 		|| ($embstyle eq 'hdn')
                   14436: 		|| ($embstyle eq 'rat')
                   14437: 		|| ($embstyle eq 'prv')
                   14438: 		|| ($embstyle eq 'ign')) {
                   14439: 		#do nothing with these
                   14440: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14441: 		|| ($embstyle eq 'emb')
                   14442: 		|| ($embstyle eq 'wrp')) {
                   14443: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14444: 	    } elsif ($embstyle eq 'unk'
                   14445: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14446: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14447: 	    } else {
1.718     www      14448: #		&logthis("Got a blank emb style");
1.695     albertel 14449: 	    }
1.694     albertel 14450: 	}
1.1343    raeburn  14451:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14452:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14453:     }
1.31      www      14454:     return $thisfn;
1.12      www      14455: }
                   14456: 
1.787     albertel 14457: sub clutter_with_no_wrapper {
                   14458:     my $uri = &clutter(shift);
                   14459:     if ($uri =~ m-^/adm/-) {
                   14460: 	$uri =~ s-^/adm/wrapper/-/-;
                   14461: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14462:     }
                   14463:     return $uri;
                   14464: }
                   14465: 
1.557     albertel 14466: sub freeze_escape {
                   14467:     my ($value)=@_;
                   14468:     if (ref($value)) {
                   14469: 	$value=&nfreeze($value);
                   14470: 	return '__FROZEN__'.&escape($value);
                   14471:     }
                   14472:     return &escape($value);
                   14473: }
                   14474: 
1.11      www      14475: 
1.557     albertel 14476: sub thaw_unescape {
                   14477:     my ($value)=@_;
                   14478:     if ($value =~ /^__FROZEN__/) {
                   14479: 	substr($value,0,10,undef);
                   14480: 	$value=&unescape($value);
                   14481: 	return &thaw($value);
                   14482:     }
                   14483:     return &unescape($value);
                   14484: }
                   14485: 
1.436     albertel 14486: sub correct_line_ends {
                   14487:     my ($result)=@_;
                   14488:     $$result =~s/\r\n/\n/mg;
                   14489:     $$result =~s/\r/\n/mg;
1.415     albertel 14490: }
1.1       albertel 14491: # ================================================================ Main Program
                   14492: 
1.184     www      14493: sub goodbye {
1.204     albertel 14494:    &logthis("Starting Shut down");
1.443     albertel 14495: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14496:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14497: #converted
1.599     albertel 14498: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14499:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14500: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14501: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14502: #1.1 only
1.870     albertel 14503: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14504: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14505: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14506: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14507:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14508:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14509:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14510:    &flushcourselogs();
                   14511:    &logthis("Shutting down");
                   14512: }
                   14513: 
1.852     albertel 14514: sub get_dns {
1.1210    raeburn  14515:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14516:     if (!$ignore_cache) {
                   14517: 	my ($content,$cached)=
                   14518: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14519: 	if ($cached) {
1.1210    raeburn  14520: 	    &$func($content,$hashref);
1.869     albertel 14521: 	    return;
                   14522: 	}
                   14523:     }
                   14524: 
                   14525:     my %alldns;
1.1379    raeburn  14526:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14527:         foreach my $dns (<$config>) {
                   14528: 	    next if ($dns !~ /^\^(\S*)/x);
                   14529:             my $line = $1;
                   14530:             my ($host,$protocol) = split(/:/,$line);
                   14531:             if ($protocol ne 'https') {
                   14532:                 $protocol = 'http';
                   14533:             }
                   14534: 	    $alldns{$host} = $protocol;
1.979     raeburn  14535:         }
1.1379    raeburn  14536:         close($config);
1.869     albertel 14537:     }
                   14538:     while (%alldns) {
1.1263    raeburn  14539: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  14540: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  14541:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  14542:         delete($alldns{$dns});
1.852     albertel 14543: 	next if ($response->is_error());
1.1379    raeburn  14544:         if ($url eq '/adm/dns/loncapaCRL') {
                   14545:             return &$func($response);
                   14546:         } else {
                   14547: 	    my @content = split("\n",$response->content);
                   14548: 	    unless ($nocache) {
                   14549: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14550: 	    }
                   14551: 	    &$func(\@content,$hashref);
                   14552:             return;
                   14553:         }
                   14554:     }
                   14555:     my $which = (split('/',$url,4))[3];
                   14556:     if ($which eq 'loncapaCRL') {
                   14557:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14558:         if (-e $diskfile) {
                   14559:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14560:         } else {
                   14561:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14562:         }
                   14563:     } else {
                   14564:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14565:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14566:             my @content = <$config>;
                   14567:             close($config);
                   14568:             &$func(\@content,$hashref);
                   14569:         }
1.852     albertel 14570:     }
1.1210    raeburn  14571:     return;
                   14572: }
                   14573: 
                   14574: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14575: sub parse_dns_checksums_tab {
1.1210    raeburn  14576:     my ($lines,$hashref) = @_;
1.1264    raeburn  14577:     my $lonhost = $perlvar{'lonHostID'};
                   14578:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14579:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14580:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14581:     my $webconfdir = '/etc/httpd/conf';
                   14582:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14583:         $webconfdir = '/etc/apache2';
                   14584:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14585:         if ($1 >= 10) {
                   14586:             $webconfdir = '/etc/apache2';
                   14587:         }
                   14588:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14589:         if ($1 >= 10.0) {
                   14590:             $webconfdir = '/etc/apache2';
                   14591:         }
                   14592:     }
1.1210    raeburn  14593:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14594:     my (%chksum,%revnum);
                   14595:     if (ref($lines) eq 'ARRAY') {
                   14596:         chomp(@{$lines});
1.1238    raeburn  14597:         my $version = shift(@{$lines});
                   14598:         if ($version eq $release) {  
1.1210    raeburn  14599:             foreach my $line (@{$lines}) {
1.1238    raeburn  14600:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14601:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14602:                     if ($webconfdir eq '/etc/apache2') {
                   14603:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14604:                     }
                   14605:                 }
1.1238    raeburn  14606:                 $chksum{$file} = $shasum;
                   14607:                 $revnum{$file} = $version;
1.1210    raeburn  14608:             }
                   14609:             if (ref($hashref) eq 'HASH') {
                   14610:                 %{$hashref} = (
                   14611:                                 sums     => \%chksum,
                   14612:                                 versions => \%revnum,
                   14613:                               );
                   14614:             }
                   14615:         }
                   14616:     }
1.869     albertel 14617:     return;
1.852     albertel 14618: }
1.1210    raeburn  14619: 
                   14620: sub fetch_dns_checksums {
1.1238    raeburn  14621:     my %checksums;
                   14622:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14623:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14624:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14625:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14626:              \%checksums);
1.1210    raeburn  14627:     return \%checksums;
                   14628: }
                   14629: 
1.1379    raeburn  14630: sub fetch_crl_pemfile {
                   14631:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14632: }
                   14633: 
                   14634: sub save_crl_pem {
                   14635:     my ($response) = @_;
1.1380    raeburn  14636:     my ($msg,$hadchanges);
1.1379    raeburn  14637:     if (ref($response)) {
                   14638:         my $now = time;
                   14639:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14640:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14641:         if (open(my $fh,'>',"$tmpcrl")) {
                   14642:             print $fh $response->content;
                   14643:             close($fh);
                   14644:             if (-e $lonca) {
                   14645:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14646:                     my $check = <PIPE>;
                   14647:                     close(PIPE);
                   14648:                     chomp($check);
                   14649:                     if ($check eq 'verify OK') {
                   14650:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  14651:                         my $backup;
1.1379    raeburn  14652:                         if (-e $dest) {
1.1380    raeburn  14653:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   14654:                                 $backup = 'ok';
                   14655:                             }
1.1379    raeburn  14656:                         }
                   14657:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   14658:                             $msg = 'ok';
1.1380    raeburn  14659:                             if ($backup) {
                   14660:                                 my (%oldnums,%newnums);
                   14661:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   14662:                                     while (<PIPE>) {
                   14663:                                         $oldnums{(split(/:/))[1]} = 1;
                   14664:                                     }
                   14665:                                     close(PIPE);
                   14666:                                 }
                   14667:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   14668:                                     while(<PIPE>) {
                   14669:                                         $newnums{(split(/:/))[1]} = 1;
                   14670:                                     }
                   14671:                                     close(PIPE);
                   14672:                                 }
                   14673:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   14674:                                     unless (exists($oldnums{$key})) {
                   14675:                                         $hadchanges = 1;
                   14676:                                         last;
                   14677:                                     }
                   14678:                                 }
                   14679:                                 unless ($hadchanges) {
                   14680:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   14681:                                         unless (exists($newnums{$key})) {
                   14682:                                             $hadchanges = 1;
                   14683:                                             last;
                   14684:                                         }
                   14685:                                     }
                   14686:                                 }
                   14687:                             }
1.1379    raeburn  14688:                         }
                   14689:                     } else {
                   14690:                         unlink($tmpcrl);
                   14691:                     }
                   14692:                 } else {
                   14693:                     unlink($tmpcrl);
                   14694:                 }
                   14695:             } else {
                   14696:                 unlink($tmpcrl);
                   14697:             }
                   14698:         }
                   14699:     }
1.1380    raeburn  14700:     return ($msg,$hadchanges);
1.1379    raeburn  14701: }
                   14702: 
1.327     albertel 14703: # ------------------------------------------------------------ Read domain file
                   14704: {
1.852     albertel 14705:     my $loaded;
1.846     albertel 14706:     my %domain;
                   14707: 
1.852     albertel 14708:     sub parse_domain_tab {
                   14709: 	my ($lines) = @_;
                   14710: 	foreach my $line (@$lines) {
                   14711: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14712: 
1.846     albertel 14713: 	    chomp($line);
1.852     albertel 14714: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14715: 	    my %this_domain;
                   14716: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14717: 			       'lang_def', 'city', 'longi', 'lati',
                   14718: 			       'primary') {
                   14719: 		$this_domain{$field} = shift(@elements);
                   14720: 	    }
                   14721: 	    $domain{$name} = \%this_domain;
1.852     albertel 14722: 	}
                   14723:     }
1.864     albertel 14724: 
                   14725:     sub reset_domain_info {
                   14726: 	undef($loaded);
                   14727: 	undef(%domain);
                   14728:     }
                   14729: 
1.852     albertel 14730:     sub load_domain_tab {
1.1293    raeburn  14731: 	my ($ignore_cache,$nocache) = @_;
                   14732: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14733: 	my $fh;
1.1359    raeburn  14734: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14735: 	    my @lines = <$fh>;
                   14736: 	    &parse_domain_tab(\@lines);
1.448     albertel 14737: 	}
1.852     albertel 14738: 	close($fh);
                   14739: 	$loaded = 1;
1.327     albertel 14740:     }
1.846     albertel 14741: 
                   14742:     sub domain {
1.852     albertel 14743: 	&load_domain_tab() if (!$loaded);
                   14744: 
1.846     albertel 14745: 	my ($name,$what) = @_;
                   14746: 	return if ( !exists($domain{$name}) );
                   14747: 
                   14748: 	if (!$what) {
                   14749: 	    return $domain{$name}{'description'};
                   14750: 	}
                   14751: 	return $domain{$name}{$what};
                   14752:     }
1.974     raeburn  14753: 
                   14754:     sub domain_info {
                   14755:         &load_domain_tab() if (!$loaded);
                   14756:         return %domain;
                   14757:     }
                   14758: 
1.327     albertel 14759: }
                   14760: 
                   14761: 
1.1       albertel 14762: # ------------------------------------------------------------- Read hosts file
                   14763: {
1.838     albertel 14764:     my %hostname;
1.844     albertel 14765:     my %hostdom;
1.845     albertel 14766:     my %libserv;
1.852     albertel 14767:     my $loaded;
1.888     albertel 14768:     my %name_to_host;
1.1074    raeburn  14769:     my %internetdom;
1.1107    raeburn  14770:     my %LC_dns_serv;
1.852     albertel 14771: 
                   14772:     sub parse_hosts_tab {
                   14773: 	my ($file) = @_;
                   14774: 	foreach my $configline (@$file) {
                   14775: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14776:             chomp($configline);
                   14777: 	    if ($configline =~ /^\^/) {
                   14778:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14779:                     $LC_dns_serv{$1} = 1;
                   14780:                 }
                   14781:                 next;
                   14782:             }
1.1074    raeburn  14783: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14784: 	    $name=~s/\s//g;
                   14785: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  14786:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14787:                     my $curr = $hostname{$id};
                   14788:                     my $skip;
                   14789:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14790:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14791:                             $skip = 1;
                   14792:                         } else {
                   14793:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14794:                         }
                   14795:                     }
                   14796:                     unless ($skip) {
                   14797:                         push(@{$name_to_host{$name}},$id);
                   14798:                     }
                   14799:                 } else {
                   14800:                     push(@{$name_to_host{$name}},$id);
                   14801:                 }
1.852     albertel 14802: 		$hostname{$id}=$name;
                   14803: 		$hostdom{$id}=$domain;
                   14804: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14805:                 if (defined($protocol)) {
                   14806:                     if ($protocol eq 'https') {
                   14807:                         $protocol{$id} = $protocol;
                   14808:                     } else {
                   14809:                         $protocol{$id} = 'http'; 
                   14810:                     }
1.968     raeburn  14811:                 } else {
1.969     raeburn  14812:                     $protocol{$id} = 'http';
1.968     raeburn  14813:                 }
1.1074    raeburn  14814:                 if (defined($intdom)) {
                   14815:                     $internetdom{$id} = $intdom;
                   14816:                 }
1.852     albertel 14817: 	    }
                   14818: 	}
                   14819:     }
1.864     albertel 14820:     
                   14821:     sub reset_hosts_info {
1.897     albertel 14822: 	&purge_remembered();
1.864     albertel 14823: 	&reset_domain_info();
                   14824: 	&reset_hosts_ip_info();
1.1339    raeburn  14825:         undef(%internetdom);
1.892     albertel 14826: 	undef(%name_to_host);
1.864     albertel 14827: 	undef(%hostname);
                   14828: 	undef(%hostdom);
                   14829: 	undef(%libserv);
                   14830: 	undef($loaded);
                   14831:     }
1.1       albertel 14832: 
1.852     albertel 14833:     sub load_hosts_tab {
1.1293    raeburn  14834: 	my ($ignore_cache,$nocache) = @_;
                   14835: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  14836: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14837: 	my @config = <$config>;
                   14838: 	&parse_hosts_tab(\@config);
                   14839: 	close($config);
                   14840: 	$loaded=1;
1.1       albertel 14841:     }
1.852     albertel 14842: 
1.838     albertel 14843:     sub hostname {
1.852     albertel 14844: 	&load_hosts_tab() if (!$loaded);
                   14845: 
1.838     albertel 14846: 	my ($lonid) = @_;
                   14847: 	return $hostname{$lonid};
                   14848:     }
1.845     albertel 14849: 
1.838     albertel 14850:     sub all_hostnames {
1.852     albertel 14851: 	&load_hosts_tab() if (!$loaded);
                   14852: 
1.838     albertel 14853: 	return %hostname;
                   14854:     }
1.845     albertel 14855: 
1.888     albertel 14856:     sub all_names {
1.1293    raeburn  14857:         my ($ignore_cache,$nocache) = @_;
                   14858: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14859: 
                   14860: 	return %name_to_host;
                   14861:     }
                   14862: 
1.974     raeburn  14863:     sub all_host_domain {
                   14864:         &load_hosts_tab() if (!$loaded);
                   14865:         return %hostdom;
                   14866:     }
                   14867: 
1.1339    raeburn  14868:     sub all_host_intdom {
                   14869:         &load_hosts_tab() if (!$loaded);
                   14870:         return %internetdom;
                   14871:     }
                   14872: 
1.845     albertel 14873:     sub is_library {
1.852     albertel 14874: 	&load_hosts_tab() if (!$loaded);
                   14875: 
1.845     albertel 14876: 	return exists($libserv{$_[0]});
                   14877:     }
                   14878: 
                   14879:     sub all_library {
1.852     albertel 14880: 	&load_hosts_tab() if (!$loaded);
                   14881: 
1.845     albertel 14882: 	return %libserv;
                   14883:     }
                   14884: 
1.1062    droeschl 14885:     sub unique_library {
                   14886: 	#2x reverse removes all hostnames that appear more than once
                   14887:         my %unique = reverse &all_library();
                   14888:         return reverse %unique;
                   14889:     }
                   14890: 
1.841     albertel 14891:     sub get_servers {
1.852     albertel 14892: 	&load_hosts_tab() if (!$loaded);
                   14893: 
1.841     albertel 14894: 	my ($domain,$type) = @_;
                   14895: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14896: 	                                          : %hostname;
                   14897: 	my %result;
1.842     albertel 14898: 	if (ref($domain) eq 'ARRAY') {
                   14899: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14900: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14901: 		    $result{$host} = $hostname;
                   14902: 		}
                   14903: 	    }
                   14904: 	} else {
                   14905: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14906: 		if ($hostdom{$host} eq $domain) {
                   14907: 		    $result{$host} = $hostname;
                   14908: 		}
1.841     albertel 14909: 	    }
                   14910: 	}
                   14911: 	return %result;
                   14912:     }
1.845     albertel 14913: 
1.1062    droeschl 14914:     sub get_unique_servers {
                   14915:         my %unique = reverse &get_servers(@_);
                   14916: 	return reverse %unique;
                   14917:     }
                   14918: 
1.844     albertel 14919:     sub host_domain {
1.852     albertel 14920: 	&load_hosts_tab() if (!$loaded);
                   14921: 
1.844     albertel 14922: 	my ($lonid) = @_;
                   14923: 	return $hostdom{$lonid};
                   14924:     }
                   14925: 
1.841     albertel 14926:     sub all_domains {
1.852     albertel 14927: 	&load_hosts_tab() if (!$loaded);
                   14928: 
1.841     albertel 14929: 	my %seen;
                   14930: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14931: 	return @uniq;
                   14932:     }
1.1074    raeburn  14933: 
                   14934:     sub internet_dom {
                   14935:         &load_hosts_tab() if (!$loaded);
                   14936: 
                   14937:         my ($lonid) = @_;
                   14938:         return $internetdom{$lonid};
                   14939:     }
1.1107    raeburn  14940: 
                   14941:     sub is_LC_dns {
                   14942:         &load_hosts_tab() if (!$loaded);
                   14943: 
                   14944:         my ($hostname) = @_;
                   14945:         return exists($LC_dns_serv{$hostname});
                   14946:     }
                   14947: 
1.1       albertel 14948: }
                   14949: 
1.847     albertel 14950: { 
                   14951:     my %iphost;
1.856     albertel 14952:     my %name_to_ip;
                   14953:     my %lonid_to_ip;
1.869     albertel 14954: 
1.847     albertel 14955:     sub get_hosts_from_ip {
                   14956: 	my ($ip) = @_;
                   14957: 	my %iphosts = &get_iphost();
                   14958: 	if (ref($iphosts{$ip})) {
                   14959: 	    return @{$iphosts{$ip}};
                   14960: 	}
                   14961: 	return;
1.839     albertel 14962:     }
1.864     albertel 14963:     
                   14964:     sub reset_hosts_ip_info {
                   14965: 	undef(%iphost);
                   14966: 	undef(%name_to_ip);
                   14967: 	undef(%lonid_to_ip);
                   14968:     }
1.856     albertel 14969: 
                   14970:     sub get_host_ip {
                   14971: 	my ($lonid) = @_;
                   14972: 	if (exists($lonid_to_ip{$lonid})) {
                   14973: 	    return $lonid_to_ip{$lonid};
                   14974: 	}
                   14975: 	my $name=&hostname($lonid);
                   14976:    	my $ip = gethostbyname($name);
                   14977: 	return if (!$ip || length($ip) ne 4);
                   14978: 	$ip=inet_ntoa($ip);
                   14979: 	$name_to_ip{$name}   = $ip;
                   14980: 	$lonid_to_ip{$lonid} = $ip;
                   14981: 	return $ip;
                   14982:     }
1.847     albertel 14983:     
                   14984:     sub get_iphost {
1.1293    raeburn  14985: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14986: 
1.869     albertel 14987: 	if (!$ignore_cache) {
                   14988: 	    if (%iphost) {
                   14989: 		return %iphost;
                   14990: 	    }
                   14991: 	    my ($ip_info,$cached)=
                   14992: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14993: 	    if ($cached) {
                   14994: 		%iphost      = %{$ip_info->[0]};
                   14995: 		%name_to_ip  = %{$ip_info->[1]};
                   14996: 		%lonid_to_ip = %{$ip_info->[2]};
                   14997: 		return %iphost;
                   14998: 	    }
                   14999: 	}
1.894     albertel 15000: 
                   15001: 	# get yesterday's info for fallback
                   15002: 	my %old_name_to_ip;
                   15003: 	my ($ip_info,$cached)=
                   15004: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15005: 	if ($cached) {
                   15006: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15007: 	}
                   15008: 
1.1293    raeburn  15009: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15010: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15011: 	    my $ip;
                   15012: 	    if (!exists($name_to_ip{$name})) {
                   15013: 		$ip = gethostbyname($name);
                   15014: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15015: 		    if (defined($old_name_to_ip{$name})) {
                   15016: 			$ip = $old_name_to_ip{$name};
                   15017: 			&logthis("Can't find $name defaulting to old $ip");
                   15018: 		    } else {
                   15019: 			&logthis("Name $name no IP found");
                   15020: 			next;
                   15021: 		    }
                   15022: 		} else {
                   15023: 		    $ip=inet_ntoa($ip);
1.847     albertel 15024: 		}
                   15025: 		$name_to_ip{$name} = $ip;
                   15026: 	    } else {
                   15027: 		$ip = $name_to_ip{$name};
1.653     albertel 15028: 	    }
1.888     albertel 15029: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15030: 		$lonid_to_ip{$id} = $ip;
                   15031: 	    }
                   15032: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15033: 	}
1.1293    raeburn  15034:         unless ($nocache) {
                   15035: 	    &do_cache_new('iphost','iphost',
                   15036: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15037: 		          48*60*60);
                   15038:         }
1.869     albertel 15039: 
1.847     albertel 15040: 	return %iphost;
1.598     albertel 15041:     }
                   15042: 
1.992     raeburn  15043:     #
                   15044:     #  Given a DNS returns the loncapa host name for that DNS 
                   15045:     # 
                   15046:     sub host_from_dns {
                   15047:         my ($dns) = @_;
                   15048:         my @hosts;
                   15049:         my $ip;
                   15050: 
1.993     raeburn  15051:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15052:             $ip = $name_to_ip{$dns};
                   15053:         }
                   15054:         if (!$ip) {
                   15055:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15056:             if (length($ip) == 4) { 
                   15057: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15058:             }
                   15059:         }
                   15060:         if ($ip) {
                   15061: 	    @hosts = get_hosts_from_ip($ip);
                   15062: 	    return $hosts[0];
                   15063:         }
                   15064:         return undef;
1.986     foxr     15065:     }
1.992     raeburn  15066: 
1.1074    raeburn  15067:     sub get_internet_names {
                   15068:         my ($lonid) = @_;
                   15069:         return if ($lonid eq '');
                   15070:         my ($idnref,$cached)=
                   15071:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15072:         if ($cached) {
                   15073:             return $idnref;
                   15074:         }
                   15075:         my $ip = &get_host_ip($lonid);
                   15076:         my @hosts = &get_hosts_from_ip($ip);
                   15077:         my %iphost = &get_iphost();
                   15078:         my (@idns,%seen);
                   15079:         foreach my $id (@hosts) {
                   15080:             my $dom = &host_domain($id);
                   15081:             my $prim_id = &domain($dom,'primary');
                   15082:             my $prim_ip = &get_host_ip($prim_id);
                   15083:             next if ($seen{$prim_ip});
                   15084:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15085:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15086:                     my $intdom = &internet_dom($id);
                   15087:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15088:                         push(@idns,$intdom);
                   15089:                     }
                   15090:                 }
                   15091:             }
                   15092:             $seen{$prim_ip} = 1;
                   15093:         }
1.1219    raeburn  15094:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15095:     }
                   15096: 
1.986     foxr     15097: }
                   15098: 
1.1079    raeburn  15099: sub all_loncaparevs {
1.1249    raeburn  15100:     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  15101: }
                   15102: 
1.1227    raeburn  15103: # ---------------------------------------------------------- Read loncaparev table
                   15104: {
                   15105:     sub load_loncaparevs { 
                   15106:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  15107:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  15108:                 while (my $configline=<$config>) {
                   15109:                     chomp($configline);
                   15110:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15111:                     $loncaparevs{$hostid}=$loncaparev;
                   15112:                 }
                   15113:                 close($config);
                   15114:             }
                   15115:         }
                   15116:     }
                   15117: }
                   15118: 
                   15119: # ---------------------------------------------------------- Read serverhostID table
                   15120: {
                   15121:     sub load_serverhomeIDs {
                   15122:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  15123:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  15124:                 while (my $configline=<$config>) {
                   15125:                     chomp($configline);
                   15126:                     my ($name,$id)=split(/:/,$configline);
                   15127:                     $serverhomeIDs{$name}=$id;
                   15128:                 }
                   15129:                 close($config);
                   15130:             }
                   15131:         }
                   15132:     }
                   15133: }
                   15134: 
                   15135: 
1.862     albertel 15136: BEGIN {
                   15137: 
                   15138: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15139:     unless ($readit) {
                   15140: {
                   15141:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15142:     %perlvar = (%perlvar,%{$configvars});
                   15143: }
                   15144: 
                   15145: 
1.1       albertel 15146: # ------------------------------------------------------ Read spare server file
                   15147: {
1.1359    raeburn  15148:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15149: 
                   15150:     while (my $configline=<$config>) {
                   15151:        chomp($configline);
1.284     matthew  15152:        if ($configline) {
1.784     albertel 15153: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15154: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15155: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15156:        }
                   15157:     }
1.448     albertel 15158:     close($config);
1.1       albertel 15159: }
1.11      www      15160: # ------------------------------------------------------------ Read permissions
                   15161: {
1.1359    raeburn  15162:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15163: 
                   15164:     while (my $configline=<$config>) {
1.448     albertel 15165: 	chomp($configline);
                   15166: 	if ($configline) {
                   15167: 	    my ($role,$perm)=split(/ /,$configline);
                   15168: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15169: 	}
1.11      www      15170:     }
1.448     albertel 15171:     close($config);
1.11      www      15172: }
                   15173: 
                   15174: # -------------------------------------------- Read plain texts for permissions
                   15175: {
1.1359    raeburn  15176:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15177: 
                   15178:     while (my $configline=<$config>) {
1.448     albertel 15179: 	chomp($configline);
                   15180: 	if ($configline) {
1.742     raeburn  15181: 	    my ($short,@plain)=split(/:/,$configline);
                   15182:             %{$prp{$short}} = ();
                   15183: 	    if (@plain > 0) {
                   15184:                 $prp{$short}{'std'} = $plain[0];
                   15185:                 for (my $i=1; $i<@plain; $i++) {
                   15186:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15187:                 }
                   15188:             }
1.448     albertel 15189: 	}
1.135     www      15190:     }
1.448     albertel 15191:     close($config);
1.135     www      15192: }
                   15193: 
                   15194: # ---------------------------------------------------------- Read package table
                   15195: {
1.1359    raeburn  15196:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15197: 
                   15198:     while (my $configline=<$config>) {
1.483     albertel 15199: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15200: 	chomp($configline);
                   15201: 	my ($short,$plain)=split(/:/,$configline);
                   15202: 	my ($pack,$name)=split(/\&/,$short);
                   15203: 	if ($plain ne '') {
                   15204: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15205: 	    $packagetab{$short}=$plain; 
                   15206: 	}
1.11      www      15207:     }
1.448     albertel 15208:     close($config);
1.329     matthew  15209: }
                   15210: 
1.1073    raeburn  15211: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  15212: 
                   15213: &load_loncaparevs();
1.1073    raeburn  15214: 
1.1074    raeburn  15215: # ---------------------------------------------------------- Read serverhostID table
                   15216: 
1.1227    raeburn  15217: &load_serverhomeIDs();
                   15218: 
                   15219: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15220: {
                   15221:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15222:     if (-e $file) {
                   15223:         my $parser = HTML::LCParser->new($file);
                   15224:         while (my $token = $parser->get_token()) {
                   15225:             if ($token->[0] eq 'S') {
                   15226:                 my $item = $token->[1];
                   15227:                 my $name = $token->[2]{'name'};
                   15228:                 my $value = $token->[2]{'value'};
1.1285    raeburn  15229:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  15230:                 my $namematch = $token->[2]{'namematch'};
                   15231:                 if ($item eq 'parameter') {
                   15232:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   15233:                         my $release = $parser->get_text();
                   15234:                         $release =~ s/(^\s*|\s*$ )//gx;
                   15235:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   15236:                     }
                   15237:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  15238:                     my $release = $parser->get_text();
                   15239:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  15240:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  15241:                 }
                   15242:             }
                   15243:         }
                   15244:     }
1.1073    raeburn  15245: }
                   15246: 
1.1138    raeburn  15247: # ---------------------------------------------------------- Read managers table
                   15248: {
                   15249:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  15250:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15251:             while (my $configline=<$config>) {
                   15252:                 chomp($configline);
                   15253:                 next if ($configline =~ /^\#/);
                   15254:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15255:                     $managerstab{$configline} = 1;
                   15256:                 }
                   15257:             }
                   15258:             close($config);
                   15259:         }
                   15260:     }
                   15261: }
                   15262: 
1.329     matthew  15263: # ------------- set up temporary directory
                   15264: {
1.1117    foxr     15265:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15266: 
1.11      www      15267: }
                   15268: 
1.1405    raeburn  15269: # ------------- set default texengine (domain default overrides this)
                   15270: {
                   15271:     $deftex = LONCAPA::texengine();
                   15272: }
                   15273: 
1.1416    raeburn  15274: # ------------- set default minimum length for passwords for internal auth users
                   15275: {
                   15276:     $passwdmin = LONCAPA::passwd_min();
                   15277: }
                   15278: 
1.794     albertel 15279: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15280: 				'compress_threshold'=> 20_000,
                   15281:  			        });
1.185     www      15282: 
1.281     www      15283: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15284: $dumpcount=0;
1.958     www      15285: $locknum=0;
1.22      www      15286: 
1.163     harris41 15287: &logtouch();
1.672     albertel 15288: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15289: $readit=1;
1.564     albertel 15290:     {
                   15291: 	use integer;
                   15292: 	my $test=(2**32)+1;
1.568     albertel 15293: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15294: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15295:     }
1.195     www      15296: }
1.1       albertel 15297: }
1.179     www      15298: 
1.1       albertel 15299: 1;
1.191     harris41 15300: __END__
                   15301: 
1.243     albertel 15302: =pod
                   15303: 
1.191     harris41 15304: =head1 NAME
                   15305: 
1.243     albertel 15306: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15307: 
                   15308: =head1 SYNOPSIS
                   15309: 
1.243     albertel 15310: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15311: 
                   15312:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15313: 
1.243     albertel 15314: Common parameters:
                   15315: 
                   15316: =over 4
                   15317: 
                   15318: =item *
                   15319: 
                   15320: $uname : an internal username (if $cname expecting a course Id specifically)
                   15321: 
                   15322: =item *
                   15323: 
                   15324: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15325: 
                   15326: =item *
                   15327: 
                   15328: $symb : a resource instance identifier
                   15329: 
                   15330: =item *
                   15331: 
                   15332: $namespace : the name of a .db file that contains the data needed or
                   15333: being set.
                   15334: 
                   15335: =back
                   15336: 
1.394     bowersj2 15337: =head1 OVERVIEW
1.191     harris41 15338: 
1.394     bowersj2 15339: lonnet provides subroutines which interact with the
                   15340: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15341: about classes, users, and resources.
1.243     albertel 15342: 
                   15343: For many of these objects you can also use this to store data about
                   15344: them or modify them in various ways.
1.191     harris41 15345: 
1.394     bowersj2 15346: =head2 Symbs
1.191     harris41 15347: 
1.394     bowersj2 15348: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15349: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15350: map, the resource number of the resource in the map, and the URL of
                   15351: the resource itself. The latter is somewhat redundant, but might help
                   15352: if maps change.
                   15353: 
                   15354: An example is
                   15355: 
                   15356:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15357: 
                   15358: The respective map entry is
                   15359: 
                   15360:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15361:   title="Problem 2">
                   15362:  </resource>
                   15363: 
                   15364: Symbs are used by the random number generator, as well as to store and
                   15365: restore data specific to a certain instance of for example a problem.
                   15366: 
                   15367: =head2 Storing And Retrieving Data
                   15368: 
                   15369: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15370: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15371: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15372: is is the non-critical message twin of cstore. These functions are for
                   15373: handlers to store a perl hash to a user's permanent data space in an
                   15374: easy manner, and to retrieve it again on another call. It is expected
                   15375: that a handler would use this once at the beginning to retrieve data,
                   15376: and then again once at the end to send only the new data back.
                   15377: 
                   15378: The data is stored in the user's data directory on the user's
                   15379: homeserver under the ID of the course.
                   15380: 
                   15381: The hash that is returned by restore will have all of the previous
                   15382: value for all of the elements of the hash.
                   15383: 
                   15384: Example:
                   15385: 
                   15386:  #creating a hash
                   15387:  my %hash;
                   15388:  $hash{'foo'}='bar';
                   15389: 
                   15390:  #storing it
                   15391:  &Apache::lonnet::cstore(\%hash);
                   15392: 
                   15393:  #changing a value
                   15394:  $hash{'foo'}='notbar';
                   15395: 
                   15396:  #adding a new value
                   15397:  $hash{'bar'}='foo';
                   15398:  &Apache::lonnet::cstore(\%hash);
                   15399: 
                   15400:  #retrieving the hash
                   15401:  my %history=&Apache::lonnet::restore();
                   15402: 
                   15403:  #print the hash
                   15404:  foreach my $key (sort(keys(%history))) {
                   15405:    print("\%history{$key} = $history{$key}");
                   15406:  }
                   15407: 
                   15408: Will print out:
1.191     harris41 15409: 
1.394     bowersj2 15410:  %history{1:foo} = bar
                   15411:  %history{1:keys} = foo:timestamp
                   15412:  %history{1:timestamp} = 990455579
                   15413:  %history{2:bar} = foo
                   15414:  %history{2:foo} = notbar
                   15415:  %history{2:keys} = foo:bar:timestamp
                   15416:  %history{2:timestamp} = 990455580
                   15417:  %history{bar} = foo
                   15418:  %history{foo} = notbar
                   15419:  %history{timestamp} = 990455580
                   15420:  %history{version} = 2
                   15421: 
                   15422: Note that the special hash entries C<keys>, C<version> and
                   15423: C<timestamp> were added to the hash. C<version> will be equal to the
                   15424: total number of versions of the data that have been stored. The
                   15425: C<timestamp> attribute will be the UNIX time the hash was
                   15426: stored. C<keys> is available in every historical section to list which
                   15427: keys were added or changed at a specific historical revision of a
                   15428: hash.
                   15429: 
                   15430: B<Warning>: do not store the hash that restore returns directly. This
                   15431: will cause a mess since it will restore the historical keys as if the
                   15432: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15433: 
1.394     bowersj2 15434: Calling convention:
1.191     harris41 15435: 
1.1225    raeburn  15436:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15437:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15438: 
1.394     bowersj2 15439: For more detailed information, see lonnet specific documentation.
1.191     harris41 15440: 
1.394     bowersj2 15441: =head1 RETURN MESSAGES
1.191     harris41 15442: 
1.394     bowersj2 15443: =over 4
1.191     harris41 15444: 
1.394     bowersj2 15445: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15446: 
1.394     bowersj2 15447: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15448: when the connection is brought back up
1.191     harris41 15449: 
1.394     bowersj2 15450: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15451: for later delivery
1.191     harris41 15452: 
1.967     bisitz   15453: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15454: 
1.394     bowersj2 15455: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15456: that was requested
1.191     harris41 15457: 
1.243     albertel 15458: =back
1.191     harris41 15459: 
1.243     albertel 15460: =head1 PUBLIC SUBROUTINES
1.191     harris41 15461: 
1.243     albertel 15462: =head2 Session Environment Functions
1.191     harris41 15463: 
1.243     albertel 15464: =over 4
1.191     harris41 15465: 
1.394     bowersj2 15466: =item * 
                   15467: X<appenv()>
1.949     raeburn  15468: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15469: the user envirnoment file, and will be restored for each access this
1.620     albertel 15470: user makes during this session, also modifies the %env for the current
1.949     raeburn  15471: process. Optional rolesarrayref - if defined contains a reference to an array
                   15472: of roles which are exempt from the restriction on modifying user.role entries 
                   15473: in the user's environment.db and in %env.    
1.191     harris41 15474: 
                   15475: =item *
1.394     bowersj2 15476: X<delenv()>
1.987     raeburn  15477: B<delenv($delthis,$regexp)>: removes all items from the session
                   15478: environment file that begin with $delthis. If the 
                   15479: optional second arg - $regexp - is true, $delthis is treated as a 
                   15480: regular expression, otherwise \Q$delthis\E is used. 
                   15481: The values are also deleted from the current processes %env.
1.191     harris41 15482: 
1.795     albertel 15483: =item * get_env_multiple($name) 
                   15484: 
                   15485: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15486: values may be defined and end up as an array ref.
                   15487: 
                   15488: returns an array of values
                   15489: 
1.243     albertel 15490: =back
                   15491: 
                   15492: =head2 User Information
1.191     harris41 15493: 
1.243     albertel 15494: =over 4
1.191     harris41 15495: 
                   15496: =item *
1.394     bowersj2 15497: X<queryauthenticate()>
                   15498: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15499: authentication scheme
                   15500: 
                   15501: =item *
1.394     bowersj2 15502: X<authenticate()>
1.1073    raeburn  15503: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15504: authenticate user from domain's lib servers (first use the current
                   15505: one). C<$upass> should be the users password.
1.1073    raeburn  15506: $checkdefauth is optional (value is 1 if a check should be made to
                   15507:    authenticate user using default authentication method, and allow
                   15508:    account creation if username does not have account in the domain).
                   15509: $clientcancheckhost is optional (value is 1 if checking whether the
                   15510:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15511: 
                   15512: =item *
1.394     bowersj2 15513: X<homeserver()>
                   15514: B<homeserver($uname,$udom)>: find the server which has
                   15515: the user's directory and files (there must be only one), this caches
                   15516: the answer, and also caches if there is a borken connection.
1.191     harris41 15517: 
                   15518: =item *
1.394     bowersj2 15519: X<idget()>
1.1300    raeburn  15520: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   15521: a list of student/employee IDs or clicker IDs
                   15522: (student/employee IDs are a unique resource in a domain, there must be 
                   15523: only 1 ID per username, and only 1 username per ID in a specific domain).
                   15524: clickerIDs are not necessarily unique, as students might share clickers.
                   15525: (returns hash: id=>name,id=>name)
1.191     harris41 15526: 
                   15527: =item *
1.394     bowersj2 15528: X<idrget()>
                   15529: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15530: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15531: 
                   15532: =item *
1.394     bowersj2 15533: X<idput()>
1.1300    raeburn  15534: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   15535: names and associated student/employee IDs or clicker IDs.
                   15536: 
                   15537: =item *
                   15538: X<iddel()>
                   15539: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15540: student/employee ID or clicker ID username look-ups from domain.
                   15541: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15542: If no $uhome is provided, it will be determined usig &homeserver()
                   15543: for each user.  If no $namespace is provided, the default is ids.
                   15544: 
                   15545: =item *
                   15546: X<updateclickers()>
                   15547: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15548: clicker ID-to-username look-ups in clickers.db on library server.
                   15549: Permitted actions are add or del (i.e., add or delete). The 
                   15550: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15551: value is an escaped comma-separated list of usernames (for whom the
                   15552: library server is the homeserver), who registered that particular ID.
                   15553: If $critical is true, the update will be sent via &critical, otherwise
                   15554: &reply() will be used.
1.191     harris41 15555: 
                   15556: =item *
1.394     bowersj2 15557: X<rolesinit()>
1.1169    droeschl 15558: B<rolesinit($udom,$username)>: get user privileges.
                   15559: returns user role, first access and timer interval hashes
1.243     albertel 15560: 
                   15561: =item *
1.1171    droeschl 15562: X<privileged()>
                   15563: B<privileged($username,$domain)>: returns a true if user has a
                   15564: privileged and active role (i.e. su or dc), false otherwise.
                   15565: 
                   15566: =item *
1.551     albertel 15567: X<getsection()>
                   15568: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15569: course $cname, return section name/number or '' for "not in course"
                   15570: and '-1' for "no section"
                   15571: 
                   15572: =item *
1.394     bowersj2 15573: X<userenvironment()>
                   15574: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15575: passed in @what from the requested user's environment, returns a hash
                   15576: 
1.858     raeburn  15577: =item * 
                   15578: X<userlog_query()>
1.859     albertel 15579: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15580: activity.log file. %filters defines filters applied when parsing the
                   15581: log file. These can be start or end timestamps, or the type of action
                   15582: - log to look for Login or Logout events, check for Checkin or
                   15583: Checkout, role for role selection. The response is in the form
                   15584: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15585: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15586: 
1.243     albertel 15587: =back
                   15588: 
                   15589: =head2 User Roles
                   15590: 
                   15591: =over 4
                   15592: 
                   15593: =item *
                   15594: 
1.1284    raeburn  15595: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15596: returns codes for allowed actions.
                   15597: 
                   15598: The first argument is required, all others are optional.
                   15599: 
                   15600: $priv is the privilege being checked.
                   15601: $uri contains additional information about what is being checked for access (e.g.,
                   15602: URL, course ID etc.). 
                   15603: $symb is the unique resource instance identifier in a course; if needed,
                   15604: but not provided, it will be retrieved via a call to &symbread(). 
                   15605: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15606: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15607: files).
                   15608: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15609: prevents recursive calls to &allowed.
                   15610: 
1.243     albertel 15611:  F: full access
                   15612:  U,I,K: authentication modes (cxx only)
                   15613:  '': forbidden
                   15614:  1: user needs to choose course
                   15615:  2: browse allowed
1.766     albertel 15616:  A: passphrase authentication needed
1.1284    raeburn  15617:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  15618:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15619: 
                   15620: =item *
                   15621: 
1.1192    raeburn  15622: constructaccess($url,$setpriv) : check for access to construction space URL
                   15623: 
                   15624: See if the owner domain and name in the URL match those in the
                   15625: expected environment.  If so, return three element list
                   15626: ($ownername,$ownerdomain,$ownerhome).
                   15627: 
                   15628: Otherwise return the null string.
                   15629: 
                   15630: If second argument 'setpriv' is true, it assigns the privileges,
                   15631: and returns the same three element list, unless the owner has
                   15632: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15633: in which case the null string is returned.
                   15634: 
                   15635: =item *
                   15636: 
1.1326    raeburn  15637: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15638: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15639: for system, domain, and course level. $uname and $udom are optional (current
                   15640: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15641: 
                   15642: =item *
                   15643: 
1.988     raeburn  15644: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15645: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15646: $type is Course (default) or Community.
1.988     raeburn  15647: If $forcedefault evaluates to true, text returned will be default 
                   15648: text for $type. Otherwise, if this is a course, the text returned 
                   15649: will be a custom name for the role (if defined in the course's 
                   15650: environment).  If no custom name is defined the default is returned.
                   15651:    
1.832     raeburn  15652: =item *
                   15653: 
1.1219    raeburn  15654: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15655: All arguments are optional. Returns a hash of a roles, either for
                   15656: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15657: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15658: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15659: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15660: For each key, value is set to colon-separated start and end times for
                   15661: the role.  If no username and domain are specified, will default to
1.934     raeburn  15662: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15663: of role statuses (active, future or previous), roles 
                   15664: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15665: to restrict the list of roles reported. If no array ref is 
                   15666: provided for types, will default to return only active roles.
1.834     albertel 15667: 
1.1195    raeburn  15668: =item *
                   15669: 
                   15670: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  15671: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   15672: 
                   15673: Additional optional arguments are: $type (if role checking is to be restricted 
                   15674: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  15675: available roles) or future (roles available in the future), and
                   15676: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  15677: have active Domain Coordinator role in course's domain or in additional
                   15678: domains (specified in 'Domains to check for privileged users' in course
                   15679: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15680: 
                   15681: =item *
                   15682: 
                   15683: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15684: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15685: $possdomains and $possroles are optional array refs -- to domains to check and
                   15686: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15687: users' roles.db to check for a dc or su role in any domain. This can be
                   15688: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15689: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15690: this then allows &privileged_by_domain() to be used, which caches the identity
                   15691: of privileged users, eliminating the need for repeated calls to &dump().
                   15692: 
                   15693: =item *
                   15694: 
                   15695: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15696: where the outer hash keys are domains specified in the $possdomains array ref,
                   15697: next inner hash keys are privileged roles specified in the $roles array ref,
                   15698: and the innermost hash contains key = value pairs for username:domain = end:start
                   15699: for active or future "privileged" users with that role in that domain. To avoid
                   15700: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15701: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  15702: 
1.243     albertel 15703: =back
                   15704: 
                   15705: =head2 User Modification
                   15706: 
                   15707: =over 4
                   15708: 
                   15709: =item *
                   15710: 
1.957     raeburn  15711: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15712: user for the level given by URL.  Optional start and end dates (leave empty
                   15713: string or zero for "no date")
1.191     harris41 15714: 
                   15715: =item *
                   15716: 
1.243     albertel 15717: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15718: change a users, password, possible return values are: ok,
                   15719: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15720: refused
1.191     harris41 15721: 
                   15722: =item *
                   15723: 
1.243     albertel 15724: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15725: 
                   15726: =item *
                   15727: 
1.1058    raeburn  15728: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15729:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15730: 
                   15731: will update user information (firstname,middlename,lastname,generation,
                   15732: permanentemail), and if forceid is true, student/employee ID also.
                   15733: A user's institutional affiliation(s) can also be updated.
                   15734: User information fields will not be overwritten with empty entries 
                   15735: unless the field is included in the $candelete array reference.
                   15736: This array is included when a single user is modified via "Manage Users",
                   15737: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15738: 
                   15739: =item *
                   15740: 
1.286     matthew  15741: modifystudent
                   15742: 
1.957     raeburn  15743: modify a student's enrollment and identification information.
1.1235    raeburn  15744: The course id is resolved based on the current user's environment.  
                   15745: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15746: associated with a course.
                   15747: 
1.297     matthew  15748: This call is essentially a wrapper for lonnet::modifyuser and
                   15749: lonnet::modify_student_enrollment
1.286     matthew  15750: 
                   15751: Inputs: 
                   15752: 
                   15753: =over 4
                   15754: 
1.957     raeburn  15755: =item B<$udom> Student's loncapa domain
1.286     matthew  15756: 
1.957     raeburn  15757: =item B<$uname> Student's loncapa login name
1.286     matthew  15758: 
1.964     bisitz   15759: =item B<$uid> Student/Employee ID
1.286     matthew  15760: 
1.957     raeburn  15761: =item B<$umode> Student's authentication mode
1.286     matthew  15762: 
1.957     raeburn  15763: =item B<$upass> Student's password
1.286     matthew  15764: 
1.957     raeburn  15765: =item B<$first> Student's first name
1.286     matthew  15766: 
1.957     raeburn  15767: =item B<$middle> Student's middle name
1.286     matthew  15768: 
1.957     raeburn  15769: =item B<$last> Student's last name
1.286     matthew  15770: 
1.957     raeburn  15771: =item B<$gene> Student's generation
1.286     matthew  15772: 
1.957     raeburn  15773: =item B<$usec> Student's section in course
1.286     matthew  15774: 
                   15775: =item B<$end> Unix time of the roles expiration
                   15776: 
                   15777: =item B<$start> Unix time of the roles start date
                   15778: 
                   15779: =item B<$forceid> If defined, allow $uid to be changed
                   15780: 
                   15781: =item B<$desiredhome> server to use as home server for student
                   15782: 
1.957     raeburn  15783: =item B<$email> Student's permanent e-mail address
                   15784: 
                   15785: =item B<$type> Type of enrollment (auto or manual)
                   15786: 
1.963     raeburn  15787: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15788: 
                   15789: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15790: 
1.963     raeburn  15791: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15792: 
1.963     raeburn  15793: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15794: 
1.1216    raeburn  15795: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15796: 
                   15797: =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  15798: 
1.286     matthew  15799: =back
1.297     matthew  15800: 
                   15801: =item *
                   15802: 
                   15803: modify_student_enrollment
                   15804: 
1.1235    raeburn  15805: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15806: 'role.request.course' must be defined for this function to proceed.
                   15807: 
                   15808: Inputs:
                   15809: 
                   15810: =over 4
                   15811: 
1.1235    raeburn  15812: =item $udom, student's domain
1.297     matthew  15813: 
1.1235    raeburn  15814: =item $uname, student's name
1.297     matthew  15815: 
1.1235    raeburn  15816: =item $uid, student's user id
1.297     matthew  15817: 
1.1235    raeburn  15818: =item $first, student's first name
1.297     matthew  15819: 
                   15820: =item $middle
                   15821: 
                   15822: =item $last
                   15823: 
                   15824: =item $gene
                   15825: 
                   15826: =item $usec
                   15827: 
                   15828: =item $end
                   15829: 
                   15830: =item $start
                   15831: 
1.957     raeburn  15832: =item $type
                   15833: 
                   15834: =item $locktype
                   15835: 
                   15836: =item $cid
                   15837: 
                   15838: =item $selfenroll
                   15839: 
                   15840: =item $context
                   15841: 
1.1216    raeburn  15842: =item $credits, number of credits student will earn from this class
                   15843: 
1.1314    raeburn  15844: =item $instsec, institutional course section code for student
                   15845: 
1.297     matthew  15846: =back
                   15847: 
1.191     harris41 15848: 
                   15849: =item *
                   15850: 
1.243     albertel 15851: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15852: custom role; give a custom role to a user for the level given by URL.  Specify
                   15853: name and domain of role author, and role name
1.191     harris41 15854: 
                   15855: =item *
                   15856: 
1.243     albertel 15857: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15858: 
                   15859: =item *
                   15860: 
1.243     albertel 15861: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15862: 
                   15863: =back
                   15864: 
                   15865: =head2 Course Infomation
                   15866: 
                   15867: =over 4
1.191     harris41 15868: 
                   15869: =item *
                   15870: 
1.1118    foxr     15871: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15872: specified course id, including all environment settings for the
                   15873: course, the description of the course will be in the hash under the
                   15874: key 'description'
1.191     harris41 15875: 
1.1118    foxr     15876: $options is an optional parameter that if supplied is a hash reference that controls
                   15877: what how this function works.  It has the following key/values:
                   15878: 
                   15879: =over 4
                   15880: 
                   15881: =item freshen_cache
                   15882: 
                   15883: If defined, and the environment cache for the course is valid, it is 
                   15884: returned in the returned hash.
                   15885: 
                   15886: =item one_time
                   15887: 
                   15888: If defined, the last cache time is set to _now_
                   15889: 
                   15890: =item user
                   15891: 
                   15892: If defined, the supplied username is used instead of the current user.
                   15893: 
                   15894: 
                   15895: =back
                   15896: 
1.191     harris41 15897: =item *
                   15898: 
1.624     albertel 15899: resdata($name,$domain,$type,@which) : request for current parameter
                   15900: setting for a specific $type, where $type is either 'course' or 'user',
                   15901: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15902: answers for 10 minutes.
1.243     albertel 15903: 
1.877     foxr     15904: =item *
                   15905: 
                   15906: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15907: data base, returning a hash that is keyed by the resource name and has
                   15908: values that are the resource value.  I believe that the timestamps and
                   15909: versions are also returned.
                   15910: 
1.1236    raeburn  15911: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15912: supplemental content area. This routine caches the number of files for 
                   15913: 10 minutes.
                   15914: 
1.243     albertel 15915: =back
                   15916: 
                   15917: =head2 Course Modification
                   15918: 
                   15919: =over 4
1.191     harris41 15920: 
                   15921: =item *
                   15922: 
1.243     albertel 15923: writecoursepref($courseid,%prefs) : write preferences (environment
                   15924: database) for a course
1.191     harris41 15925: 
                   15926: =item *
                   15927: 
1.1011    raeburn  15928: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15929: 
                   15930: =item *
                   15931: 
1.1038    raeburn  15932: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15933: 
1.1167    droeschl 15934: =item *
                   15935: 
                   15936: is_course($courseid), is_course($cdom, $cnum)
                   15937: 
                   15938: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15939: two component version $cdom, $cnum. It checks if the specified course exists.
                   15940: 
                   15941: Returns:
                   15942:     undef if the course doesn't exist, otherwise
                   15943:     in scalar context the combined courseid.
                   15944:     in list context the two components of the course identifier, domain and 
                   15945:     courseid.    
                   15946: 
1.243     albertel 15947: =back
                   15948: 
1.1401    raeburn  15949: =head2 Bubblesheet Configuration
                   15950: 
                   15951: =over 4
                   15952: 
                   15953: =item *
                   15954: 
                   15955: get_scantron_config($which)
                   15956: 
                   15957: $which - the name of the configuration to parse from the file.
                   15958: 
                   15959: Parses and returns the bubblesheet configuration line selected as a
                   15960: hash of configuration file fields.
                   15961: 
                   15962: 
                   15963: Returns:
                   15964:     If the named configuration is not in the file, an empty
                   15965:     hash is returned.
                   15966: 
                   15967:     a hash with the fields
                   15968:       name         - internal name for the this configuration setup
                   15969:       description  - text to display to operator that describes this config
                   15970:       CODElocation - if 0 or the string 'none'
                   15971:                           - no CODE exists for this config
                   15972:                      if -1 || the string 'letter'
                   15973:                           - a CODE exists for this config and is
                   15974:                             a string of letters
                   15975:                      Unsupported value (but planned for future support)
                   15976:                           if a positive integer
                   15977:                                - The CODE exists as the first n items from
                   15978:                                  the question section of the form
                   15979:                           if the string 'number'
                   15980:                                - The CODE exists for this config and is
                   15981:                                  a string of numbers
                   15982:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15983:                      the CODE starts
                   15984:       CODElength  - length of the CODE
                   15985:       IDstart     - column where the student/employee ID starts
                   15986:       IDlength    - length of the student/employee ID info
                   15987:       Qstart      - column where the information from the bubbled
                   15988:                     'questions' start
                   15989:       Qlength     - number of columns comprising a single bubble line from
                   15990:                     the sheet. (usually either 1 or 10)
                   15991:       Qon         - either a single character representing the character used
                   15992:                     to signal a bubble was chosen in the positional setup, or
                   15993:                     the string 'letter' if the letter of the chosen bubble is
                   15994:                     in the final, or 'number' if a number representing the
                   15995:                     chosen bubble is in the file (1->A 0->J)
                   15996:       Qoff        - the character used to represent that a bubble was
                   15997:                     left blank
                   15998:       PaperID     - if the scanning process generates a unique number for each
                   15999:                     sheet scanned the column that this ID number starts in
                   16000:       PaperIDlength - number of columns that comprise the unique ID number
                   16001:                       for the sheet of paper
                   16002:       FirstName   - column that the first name starts in
                   16003:       FirstNameLength - number of columns that the first name spans
                   16004:       LastName    - column that the last name starts in
                   16005:       LastNameLength - number of columns that the last name spans
                   16006:       BubblesPerRow - number of bubbles available in each row used to
                   16007:                       bubble an answer. (If not specified, 10 assumed).
                   16008: 
                   16009: 
                   16010: =item *
                   16011: 
                   16012: get_scantronformat_file($cdom)
                   16013: 
                   16014: $cdom - the course's domain (optional); if not supplied, uses
                   16015: domain for current $env{'request.course.id'}.
                   16016: 
                   16017: Returns an array containing lines from the scantron format file for
                   16018: the domain of the course.
                   16019: 
                   16020: If a url for a custom.tab file is listed in domain's configuration.db,
                   16021: lines are from this file.
                   16022: 
                   16023: Otherwise, if a default.tab has been published in RES space by the
                   16024: domainconfig user, lines are from this file.
                   16025: 
                   16026: Otherwise, fall back to getting lines from the legacy file on the
                   16027: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16028: 
                   16029: =back
                   16030: 
1.243     albertel 16031: =head2 Resource Subroutines
                   16032: 
                   16033: =over 4
1.191     harris41 16034: 
                   16035: =item *
                   16036: 
1.243     albertel 16037: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16038: 
                   16039: =item *
                   16040: 
1.243     albertel 16041: repcopy($filename) : subscribes to the requested file, and attempts to
                   16042: replicate from the owning library server, Might return
1.607     raeburn  16043: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16044: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16045: resource. Expects the local filesystem pathname
                   16046: (/home/httpd/html/res/....)
                   16047: 
                   16048: =back
                   16049: 
                   16050: =head2 Resource Information
                   16051: 
                   16052: =over 4
1.191     harris41 16053: 
                   16054: =item *
                   16055: 
1.1228    raeburn  16056: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16057: and returns the value of a variety of different possible values,
                   16058: $varname should be a request string, and the other parameters can be
                   16059: used to specify who and what one is asking about. Ordinarily, $cid 
                   16060: does not need to be specified, as it is retrived from 
                   16061: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16062: within lonuserstate::loadmap() when initializing a course, before
                   16063: $env{'request.course.id'} has been set, so it needs to be provided
                   16064: in that one case.
1.243     albertel 16065: 
                   16066: Possible values for $varname are environment.lastname (or other item
                   16067: from the envirnment hash), user.name (or someother aspect about the
                   16068: user), resource.0.maxtries (or some other part and parameter of a
                   16069: resource)
1.204     albertel 16070: 
                   16071: =item *
                   16072: 
1.243     albertel 16073: directcondval($number) : get current value of a condition; reads from a state
                   16074: string
1.204     albertel 16075: 
                   16076: =item *
                   16077: 
1.243     albertel 16078: condval($condidx) : value of condition index based on state
1.204     albertel 16079: 
                   16080: =item *
                   16081: 
1.1362    raeburn  16082: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16083: resource's metadata, $what should be either a specific key, or either
                   16084: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  16085: packages that this resource currently uses, the last 3 arguments are 
                   16086: only used internally for recursive metadata.
                   16087: 
                   16088: the toolsymb is only used where the uri is for an external tool (for which
                   16089: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16090: 
1.1371    raeburn  16091: this function automatically caches all requests except any made recursively
                   16092: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   16093: defined).
1.191     harris41 16094: 
                   16095: =item *
                   16096: 
1.243     albertel 16097: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16098: network of library servers; returns file handle of where SQL and regex results
                   16099: will be stored for query
1.191     harris41 16100: 
                   16101: =item *
                   16102: 
1.1282    raeburn  16103: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   16104: return symbolic list entry (all arguments optional). 
                   16105: 
                   16106: Args: filename is the filename (including path) for the file for which a symb 
                   16107: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   16108: to check access status if more than one resource was found in the bighash 
                   16109: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   16110: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   16111: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16112: cause possible symbs to be checked to determine if they are subject to content
                   16113: blocking, if so they will not be included as possible symbs; possibles is a
                   16114: ref to a hash, which, as a side effect, will be populated with all possible 
                   16115: symbs (content blocking not tested).
                   16116:  
1.243     albertel 16117: returns the data handle
1.191     harris41 16118: 
                   16119: =item *
                   16120: 
1.1190    raeburn  16121: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   16122: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16123: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  16124: on failure, user must be in a course, as it assumes the existence of
                   16125: the course initial hash, and uses $env('request.course.id'}.  The third
                   16126: arg is an optional reference to a scalar.  If this arg is passed in the 
                   16127: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16128: encrypted; otherwise it will be null.  
1.191     harris41 16129: 
                   16130: =item *
                   16131: 
1.243     albertel 16132: symbclean($symb) : removes versions numbers from a symb, returns the
                   16133: cleaned symb
1.191     harris41 16134: 
                   16135: =item *
                   16136: 
1.243     albertel 16137: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16138: course map, user must be in a course for it to work.
1.191     harris41 16139: 
                   16140: =item *
                   16141: 
1.243     albertel 16142: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16143: 
                   16144: =item *
                   16145: 
1.243     albertel 16146: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16147: a random seed, all arguments are optional, if they aren't sent it uses the
                   16148: environment to derive them. Note: if symb isn't sent and it can't get one
                   16149: from &symbread it will use the current time as its return value
1.191     harris41 16150: 
                   16151: =item *
                   16152: 
1.243     albertel 16153: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16154: unfakeable, receipt
1.191     harris41 16155: 
                   16156: =item *
                   16157: 
1.620     albertel 16158: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16159: 
                   16160: =item *
                   16161: 
1.243     albertel 16162: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16163: 
                   16164: =item *
                   16165: 
1.243     albertel 16166: 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 16167: 
                   16168: =item *
                   16169: 
1.243     albertel 16170: 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 16171: 
                   16172: =item *
                   16173: 
1.243     albertel 16174: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16175: 
                   16176: =item *
                   16177: 
1.243     albertel 16178: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16179: forcing spreadsheet to reevaluate the resource scores next time.
                   16180: 
1.1195    raeburn  16181: =item * 
                   16182: 
1.1196    raeburn  16183: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16184: when viewing in course context.
1.1195    raeburn  16185: 
1.1196    raeburn  16186:  input: six args -- filename (decluttered), course number, course domain,
                   16187:                     url, symb (if registered) and group (if this is a 
                   16188:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  16189: 
1.1196    raeburn  16190:  output: array of five scalars --
1.1195    raeburn  16191:          $cfile -- url for file editing if editable on current server
                   16192:          $home -- homeserver of resource (i.e., for author if published,
                   16193:                                           or course if uploaded.).
                   16194:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  16195:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   16196:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  16197: 
                   16198: =item *
                   16199: 
                   16200: is_course_upload($file,$cnum,$cdom)
                   16201: 
                   16202: Used in course context to determine if current file was uploaded to 
                   16203: the course (i.e., would be found in /userfiles/docs on the course's 
                   16204: homeserver.
                   16205: 
                   16206:   input: 3 args -- filename (decluttered), course number and course domain.
                   16207:   output: boolean -- 1 if file was uploaded.
                   16208: 
1.243     albertel 16209: =back
                   16210: 
                   16211: =head2 Storing/Retreiving Data
                   16212: 
                   16213: =over 4
1.191     harris41 16214: 
                   16215: =item *
                   16216: 
1.1269    raeburn  16217: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   16218: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16219: the remaining args aren't required and if they aren't passed or are '' they will
                   16220: be derived from the env (with the exception of $laststore, which is an 
                   16221: optional arg used when a user's submission is stored in grading).
                   16222: $laststore is $version=$timestamp, where $version is the most recent version
                   16223: number retrieved for the corresponding $symb in the $namespace db file, and
                   16224: $timestamp is the timestamp for that transaction (UNIX time).
                   16225: $laststore is currently only passed when cstore() is called by 
                   16226: structuretags::finalize_storage().
1.191     harris41 16227: 
                   16228: =item *
                   16229: 
1.1269    raeburn  16230: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   16231: but uses critical subroutine
1.191     harris41 16232: 
                   16233: =item *
                   16234: 
1.243     albertel 16235: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16236: all args are optional
1.191     harris41 16237: 
                   16238: =item *
                   16239: 
1.717     albertel 16240: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16241: dumps the complete (or key matching regexp) namespace into a hash
                   16242: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16243: normally &store()ed into
                   16244: 
                   16245: $range should be either an integer '100' (give me the first 100
                   16246:                                            matching records)
                   16247:               or be  two integers sperated by a - with no spaces
                   16248:                  '30-50' (give me the 30th through the 50th matching
                   16249:                           records)
                   16250: 
                   16251: 
                   16252: =item *
                   16253: 
1.1269    raeburn  16254: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16255: replaces a &store() version of data with a replacement set of data
                   16256: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  16257: reference. If $tolog is true, the transaction is logged in the courselog
                   16258: with an action=PUTSTORE.
1.717     albertel 16259: 
                   16260: =item *
                   16261: 
1.243     albertel 16262: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16263: works very similar to store/cstore, but all data is stored in a
                   16264: temporary location and can be reset using tmpreset, $storehash should
                   16265: be a hash reference, returns nothing on success
1.191     harris41 16266: 
                   16267: =item *
                   16268: 
1.243     albertel 16269: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16270: similar to restore, but all data is stored in a temporary location and
                   16271: can be reset using tmpreset. Returns a hash of values on success,
                   16272: error string otherwise.
1.191     harris41 16273: 
                   16274: =item *
                   16275: 
1.243     albertel 16276: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16277: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16278: 
                   16279: =item *
                   16280: 
1.243     albertel 16281: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16282: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16283: 
                   16284: =item *
                   16285: 
1.243     albertel 16286: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16287: namesp ($udom and $uname are optional)
1.191     harris41 16288: 
                   16289: =item *
                   16290: 
1.702     albertel 16291: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16292: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16293: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16294: 
1.702     albertel 16295: $range should be either an integer '100' (give me the first 100
                   16296:                                            matching records)
                   16297:               or be  two integers sperated by a - with no spaces
                   16298:                  '30-50' (give me the 30th through the 50th matching
                   16299:                           records)
1.449     matthew  16300: =item *
                   16301: 
                   16302: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16303: $store can be a scalar, an array reference, or if the amount to be 
                   16304: incremented is > 1, a hash reference.
                   16305: 
                   16306: ($udom and $uname are optional)
1.191     harris41 16307: 
                   16308: =item *
                   16309: 
1.243     albertel 16310: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16311: ($udom and $uname are optional)
1.191     harris41 16312: 
                   16313: =item *
                   16314: 
1.243     albertel 16315: cput($namespace,$storehash,$udom,$uname) : critical put
                   16316: ($udom and $uname are optional)
1.191     harris41 16317: 
                   16318: =item *
                   16319: 
1.748     albertel 16320: newput($namespace,$storehash,$udom,$uname) :
                   16321: 
                   16322: Attempts to store the items in the $storehash, but only if they don't
                   16323: currently exist, if this succeeds you can be certain that you have 
                   16324: successfully created a new key value pair in the $namespace db.
                   16325: 
                   16326: 
                   16327: Args:
                   16328:  $namespace: name of database to store values to
                   16329:  $storehash: hashref to store to the db
                   16330:  $udom: (optional) domain of user containing the db
                   16331:  $uname: (optional) name of user caontaining the db
                   16332: 
                   16333: Returns:
                   16334:  'ok' -> succeeded in storing all keys of $storehash
                   16335:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16336:                         least <key> already existed in the db (other
                   16337:                         requested keys may also already exist)
1.967     bisitz   16338:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16339:  'con_lost' -> unable to contact request server
                   16340:  'refused' -> action was not allowed by remote machine
                   16341: 
                   16342: 
                   16343: =item *
                   16344: 
1.243     albertel 16345: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16346: reference filled in from namesp (encrypts the return communication)
                   16347: ($udom and $uname are optional)
1.191     harris41 16348: 
                   16349: =item *
                   16350: 
1.243     albertel 16351: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16352: critical subroutine
                   16353: 
1.806     raeburn  16354: =item *
                   16355: 
1.860     raeburn  16356: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16357: array reference filled in from namespace found in domain level on either
                   16358: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16359: 
                   16360: =item *
                   16361: 
1.860     raeburn  16362: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16363: domain level either on specified domain server ($uhome) or primary domain 
                   16364: server ($udom and $uhome are optional)
1.806     raeburn  16365: 
1.943     raeburn  16366: =item * 
                   16367: 
1.1240    raeburn  16368: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16369: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16370: the target domain.
                   16371: 
                   16372: May also include additional key => value pairs for the following groups:
                   16373: 
                   16374: =over
                   16375: 
                   16376: =item
                   16377: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16378: 
                   16379: =over
                   16380: 
                   16381: =item defaultquota, authorquota
                   16382: 
                   16383: =back
                   16384: 
                   16385: =item
                   16386: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16387: portfolio for users).
                   16388: 
                   16389: =over
                   16390: 
                   16391: =item
                   16392: aboutme, blog, webdav, portfolio
                   16393: 
                   16394: =back
                   16395: 
                   16396: =item
                   16397: requestcourses: ability to request courses, and how requests are processed.
                   16398: 
                   16399: =over
                   16400: 
                   16401: =item
1.1305    raeburn  16402: official, unofficial, community, textbook, placement
1.1240    raeburn  16403: 
                   16404: =back
                   16405: 
                   16406: =item
                   16407: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16408: 
                   16409: =over
                   16410: 
                   16411: =item
1.1256    raeburn  16412: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16413: 
                   16414: =back
                   16415: 
                   16416: =item
                   16417: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16418: for course's uploaded content.
                   16419: 
                   16420: =over
                   16421: 
                   16422: =item
1.1246    raeburn  16423: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16424: communityquota, textbookquota, placementquota
1.1240    raeburn  16425: 
                   16426: =back
                   16427: 
                   16428: =item
                   16429: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16430: on your servers.
                   16431: 
                   16432: =over
                   16433: 
                   16434: =item 
                   16435: remotesessions, hostedsessions
                   16436: 
                   16437: =back
                   16438: 
                   16439: =back
                   16440: 
                   16441: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16442: utility to create a configuration.db file on a domain's primary library server 
                   16443: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16444: -- corresponding values are authentication type (internal, krb4, krb5,
                   16445: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16446: will be available. Values are retrieved from cache (if current), unless the
                   16447: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16448: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16449: 
                   16450: Typical usage:
1.943     raeburn  16451: 
1.1240    raeburn  16452: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16453: 
1.243     albertel 16454: =back
                   16455: 
                   16456: =head2 Network Status Functions
                   16457: 
                   16458: =over 4
1.191     harris41 16459: 
                   16460: =item *
                   16461: 
1.1137    raeburn  16462: dirlist() : return directory list based on URI (first arg).
                   16463: 
                   16464: Inputs: 1 required, 5 optional.
                   16465: 
                   16466: =over
                   16467: 
                   16468: =item 
                   16469: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16470: 
                   16471: =item
                   16472: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16473: 
                   16474: =item
                   16475: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16476: 
                   16477: =item
                   16478: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16479: 
                   16480: =item
                   16481: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16482: 
                   16483: =item 
                   16484: $alternateRoot - path to prepend in place of path from $uri.
                   16485: 
                   16486: =back
                   16487: 
                   16488: Returns: Array of up to two items.
                   16489: 
                   16490: =over
                   16491: 
                   16492: a reference to an array of files/subdirectories
                   16493: 
                   16494: =over
                   16495: 
                   16496: Each element in the array of files/subdirectories is a & separated list of
                   16497: item name and the result of running stat on the item.  If dirlist was requested
                   16498: for a file instead of a directory, the item name will be ''. For a directory 
                   16499: listing, if the item is a metadata file, the element will end &N&M 
                   16500: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16501: default copyright set (1).  
                   16502: 
                   16503: =back
                   16504: 
                   16505: a scalar containing error condition (if encountered).
                   16506: 
                   16507: =over
                   16508: 
                   16509: =item 
                   16510: no_host (no homeserver identified for $username:$domain).
                   16511: 
                   16512: =item 
                   16513: no_such_host (server contacted for listing not identified as valid host).
                   16514: 
                   16515: =item 
                   16516: con_lost (connection to remote server failed).
                   16517: 
                   16518: =item 
                   16519: refused (invalid $username:$domain received on lond side).
                   16520: 
                   16521: =item 
                   16522: no_such_dir (directory at specified path on lond side does not exist). 
                   16523: 
                   16524: =item 
                   16525: empty (directory at specified path on lond side is empty).
                   16526: 
                   16527: =over
                   16528: 
                   16529: This is currently not encountered because the &ls3, &ls2, 
                   16530: &ls (_handler) routines on the lond side do not filter out
                   16531: . and .. from a directory listing. 
                   16532: 
                   16533: =back
                   16534: 
                   16535: =back
                   16536: 
                   16537: =back
1.191     harris41 16538: 
                   16539: =item *
                   16540: 
1.243     albertel 16541: spareserver() : find server with least workload from spare.tab
                   16542: 
1.986     foxr     16543: 
                   16544: =item *
                   16545: 
                   16546: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16547: if there is no corresponding loncapa host.
                   16548: 
1.243     albertel 16549: =back
                   16550: 
1.986     foxr     16551: 
1.243     albertel 16552: =head2 Apache Request
                   16553: 
                   16554: =over 4
1.191     harris41 16555: 
                   16556: =item *
                   16557: 
1.243     albertel 16558: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16559: localhost, posts hash
                   16560: 
                   16561: =back
                   16562: 
                   16563: =head2 Data to String to Data
                   16564: 
                   16565: =over 4
1.191     harris41 16566: 
                   16567: =item *
                   16568: 
1.243     albertel 16569: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16570: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16571: 
                   16572: =item *
                   16573: 
1.243     albertel 16574: hashref2str($hashref) : convert a hashref into a string complete with
                   16575: escaping and '=' and '&' separators, supports elements that are
                   16576: arrayrefs and hashrefs
1.191     harris41 16577: 
                   16578: =item *
                   16579: 
1.243     albertel 16580: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16581: with escaping and '&' separators, supports elements that are arrayrefs
                   16582: and hashrefs
1.191     harris41 16583: 
                   16584: =item *
                   16585: 
1.243     albertel 16586: str2hash($string) : convert string to hash using unescaping and
                   16587: splitting on '=' and '&', supports elements that are arrayrefs and
                   16588: hashrefs
1.191     harris41 16589: 
                   16590: =item *
                   16591: 
1.243     albertel 16592: str2array($string) : convert string to hash using unescaping and
                   16593: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16594: 
                   16595: =back
                   16596: 
                   16597: =head2 Logging Routines
                   16598: 
                   16599: 
                   16600: These routines allow one to make log messages in the lonnet.log and
                   16601: lonnet.perm logfiles.
1.191     harris41 16602: 
1.1119    foxr     16603: =over 4
                   16604: 
1.191     harris41 16605: =item *
                   16606: 
1.243     albertel 16607: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16608: 
                   16609: =item *
                   16610: 
1.243     albertel 16611: logthis() : append message to the normal lonnet.log file, it gets
                   16612: preiodically rolled over and deleted.
1.191     harris41 16613: 
                   16614: =item *
                   16615: 
1.243     albertel 16616: logperm() : append a permanent message to lonnet.perm.log, this log
                   16617: file never gets deleted by any automated portion of the system, only
                   16618: messages of critical importance should go in here.
                   16619: 
1.1119    foxr     16620: 
1.243     albertel 16621: =back
                   16622: 
                   16623: =head2 General File Helper Routines
                   16624: 
                   16625: =over 4
1.191     harris41 16626: 
                   16627: =item *
                   16628: 
1.481     raeburn  16629: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16630: (a) files in /uploaded
                   16631:   (i) If a local copy of the file exists - 
                   16632:       compares modification date of local copy with last-modified date for 
                   16633:       definitive version stored on home server for course. If local copy is 
                   16634:       stale, requests a new version from the home server and stores it. 
                   16635:       If the original has been removed from the home server, then local copy 
                   16636:       is unlinked.
                   16637:   (ii) If local copy does not exist -
                   16638:       requests the file from the home server and stores it. 
                   16639:   
                   16640:   If $caller is 'uploadrep':  
                   16641:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16642:     for request for files originally uploaded via DOCS. 
                   16643:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16644:   
                   16645:   Otherwise:
                   16646:      This indicates a call from the content generation phase of the request.
                   16647:      -  returns the entire contents of the file or -1.
                   16648:      
                   16649: (b) files in /res
                   16650:    - returns the entire contents of a file or -1; 
                   16651:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16652: 
1.712     albertel 16653: 
                   16654: =item *
                   16655: 
                   16656: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16657:                   reference
                   16658: 
                   16659: returns either a stat() list of data about the file or an empty list
                   16660: if the file doesn't exist or couldn't find out about it (connection
                   16661: problems or user unknown)
                   16662: 
1.191     harris41 16663: =item *
                   16664: 
1.243     albertel 16665: filelocation($dir,$file) : returns file system location of a file
                   16666: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16667: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16668: and a file of ../bob will become /a/bob)
1.191     harris41 16669: 
                   16670: =item *
                   16671: 
                   16672: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16673: filelocation except for hrefs
                   16674: 
                   16675: =item *
                   16676: 
1.1261    raeburn  16677: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16678: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16679: 
1.243     albertel 16680: =back
                   16681: 
1.608     albertel 16682: =head2 Usererfile file routines (/uploaded*)
                   16683: 
                   16684: =over 4
                   16685: 
                   16686: =item *
                   16687: 
                   16688: userfileupload(): main rotine for putting a file in a user or course's
                   16689:                   filespace, arguments are,
                   16690: 
1.620     albertel 16691:  formname - required - this is the name of the element in $env where the
1.608     albertel 16692:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16693:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16694:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16695:  context - if coursedoc, store the file in the course of the active role
                   16696:              of the current user; 
                   16697:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16698:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16699:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16700:          if undefined, it will be placed in "unknown"
                   16701: 
                   16702:  (This routine calls clean_filename() to remove any dangerous
                   16703:  characters from the filename, and then calls finuserfileupload() to
                   16704:  complete the transaction)
                   16705: 
                   16706:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16707:  and /adm/notfound.html if unsuccessful
                   16708: 
                   16709: =item *
                   16710: 
                   16711: clean_filename(): routine for cleaing a filename up for storage in
                   16712:                  userfile space, argument is:
                   16713: 
                   16714:  filename - proposed filename
                   16715: 
                   16716: returns: the new clean filename
                   16717: 
                   16718: =item *
                   16719: 
1.1090    raeburn  16720: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16721: userspace, probably shouldn't be called directly
                   16722: 
                   16723:   docuname: username or courseid of destination for the file
                   16724:   docudom: domain of user/course of destination for the file
                   16725:   formname: same as for userfileupload()
1.1090    raeburn  16726:   fname: filename (including subdirectories) for the file
                   16727:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  16728:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16729:   allfiles: reference to hash used to store objects found by parser
                   16730:   codebase: reference to hash used for codebases of java objects found by parser
                   16731:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16732:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16733:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16734:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16735:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16736:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16737:   mimetype: reference to scalar to accommodate mime type determined
                   16738:             from File::MMagic if $parser = parse.
1.608     albertel 16739: 
                   16740:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16741:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16742:  was 'overwrite').
                   16743:  
1.608     albertel 16744: 
                   16745: =item *
                   16746: 
                   16747: renameuserfile(): renames an existing userfile to a new name
                   16748: 
                   16749:   Args:
                   16750:    docuname: username or courseid of destination for the file
                   16751:    docudom: domain of user/course of destination for the file
                   16752:    old: current file name (including any subdirs under userfiles)
                   16753:    new: desired file name (including any subdirs under userfiles)
                   16754: 
                   16755: =item *
                   16756: 
                   16757: mkdiruserfile(): creates a directory is a userfiles dir
                   16758: 
                   16759:   Args:
                   16760:    docuname: username or courseid of destination for the file
                   16761:    docudom: domain of user/course of destination for the file
                   16762:    dir: dir to create (including any subdirs under userfiles)
                   16763: 
                   16764: =item *
                   16765: 
                   16766: removeuserfile(): removes a file that exists in userfiles
                   16767: 
                   16768:   Args:
                   16769:    docuname: username or courseid of destination for the file
                   16770:    docudom: domain of user/course of destination for the file
                   16771:    fname: filname to delete (including any subdirs under userfiles)
                   16772: 
                   16773: =item *
                   16774: 
                   16775: removeuploadedurl(): convience function for removeuserfile()
                   16776: 
                   16777:   Args:
                   16778:    url:  a full /uploaded/... url to delete
                   16779: 
1.747     albertel 16780: =item * 
                   16781: 
                   16782: get_portfile_permissions():
                   16783:   Args:
                   16784:     domain: domain of user or course contain the portfolio files
                   16785:     user: name of user or num of course contain the portfolio files
                   16786:   Returns:
                   16787:     hashref of a dump of the proper file_permissions.db
                   16788:    
                   16789: 
                   16790: =item * 
                   16791: 
                   16792: get_access_controls():
                   16793: 
                   16794: Args:
                   16795:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16796:   group: (optional) the group you want the files associated with
                   16797:   file: (optional) the file you want access info on
                   16798: 
                   16799: Returns:
1.749     raeburn  16800:     a hash (keys are file names) of hashes containing
                   16801:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16802:         values are XML containing access control settings (see below) 
1.747     albertel 16803: 
                   16804: Internal notes:
                   16805: 
1.749     raeburn  16806:  access controls are stored in file_permissions.db as key=value pairs.
                   16807:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16808:         where scope -> public,guest,course,group,domains or users.
                   16809:               end -> UNIX time for end of access (0 -> no end date)
                   16810:               start -> UNIX time for start of access
                   16811: 
                   16812:     value -> XML description of access control
                   16813:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16814:             <start></start>
                   16815:             <end></end>
                   16816: 
                   16817:             <password></password>  for scope type = guest
                   16818: 
                   16819:             <domain></domain>     for scope type = course or group
                   16820:             <number></number>
                   16821:             <roles id="">
                   16822:              <role></role>
                   16823:              <access></access>
                   16824:              <section></section>
                   16825:              <group></group>
                   16826:             </roles>
                   16827: 
                   16828:             <dom></dom>         for scope type = domains
                   16829: 
                   16830:             <users>             for scope type = users
                   16831:              <user>
                   16832:               <uname></uname>
                   16833:               <udom></udom>
                   16834:              </user>
                   16835:             </users>
                   16836:            </scope> 
                   16837:               
                   16838:  Access data is also aggregated for each file in an additional key=value pair:
                   16839:  key -> path to file/file_name\0accesscontrol 
                   16840:  value -> reference to hash
                   16841:           hash contains key = value pairs
                   16842:           where key = uniqueID:scope_end_start
                   16843:                 value = UNIX time record was last updated
                   16844: 
                   16845:           Used to improve speed of look-ups of access controls for each file.  
                   16846:  
                   16847:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16848: 
1.1198    raeburn  16849: =item *
                   16850: 
1.749     raeburn  16851: modify_access_controls():
                   16852: 
                   16853: Modifies access controls for a portfolio file
                   16854: Args
                   16855: 1. file name
                   16856: 2. reference to hash of required changes,
                   16857: 3. domain
                   16858: 4. username
                   16859:   where domain,username are the domain of the portfolio owner 
                   16860:   (either a user or a course) 
                   16861: 
                   16862: Returns:
                   16863: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16864: 2. result of deletions ('ok' or 'error', with error message).
                   16865: 3. reference to hash of any new or updated access controls.
                   16866: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16867:    key = integer (inbound ID)
1.1198    raeburn  16868:    value = uniqueID
                   16869: 
                   16870: =item *
                   16871: 
                   16872: get_timebased_id():
                   16873: 
                   16874: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   16875: course via the Course Editor (e.g., folders, composite pages, 
                   16876: group bulletin boards).
                   16877: 
                   16878: Args: (first three required; six others optional)
                   16879: 
                   16880: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16881:    docssequence, or name of group
                   16882: 
                   16883: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16884:    e.g., num, boardids
                   16885: 
                   16886: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   16887:    file will be named nohist_namespace.db
                   16888: 
                   16889: 4. cdom: domain of course; default is current course domain from %env
                   16890: 
                   16891: 5. cnum: course number; default is current course number from %env
                   16892: 
                   16893: 6. idtype: set to concat if an additional digit is to be appended to the 
                   16894:    unix timestamp to form the suffix, if the plain timestamp is already
                   16895:    in use.  Default is to not do this, but simply increment the unix 
                   16896:    timestamp by 1 until a unique key is obtained.
                   16897: 
                   16898: 7. who: holder of locking key; defaults to user:domain for user.
                   16899: 
                   16900: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   16901:    retrying); default is 3.
                   16902: 
                   16903: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   16904: 
                   16905: Returns:
                   16906: 
                   16907: 1. suffix obtained (numeric)
                   16908: 
                   16909: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16910: 
                   16911: 3. error: contains (localized) error message if an error occurred.
                   16912: 
1.747     albertel 16913: 
1.608     albertel 16914: =back
                   16915: 
1.243     albertel 16916: =head2 HTTP Helper Routines
                   16917: 
                   16918: =over 4
                   16919: 
1.191     harris41 16920: =item *
                   16921: 
                   16922: escape() : unpack non-word characters into CGI-compatible hex codes
                   16923: 
                   16924: =item *
                   16925: 
                   16926: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16927: 
1.243     albertel 16928: =back
                   16929: 
                   16930: =head1 PRIVATE SUBROUTINES
                   16931: 
                   16932: =head2 Underlying communication routines (Shouldn't call)
                   16933: 
                   16934: =over 4
                   16935: 
                   16936: =item *
                   16937: 
                   16938: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16939: 
                   16940: =item *
                   16941: 
                   16942: reply() : uses subreply to send a message to remote machine, logs all failures
                   16943: 
                   16944: =item *
                   16945: 
                   16946: critical() : passes a critical message to another server; if cannot
                   16947: get through then place message in connection buffer directory and
                   16948: returns con_delayed, if incapable of saving message, returns
                   16949: con_failed
                   16950: 
                   16951: =item *
                   16952: 
                   16953: reconlonc() : tries to reconnect lonc client processes.
                   16954: 
                   16955: =back
                   16956: 
                   16957: =head2 Resource Access Logging
                   16958: 
                   16959: =over 4
                   16960: 
                   16961: =item *
                   16962: 
                   16963: flushcourselogs() : flush (save) buffer logs and access logs
                   16964: 
                   16965: =item *
                   16966: 
                   16967: courselog($what) : save message for course in hash
                   16968: 
                   16969: =item *
                   16970: 
                   16971: courseacclog($what) : save message for course using &courselog().  Perform
                   16972: special processing for specific resource types (problems, exams, quizzes, etc).
                   16973: 
1.191     harris41 16974: =item *
                   16975: 
                   16976: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16977: as a PerlChildExitHandler
1.243     albertel 16978: 
                   16979: =back
                   16980: 
                   16981: =head2 Other
                   16982: 
                   16983: =over 4
                   16984: 
                   16985: =item *
                   16986: 
                   16987: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16988: 
                   16989: =back
                   16990: 
                   16991: =cut
1.877     foxr     16992: 

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