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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1439  ! raeburn     4: # $Id: lonnet.pm,v 1.1438 2021/01/17 01:58:56 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;
                   2167:         if ($namespace =~ /^enc/) {
                   2168:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2169:         } else {
                   2170:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2171:         }
1.866     raeburn  2172:         my %returnhash;
1.875     albertel 2173:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2174:             return %returnhash;
                   2175:         }
1.806     raeburn  2176:         my @pairs=split(/\&/,$rep);
                   2177:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2178:             return @pairs;
                   2179:         }
                   2180:         my $i=0;
                   2181:         foreach my $item (@$storearr) {
                   2182:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2183:             $i++;
                   2184:         }
                   2185:         return %returnhash;
                   2186:     } else {
1.880     banghart 2187:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2188:     }
                   2189: }
                   2190: 
                   2191: # -------------------------------------------- put items in domain db files 
                   2192: 
                   2193: sub put_dom {
1.860     raeburn  2194:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2195:     if (!$udom) {
                   2196:         $udom=$env{'user.domain'};
                   2197:         if (defined(&domain($udom,'primary'))) {
                   2198:             $uhome=&domain($udom,'primary');
                   2199:         } else {
1.874     albertel 2200:             undef($uhome);
1.860     raeburn  2201:         }
                   2202:     } else {
                   2203:         if (!$uhome) {
                   2204:             if (defined(&domain($udom,'primary'))) {
                   2205:                 $uhome=&domain($udom,'primary');
                   2206:             }
                   2207:         }
                   2208:     } 
                   2209:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2210:         my $items='';
                   2211:         foreach my $item (keys(%$storehash)) {
                   2212:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2213:         }
                   2214:         $items=~s/\&$//;
1.1344    raeburn  2215:         if ($namespace =~ /^enc/) {
                   2216:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2217:         } else {
                   2218:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2219:         }
1.806     raeburn  2220:     } else {
1.860     raeburn  2221:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2222:     }
                   2223: }
                   2224: 
1.1023    raeburn  2225: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2226: sub newput_dom {
1.1023    raeburn  2227:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2228:     my $result;
                   2229:     if (!$udom) {
                   2230:         $udom=$env{'user.domain'};
                   2231:     }
1.1023    raeburn  2232:     if ($udom) {
                   2233:         my $uname = &get_domainconfiguser($udom);
                   2234:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2235:     }
                   2236:     return $result;
                   2237: }
                   2238: 
1.1023    raeburn  2239: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2240: sub del_dom {
1.1023    raeburn  2241:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2242:     if (ref($storearr) eq 'ARRAY') {
                   2243:         if (!$udom) {
                   2244:             $udom=$env{'user.domain'};
                   2245:         }
1.1023    raeburn  2246:         if ($udom) {
                   2247:             my $uname = &get_domainconfiguser($udom); 
                   2248:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2249:         }
                   2250:     }
                   2251: }
                   2252: 
1.1023    raeburn  2253: # ----------------------------------construct domainconfig user for a domain 
                   2254: sub get_domainconfiguser {
                   2255:     my ($udom) = @_;
                   2256:     return $udom.'-domainconfig';
                   2257: }
                   2258: 
1.837     raeburn  2259: sub retrieve_inst_usertypes {
                   2260:     my ($udom) = @_;
                   2261:     my (%returnhash,@order);
1.989     raeburn  2262:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2263:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2264:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2265:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2266:     } else {
                   2267:         if (defined(&domain($udom,'primary'))) {
                   2268:             my $uhome=&domain($udom,'primary');
                   2269:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2270:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2271:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2272:                 return (\%returnhash,\@order);
                   2273:             }
                   2274:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2275:             my @pairs=split(/\&/,$hashitems);
                   2276:             foreach my $item (@pairs) {
                   2277:                 my ($key,$value)=split(/=/,$item,2);
                   2278:                 $key = &unescape($key);
                   2279:                 next if ($key =~ /^error: 2 /);
                   2280:                 $returnhash{$key}=&thaw_unescape($value);
                   2281:             }
                   2282:             my @esc_order = split(/\&/,$orderitems);
                   2283:             foreach my $item (@esc_order) {
                   2284:                 push(@order,&unescape($item));
                   2285:             }
                   2286:         } else {
1.1256    raeburn  2287:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2288:         }
1.1256    raeburn  2289:         return (\%returnhash,\@order);
1.837     raeburn  2290:     }
                   2291: }
                   2292: 
1.868     raeburn  2293: sub is_domainimage {
                   2294:     my ($url) = @_;
1.1306    raeburn  2295:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2296:         if (&domain($1) ne '') {
                   2297:             return '1';
                   2298:         }
                   2299:     }
                   2300:     return;
                   2301: }
                   2302: 
1.899     raeburn  2303: sub inst_directory_query {
                   2304:     my ($srch) = @_;
                   2305:     my $udom = $srch->{'srchdomain'};
                   2306:     my %results;
                   2307:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2308:     my $outcome;
1.899     raeburn  2309:     if ($homeserver ne '') {
1.1357    raeburn  2310:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2311:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2312:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2313:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2314:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2315:                     (($major == 2) && ($minor < 12))) {
                   2316:                     return;
                   2317:                 }
                   2318:             }
                   2319:         }
1.904     albertel 2320: 	my $queryid=&reply("querysend:instdirsearch:".
                   2321: 			   &escape($srch->{'srchby'}).':'.
                   2322: 			   &escape($srch->{'srchterm'}).':'.
                   2323: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2324: 	my $host=&hostname($homeserver);
                   2325: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2326: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2327: 	    return;
                   2328: 	}
                   2329: 	my $response = &get_query_reply($queryid);
                   2330: 	my $maxtries = 5;
                   2331: 	my $tries = 1;
                   2332: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2333: 	    $response = &get_query_reply($queryid);
                   2334: 	    $tries ++;
                   2335: 	}
                   2336: 
                   2337:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2338:             if ($response eq 'unavailable') {
                   2339:                 $outcome = $response;
                   2340:             } else {
                   2341:                 $outcome = 'ok';
                   2342:                 my @matches = split(/\n/,$response);
                   2343:                 foreach my $match (@matches) {
                   2344:                     my ($key,$value) = split(/=/,$match);
                   2345:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2346:                 }
1.899     raeburn  2347:             }
                   2348:         }
                   2349:     }
1.909     raeburn  2350:     return ($outcome,%results);
1.899     raeburn  2351: }
                   2352: 
                   2353: sub usersearch {
                   2354:     my ($srch) = @_;
                   2355:     my $dom = $srch->{'srchdomain'};
                   2356:     my %results;
                   2357:     my %libserv = &all_library();
                   2358:     my $query = 'usersearch';
                   2359:     foreach my $tryserver (keys(%libserv)) {
                   2360:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2361:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2362:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2363:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2364:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2365:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2366:                              (($major == 2) && ($minor < 12)));
                   2367:                 }
                   2368:             }
1.899     raeburn  2369:             my $host=&hostname($tryserver);
                   2370:             my $queryid=
1.911     raeburn  2371:                 &reply("querysend:".&escape($query).':'.
                   2372:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2373:                        &escape($srch->{'srchtype'}).':'.
                   2374:                        &escape($srch->{'srchterm'}),$tryserver);
                   2375:             if ($queryid !~/^\Q$host\E\_/) {
                   2376:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2377:                 next;
1.899     raeburn  2378:             }
                   2379:             my $reply = &get_query_reply($queryid);
                   2380:             my $maxtries = 1;
                   2381:             my $tries = 1;
                   2382:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2383:                 $reply = &get_query_reply($queryid);
                   2384:                 $tries ++;
                   2385:             }
                   2386:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2387:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2388:             } else {
1.911     raeburn  2389:                 my @matches;
                   2390:                 if ($reply =~ /\n/) {
                   2391:                     @matches = split(/\n/,$reply);
                   2392:                 } else {
                   2393:                     @matches = split(/\&/,$reply);
                   2394:                 }
1.899     raeburn  2395:                 foreach my $match (@matches) {
                   2396:                     my ($uname,$udom,%userhash);
1.911     raeburn  2397:                     foreach my $entry (split(/:/,$match)) {
                   2398:                         my ($key,$value) =
                   2399:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2400:                         $userhash{$key} = $value;
                   2401:                         if ($key eq 'username') {
                   2402:                             $uname = $value;
                   2403:                         } elsif ($key eq 'domain') {
                   2404:                             $udom = $value;
1.911     raeburn  2405:                         }
1.899     raeburn  2406:                     }
                   2407:                     $results{$uname.':'.$udom} = \%userhash;
                   2408:                 }
                   2409:             }
                   2410:         }
                   2411:     }
                   2412:     return %results;
                   2413: }
                   2414: 
1.912     raeburn  2415: sub get_instuser {
                   2416:     my ($udom,$uname,$id) = @_;
                   2417:     my $homeserver = &domain($udom,'primary');
                   2418:     my ($outcome,%results);
                   2419:     if ($homeserver ne '') {
                   2420:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2421:                            &escape($id).':'.&escape($udom),$homeserver);
                   2422:         my $host=&hostname($homeserver);
                   2423:         if ($queryid !~/^\Q$host\E\_/) {
                   2424:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2425:             return;
                   2426:         }
                   2427:         my $response = &get_query_reply($queryid);
                   2428:         my $maxtries = 5;
                   2429:         my $tries = 1;
                   2430:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2431:             $response = &get_query_reply($queryid);
                   2432:             $tries ++;
                   2433:         }
                   2434:         if (!&error($response) && $response ne 'refused') {
                   2435:             if ($response eq 'unavailable') {
                   2436:                 $outcome = $response;
                   2437:             } else {
                   2438:                 $outcome = 'ok';
                   2439:                 my @matches = split(/\n/,$response);
                   2440:                 foreach my $match (@matches) {
                   2441:                     my ($key,$value) = split(/=/,$match);
                   2442:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2443:                 }
                   2444:             }
                   2445:         }
                   2446:     }
                   2447:     my %userinfo;
                   2448:     if (ref($results{$uname}) eq 'HASH') {
                   2449:         %userinfo = %{$results{$uname}};
                   2450:     } 
                   2451:     return ($outcome,%userinfo);
                   2452: }
                   2453: 
1.1290    raeburn  2454: sub get_multiple_instusers {
                   2455:     my ($udom,$users,$caller) = @_;
                   2456:     my ($outcome,$results);
                   2457:     if (ref($users) eq 'HASH') {
                   2458:         my $count = keys(%{$users}); 
                   2459:         my $requested = &freeze_escape($users);
                   2460:         my $homeserver = &domain($udom,'primary');
                   2461:         if ($homeserver ne '') {
                   2462:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2463:             my $host=&hostname($homeserver);
                   2464:             if ($queryid !~/^\Q$host\E\_/) {
                   2465:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2466:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2467:                 return ($outcome,$results);
                   2468:             }
                   2469:             my $response = &get_query_reply($queryid);
                   2470:             my $maxtries = 5;
                   2471:             if ($count > 100) {
                   2472:                 $maxtries = 1+int($count/20);
                   2473:             }
                   2474:             my $tries = 1;
                   2475:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2476:                 $response = &get_query_reply($queryid);
                   2477:                 $tries ++;
                   2478:             }
                   2479:             if ($response eq '') {
                   2480:                 $results = {};
                   2481:                 foreach my $key (keys(%{$users})) {
                   2482:                     my ($uname,$id);
                   2483:                     if ($caller eq 'id') {
                   2484:                         $id = $key;
                   2485:                     } else {
                   2486:                         $uname = $key;
                   2487:                     }
                   2488:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2489:                     $outcome = $resp;
1.1290    raeburn  2490:                     if ($resp eq 'ok') {
                   2491:                         %{$results} = (%{$results}, %info);
                   2492:                     } else {
                   2493:                         last;
                   2494:                     }
                   2495:                 }
                   2496:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2497:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2498:                     $outcome = $response;
                   2499:                 } else {
1.1291    raeburn  2500:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2501:                     if ($outcome eq 'ok') {
                   2502:                         $results = &thaw_unescape($userdata); 
                   2503:                     }
                   2504:                 }
                   2505:             }
                   2506:         }
                   2507:     }
                   2508:     return ($outcome,$results);
                   2509: }
                   2510: 
1.912     raeburn  2511: sub inst_rulecheck {
1.923     raeburn  2512:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2513:     my %returnhash;
                   2514:     if ($udom ne '') {
                   2515:         if (ref($rules) eq 'ARRAY') {
                   2516:             @{$rules} = map {&escape($_);} (@{$rules});
                   2517:             my $rulestr = join(':',@{$rules});
                   2518:             my $homeserver=&domain($udom,'primary');
                   2519:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2520:                 my $response;
                   2521:                 if ($item eq 'username') {                
                   2522:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2523:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2524:                                               $homeserver));
1.923     raeburn  2525:                 } elsif ($item eq 'id') {
                   2526:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2527:                                               ':'.&escape($id).':'.$rulestr,
                   2528:                                               $homeserver));
1.945     raeburn  2529:                 } elsif ($item eq 'selfcreate') {
                   2530:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2531:                                                &escape($udom).':'.&escape($uname).
                   2532:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2533:                 }
1.912     raeburn  2534:                 if ($response ne 'refused') {
                   2535:                     my @pairs=split(/\&/,$response);
                   2536:                     foreach my $item (@pairs) {
                   2537:                         my ($key,$value)=split(/=/,$item,2);
                   2538:                         $key = &unescape($key);
                   2539:                         next if ($key =~ /^error: 2 /);
                   2540:                         $returnhash{$key}=&thaw_unescape($value);
                   2541:                     }
                   2542:                 }
                   2543:             }
                   2544:         }
                   2545:     }
                   2546:     return %returnhash;
                   2547: }
                   2548: 
                   2549: sub inst_userrules {
1.923     raeburn  2550:     my ($udom,$check) = @_;
1.912     raeburn  2551:     my (%ruleshash,@ruleorder);
                   2552:     if ($udom ne '') {
                   2553:         my $homeserver=&domain($udom,'primary');
                   2554:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2555:             my $response;
                   2556:             if ($check eq 'id') {
                   2557:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2558:                                  $homeserver);
1.943     raeburn  2559:             } elsif ($check eq 'email') {
                   2560:                 $response=&reply('instemailrules:'.&escape($udom),
                   2561:                                  $homeserver);
1.923     raeburn  2562:             } else {
                   2563:                 $response=&reply('instuserrules:'.&escape($udom),
                   2564:                                  $homeserver);
                   2565:             }
1.912     raeburn  2566:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2567:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2568:                 ($response ne 'no_such_host')) {
                   2569:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2570:                 my @pairs=split(/\&/,$hashitems);
                   2571:                 foreach my $item (@pairs) {
                   2572:                     my ($key,$value)=split(/=/,$item,2);
                   2573:                     $key = &unescape($key);
                   2574:                     next if ($key =~ /^error: 2 /);
                   2575:                     $ruleshash{$key}=&thaw_unescape($value);
                   2576:                 }
                   2577:                 my @esc_order = split(/\&/,$orderitems);
                   2578:                 foreach my $item (@esc_order) {
                   2579:                     push(@ruleorder,&unescape($item));
                   2580:                 }
                   2581:             }
                   2582:         }
                   2583:     }
                   2584:     return (\%ruleshash,\@ruleorder);
                   2585: }
                   2586: 
1.976     raeburn  2587: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2588: 
                   2589: sub get_domain_defaults {
1.1240    raeburn  2590:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2591:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2592:     my $cachetime = 60*60*24;
1.1240    raeburn  2593:     unless ($ignore_cache) {
                   2594:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2595:         if (defined($cached)) {
                   2596:             if (ref($result) eq 'HASH') {
                   2597:                 return %{$result};
                   2598:             }
1.943     raeburn  2599:         }
                   2600:     }
                   2601:     my %domdefaults;
                   2602:     my %domconfig =
1.989     raeburn  2603:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2604:                                   'requestcourses','inststatus',
1.1183    raeburn  2605:                                   'coursedefaults','usersessions',
1.1258    raeburn  2606:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2607:                                   'coursecategories','ssl','autoenroll',
1.1434    raeburn  2608:                                   'trust','helpsettings','wafproxy'],$domain);
1.1305    raeburn  2609:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2610:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2611:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2612:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2613:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2614:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2615:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2616:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2617:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2618:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2619:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2620:     } else {
                   2621:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2622:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2623:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2624:     }
1.976     raeburn  2625:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2626:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2627:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2628:         } else {
                   2629:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2630:         }
1.1177    raeburn  2631:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2632:         foreach my $item (@usertools) {
                   2633:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2634:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2635:             }
                   2636:         }
1.1229    raeburn  2637:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2638:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2639:         }
1.976     raeburn  2640:     }
1.985     raeburn  2641:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2642:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2643:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2644:         }
                   2645:     }
1.1183    raeburn  2646:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2647:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2648:     }
1.989     raeburn  2649:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2650:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2651:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2652:         }
                   2653:     }
1.1047    raeburn  2654:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2655:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2656:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2657:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2658:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2659:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2660:         }
1.1254    raeburn  2661:         foreach my $type (@coursetypes) {
                   2662:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2663:                 unless ($type eq 'community') {
                   2664:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2665:                 }
                   2666:             }
                   2667:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2668:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2669:             }
1.1277    raeburn  2670:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2671:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2672:                     $domdefaults{$type.'postsubtimeout'} = 
                   2673:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2674:                 }
                   2675:             }
1.1230    raeburn  2676:         }
1.1286    raeburn  2677:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2678:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2679:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2680:                 if (@clonecodes) {
                   2681:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2682:                 }
                   2683:             }
                   2684:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2685:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2686:         }
1.1356    raeburn  2687:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2688:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2689:         } 
1.1047    raeburn  2690:     }
1.1073    raeburn  2691:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2692:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2693:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2694:         }
                   2695:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2696:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2697:         }
1.1279    raeburn  2698:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2699:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2700:         }
1.1439  ! raeburn  2701:         if (ref($domconfig{'usersessions'}{offloadoth'} eq 'HASH') {
        !          2702:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
        !          2703:         }
1.1073    raeburn  2704:     }
1.1254    raeburn  2705:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2706:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2707:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2708:                             'approval','limit');
                   2709:             foreach my $type (@coursetypes) {
                   2710:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2711:                     my @mgrdc = ();
                   2712:                     foreach my $item (@settings) {
                   2713:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2714:                             push(@mgrdc,$item);
                   2715:                         }
                   2716:                     }
                   2717:                     if (@mgrdc) {
                   2718:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2719:                     }
                   2720:                 }
                   2721:             }
                   2722:         }
                   2723:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2724:             foreach my $type (@coursetypes) {
                   2725:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2726:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2727:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2728:                     }
                   2729:                 }
                   2730:             }
                   2731:         }
                   2732:     }
1.1258    raeburn  2733:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2734:         $domdefaults{'catauth'} = 'std';
                   2735:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2736:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2737:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2738:         }
                   2739:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2740:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2741:         }
                   2742:     }
1.1315    raeburn  2743:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2744:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2745:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2746:         }
1.1338    raeburn  2747:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2748:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2749:         }
                   2750:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2751:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2752:         }
                   2753:     }
1.1320    raeburn  2754:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2755:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2756:         foreach my $prefix (@prefixes) {
                   2757:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2758:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2759:             }
                   2760:         }
                   2761:     }
1.1314    raeburn  2762:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2763:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2764:     }
1.1332    raeburn  2765:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2766:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2767:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2768:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2769:         }
                   2770:     }
1.1434    raeburn  2771:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1437    raeburn  2772:         foreach my $item ('ipheader','trusted','vpnint','vpnext') {
1.1434    raeburn  2773:             if ($domconfig{'wafproxy'}{$item}) {
                   2774:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2775:             }
                   2776:         }
                   2777:     } 
1.1219    raeburn  2778:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2779:     return %domdefaults;
                   2780: }
                   2781: 
1.1412    raeburn  2782: sub get_dom_cats {
                   2783:     my ($dom) = @_;
                   2784:     return unless (&domain($dom));
                   2785:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2786:     unless (defined($cached)) {
                   2787:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2788:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2789:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2790:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2791:             } else {
                   2792:                 $cats = {};
                   2793:             }
                   2794:         } else {
                   2795:             $cats = {};
                   2796:         }
                   2797:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2798:     }
1.1413    raeburn  2799:     return $cats;
                   2800: }
                   2801: 
                   2802: sub get_dom_instcats {
                   2803:     my ($dom) = @_;
                   2804:     return unless (&domain($dom));
                   2805:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2806:     unless (defined($cached)) {
                   2807:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2808:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2809:         if ($totcodes > 0) {
                   2810:             my $caller = 'global';
                   2811:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2812:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2813:                 $instcats = {
                   2814:                                 codes => \%codes,
                   2815:                                 codetitles => \@codetitles,
                   2816:                                 cat_titles => \%cat_titles,
                   2817:                                 cat_order => \%cat_order,
                   2818:                             };
                   2819:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2820:             }
                   2821:         }
                   2822:     }
                   2823:     return $instcats;
                   2824: }
                   2825: 
                   2826: sub retrieve_instcodes {
                   2827:     my ($coursecodes,$dom) = @_;
                   2828:     my $totcodes;
                   2829:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2830:     foreach my $course (keys(%courses)) {
                   2831:         if (ref($courses{$course}) eq 'HASH') {
                   2832:             if ($courses{$course}{'inst_code'} ne '') {
                   2833:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2834:                 $totcodes ++;
                   2835:             }
                   2836:         }
                   2837:     }
                   2838:     return $totcodes;
1.1412    raeburn  2839: }
                   2840: 
1.1311    raeburn  2841: sub course_portal_url {
                   2842:     my ($cnum,$cdom) = @_;
                   2843:     my $chome = &homeserver($cnum,$cdom);
                   2844:     my $hostname = &hostname($chome);
                   2845:     my $protocol = $protocol{$chome};
                   2846:     $protocol = 'http' if ($protocol ne 'https');
                   2847:     my %domdefaults = &get_domain_defaults($cdom);
                   2848:     my $firsturl;
                   2849:     if ($domdefaults{'portal_def'}) {
                   2850:         $firsturl = $domdefaults{'portal_def'};
                   2851:     } else {
                   2852:         $firsturl = $protocol.'://'.$hostname;
                   2853:     }
                   2854:     return $firsturl;
                   2855: }
                   2856: 
1.1407    raeburn  2857: # --------------------------------------------- Get domain config for passwords
                   2858: 
                   2859: sub get_passwdconf {
                   2860:     my ($dom) = @_;
                   2861:     my (%passwdconf,$gotconf,$lookup);
                   2862:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2863:     if (defined($cached)) {
                   2864:         if (ref($result) eq 'HASH') {
                   2865:             %passwdconf = %{$result};
                   2866:             $gotconf = 1;
                   2867:         }
                   2868:     }
                   2869:     unless ($gotconf) {
                   2870:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2871:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2872:             %passwdconf = %{$domconfig{'passwords'}};
                   2873:         }
                   2874:         my $cachetime = 24*60*60;
                   2875:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2876:     }
                   2877:     return %passwdconf;
                   2878: }
                   2879: 
1.344     www      2880: # --------------------------------------------------- Assign a key to a student
                   2881: 
                   2882: sub assign_access_key {
1.364     www      2883: #
                   2884: # a valid key looks like uname:udom#comments
                   2885: # comments are being appended
                   2886: #
1.498     www      2887:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2888:     $kdom=
1.620     albertel 2889:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2890:     $knum=
1.620     albertel 2891:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2892:     $cdom=
1.620     albertel 2893:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2894:     $cnum=
1.620     albertel 2895:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2896:     $udom=$env{'user.name'} unless (defined($udom));
                   2897:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2898:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2899:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2900:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2901:                                                   # assigned to this person
                   2902:                                                   # - this should not happen,
1.345     www      2903:                                                   # unless something went wrong
                   2904:                                                   # the first time around
                   2905: # ready to assign
1.364     www      2906:         $logentry=$1.'; '.$logentry;
1.496     www      2907:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2908:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2909: # key now belongs to user
1.346     www      2910: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2911:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2912:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2913:                 return 'ok';
                   2914:             } else {
                   2915:                 return 
                   2916:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2917: 	    }
                   2918:         } else {
                   2919:             return 'error: Could not assign key, try again later.';
                   2920:         }
1.364     www      2921:     } elsif (!$existing{$ckey}) {
1.345     www      2922: # the key does not exist
                   2923: 	return 'error: The key does not exist';
                   2924:     } else {
                   2925: # the key is somebody else's
                   2926: 	return 'error: The key is already in use';
                   2927:     }
1.344     www      2928: }
                   2929: 
1.364     www      2930: # ------------------------------------------ put an additional comment on a key
                   2931: 
                   2932: sub comment_access_key {
                   2933: #
                   2934: # a valid key looks like uname:udom#comments
                   2935: # comments are being appended
                   2936: #
                   2937:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2938:     $cdom=
1.620     albertel 2939:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2940:     $cnum=
1.620     albertel 2941:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2942:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2943:     if ($existing{$ckey}) {
                   2944:         $existing{$ckey}.='; '.$logentry;
                   2945: # ready to assign
1.367     www      2946:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2947:                                                  $cdom,$cnum) eq 'ok') {
                   2948: 	    return 'ok';
                   2949:         } else {
                   2950: 	    return 'error: Count not store comment.';
                   2951:         }
                   2952:     } else {
                   2953: # the key does not exist
                   2954: 	return 'error: The key does not exist';
                   2955:     }
                   2956: }
                   2957: 
1.344     www      2958: # ------------------------------------------------------ Generate a set of keys
                   2959: 
                   2960: sub generate_access_keys {
1.364     www      2961:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2962:     $cdom=
1.620     albertel 2963:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2964:     $cnum=
1.620     albertel 2965:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2966:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2967:     unless (($cdom) && ($cnum)) { return 0; }
                   2968:     if ($number>10000) { return 0; }
                   2969:     sleep(2); # make sure don't get same seed twice
                   2970:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2971:     my $total=0;
                   2972:     for (my $i=1;$i<=$number;$i++) {
                   2973:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2974:                   sprintf("%lx",int(100000*rand)).'-'.
                   2975:                   sprintf("%lx",int(100000*rand));
                   2976:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2977:        $newkey=~s/0/h/g; # and also 0 and O
                   2978:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2979:        if ($existing{$newkey}) {
                   2980:            $i--;
                   2981:        } else {
1.364     www      2982: 	  if (&put('accesskeys',
                   2983:               { $newkey => '# generated '.localtime().
1.620     albertel 2984:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2985:                            '; '.$logentry },
                   2986: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2987:               $total++;
                   2988: 	  }
                   2989:        }
                   2990:     }
1.620     albertel 2991:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2992:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2993:     return $total;
                   2994: }
                   2995: 
                   2996: # ------------------------------------------------------- Validate an accesskey
                   2997: 
                   2998: sub validate_access_key {
                   2999:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3000:     $cdom=
1.620     albertel 3001:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3002:     $cnum=
1.620     albertel 3003:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3004:     $udom=$env{'user.domain'} unless (defined($udom));
                   3005:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3006:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3007:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3008: }
                   3009: 
                   3010: # ------------------------------------- Find the section of student in a course
1.652     albertel 3011: sub devalidate_getsection_cache {
                   3012:     my ($udom,$unam,$courseid)=@_;
                   3013:     my $hashid="$udom:$unam:$courseid";
                   3014:     &devalidate_cache_new('getsection',$hashid);
                   3015: }
1.298     matthew  3016: 
1.815     albertel 3017: sub courseid_to_courseurl {
                   3018:     my ($courseid) = @_;
                   3019:     #already url style courseid
                   3020:     return $courseid if ($courseid =~ m{^/});
                   3021: 
                   3022:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3023: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3024: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3025: 	return "/$cdom/$cnum";
                   3026:     }
                   3027: 
                   3028:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3029:     if (exists($courseinfo{'num'})) {
                   3030: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3031:     }
                   3032: 
                   3033:     return undef;
                   3034: }
                   3035: 
1.298     matthew  3036: sub getsection {
                   3037:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3038:     my $cachetime=1800;
1.551     albertel 3039: 
                   3040:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3041:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3042:     if (defined($cached)) { return $result; }
                   3043: 
1.298     matthew  3044:     my %Pending; 
                   3045:     my %Expired;
                   3046:     #
                   3047:     # Each role can either have not started yet (pending), be active, 
                   3048:     #    or have expired.
                   3049:     #
                   3050:     # If there is an active role, we are done.
                   3051:     #
                   3052:     # If there is more than one role which has not started yet, 
                   3053:     #     choose the one which will start sooner
                   3054:     # If there is one role which has not started yet, return it.
                   3055:     #
                   3056:     # If there is more than one expired role, choose the one which ended last.
                   3057:     # If there is a role which has expired, return it.
                   3058:     #
1.815     albertel 3059:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3060:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3061:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3062:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3063:         my $section=$1;
                   3064:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3065:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3066:         my $now=time;
1.548     albertel 3067:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3068:             $Expired{$end}=$section;
                   3069:             next;
                   3070:         }
1.548     albertel 3071:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3072:             $Pending{$start}=$section;
                   3073:             next;
                   3074:         }
1.599     albertel 3075:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3076:     }
                   3077:     #
                   3078:     # Presumedly there will be few matching roles from the above
                   3079:     # loop and the sorting time will be negligible.
                   3080:     if (scalar(keys(%Pending))) {
                   3081:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3082:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3083:     } 
                   3084:     if (scalar(keys(%Expired))) {
                   3085:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3086:         my $time = pop(@sorted);
1.599     albertel 3087:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3088:     }
1.599     albertel 3089:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3090: }
1.70      www      3091: 
1.599     albertel 3092: sub save_cache {
                   3093:     &purge_remembered();
1.722     albertel 3094:     #&Apache::loncommon::validate_page();
1.620     albertel 3095:     undef(%env);
1.780     albertel 3096:     undef($env_loaded);
1.599     albertel 3097: }
1.452     albertel 3098: 
1.599     albertel 3099: my $to_remember=-1;
                   3100: my %remembered;
                   3101: my %accessed;
                   3102: my $kicks=0;
                   3103: my $hits=0;
1.849     albertel 3104: sub make_key {
                   3105:     my ($name,$id) = @_;
1.872     albertel 3106:     if (length($id) > 65 
                   3107: 	&& length(&escape($id)) > 200) {
                   3108: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3109:     }
1.849     albertel 3110:     return &escape($name.':'.$id);
                   3111: }
                   3112: 
1.599     albertel 3113: sub devalidate_cache_new {
                   3114:     my ($name,$id,$debug) = @_;
                   3115:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3116:     my $remembered_id=$name.':'.$id;
1.849     albertel 3117:     $id=&make_key($name,$id);
1.599     albertel 3118:     $memcache->delete($id);
1.1319    damieng  3119:     delete($remembered{$remembered_id});
                   3120:     delete($accessed{$remembered_id});
1.599     albertel 3121: }
                   3122: 
                   3123: sub is_cached_new {
                   3124:     my ($name,$id,$debug) = @_;
1.1319    damieng  3125:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3126:     if (exists($remembered{$remembered_id})) {
                   3127: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3128: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3129: 	$hits++;
1.1319    damieng  3130: 	return ($remembered{$remembered_id},1);
1.599     albertel 3131:     }
1.1319    damieng  3132:     $id=&make_key($name,$id);
1.599     albertel 3133:     my $value = $memcache->get($id);
                   3134:     if (!(defined($value))) {
                   3135: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3136: 	return (undef,undef);
1.416     albertel 3137:     }
1.599     albertel 3138:     if ($value eq '__undef__') {
                   3139: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3140: 	$value=undef;
                   3141:     }
1.1319    damieng  3142:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3143:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3144:     return ($value,1);
                   3145: }
                   3146: 
                   3147: sub do_cache_new {
                   3148:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3149:     my $remembered_id=$name.':'.$id;
1.849     albertel 3150:     $id=&make_key($name,$id);
1.599     albertel 3151:     my $setvalue=$value;
                   3152:     if (!defined($setvalue)) {
                   3153: 	$setvalue='__undef__';
                   3154:     }
1.623     albertel 3155:     if (!defined($time) ) {
                   3156: 	$time=600;
                   3157:     }
1.599     albertel 3158:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3159:     my $result = $memcache->set($id,$setvalue,$time);
                   3160:     if (! $result) {
1.872     albertel 3161: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3162: 	$memcache->disconnect_all();
1.872     albertel 3163:     }
1.600     albertel 3164:     # need to make a copy of $value
1.1319    damieng  3165:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3166:     return $value;
                   3167: }
                   3168: 
                   3169: sub make_room {
1.1319    damieng  3170:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3171: 
1.1319    damieng  3172:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3173:                                     : $value;
1.599     albertel 3174:     if ($to_remember<0) { return; }
1.1319    damieng  3175:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3176:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3177:     my $to_kick;
                   3178:     my $max_time=0;
                   3179:     foreach my $other (keys(%accessed)) {
                   3180: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3181: 	    $to_kick=$other;
                   3182: 	    $max_time=&tv_interval($accessed{$other});
                   3183: 	}
                   3184:     }
                   3185:     delete($remembered{$to_kick});
                   3186:     delete($accessed{$to_kick});
                   3187:     $kicks++;
                   3188:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3189:     return;
                   3190: }
                   3191: 
1.599     albertel 3192: sub purge_remembered {
1.604     albertel 3193:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3194:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3195:     undef(%remembered);
                   3196:     undef(%accessed);
1.428     albertel 3197: }
1.70      www      3198: # ------------------------------------- Read an entry from a user's environment
                   3199: 
                   3200: sub userenvironment {
                   3201:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3202:     my $items;
                   3203:     foreach my $item (@what) {
                   3204:         $items.=&escape($item).'&';
                   3205:     }
                   3206:     $items=~s/\&$//;
1.70      www      3207:     my %returnhash=();
1.1009    raeburn  3208:     my $uhome = &homeserver($unam,$udom);
                   3209:     unless ($uhome eq 'no_host') {
                   3210:         my @answer=split(/\&/, 
                   3211:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3212:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3213:             return %returnhash;
                   3214:         }
1.1009    raeburn  3215:         my $i;
                   3216:         for ($i=0;$i<=$#what;$i++) {
                   3217: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3218:         }
1.70      www      3219:     }
                   3220:     return %returnhash;
1.1       albertel 3221: }
                   3222: 
1.617     albertel 3223: # ---------------------------------------------------------- Get a studentphoto
                   3224: sub studentphoto {
                   3225:     my ($udom,$unam,$ext) = @_;
                   3226:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3227:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3228:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3229:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3230:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3231:             } else {
                   3232:                 my ($result,$perm_reqd)=
1.707     albertel 3233: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3234:                 if ($result eq 'ok') {
                   3235:                     if (!($perm_reqd eq 'yes')) {
                   3236:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3237:                     }
                   3238:                 }
                   3239:             }
                   3240:         }
                   3241:     } else {
                   3242:         my ($result,$perm_reqd) = 
1.707     albertel 3243: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3244:         if ($result eq 'ok') {
                   3245:             if (!($perm_reqd eq 'yes')) {
                   3246:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3247:             }
                   3248:         }
                   3249:     }
                   3250:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3251: }
                   3252: 
                   3253: sub retrievestudentphoto {
                   3254:     my ($udom,$unam,$ext,$type) = @_;
                   3255:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3256:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3257:     if ($ret eq 'ok') {
                   3258:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3259:         if ($type eq 'thumbnail') {
                   3260:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3261:         }
                   3262:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3263:         return $tokenurl;
                   3264:     } else {
                   3265:         if ($type eq 'thumbnail') {
                   3266:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3267:         } else { 
                   3268:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3269:         }
1.617     albertel 3270:     }
                   3271: }
                   3272: 
1.263     www      3273: # -------------------------------------------------------------------- New chat
                   3274: 
                   3275: sub chatsend {
1.724     raeburn  3276:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3277:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3278:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3279:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3280:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3281: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3282: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3283: }
                   3284: 
                   3285: # ------------------------------------------ Find current version of a resource
                   3286: 
                   3287: sub getversion {
                   3288:     my $fname=&clutter(shift);
1.1189    raeburn  3289:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3290:     return &currentversion(&filelocation('',$fname));
                   3291: }
                   3292: 
                   3293: sub currentversion {
                   3294:     my $fname=shift;
                   3295:     my $author=$fname;
                   3296:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3297:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3298:     my $home=&homeserver($uname,$udom);
1.292     www      3299:     if ($home eq 'no_host') { 
                   3300:         return -1; 
                   3301:     }
1.1112    www      3302:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3303:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3304: 	return -1;
                   3305:     }
1.1112    www      3306:     return $answer;
1.263     www      3307: }
                   3308: 
1.1111    www      3309: #
                   3310: # Return special version number of resource if set by override, empty otherwise
                   3311: #
                   3312: sub usedversion {
                   3313:     my $fname=shift;
                   3314:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3315:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3316:     if ($urlversion) { return $urlversion; }
                   3317:     return '';
                   3318: }
                   3319: 
1.1       albertel 3320: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3321: 
1.1       albertel 3322: sub subscribe {
                   3323:     my $fname=shift;
1.761     raeburn  3324:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3325:     $fname=~s/[\n\r]//g;
1.1       albertel 3326:     my $author=$fname;
                   3327:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3328:     my ($udom,$uname)=split(/\//,$author);
                   3329:     my $home=homeserver($uname,$udom);
1.335     albertel 3330:     if ($home eq 'no_host') {
                   3331:         return 'not_found';
1.1       albertel 3332:     }
                   3333:     my $answer=reply("sub:$fname",$home);
1.64      www      3334:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3335: 	$answer.=' by '.$home;
                   3336:     }
1.1       albertel 3337:     return $answer;
                   3338: }
                   3339:     
1.8       www      3340: # -------------------------------------------------------------- Replicate file
                   3341: 
                   3342: sub repcopy {
                   3343:     my $filename=shift;
1.23      www      3344:     $filename=~s/\/+/\//g;
1.1142    raeburn  3345:     my $londocroot = $perlvar{'lonDocRoot'};
                   3346:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3347:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3348:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3349: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3350: 	return &repcopy_userfile($filename);
                   3351:     }
1.532     albertel 3352:     $filename=~s/[\n\r]//g;
1.8       www      3353:     my $transname="$filename.in.transfer";
1.828     www      3354: # FIXME: this should flock
1.607     raeburn  3355:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3356:     my $remoteurl=subscribe($filename);
1.64      www      3357:     if ($remoteurl =~ /^con_lost by/) {
                   3358: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3359:            return 'unavailable';
1.8       www      3360:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3361: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3362: 	   return 'not_found';
1.64      www      3363:     } elsif ($remoteurl =~ /^rejected by/) {
                   3364: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3365:            return 'forbidden';
1.20      www      3366:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3367:            return 'ok';
1.8       www      3368:     } else {
1.290     www      3369:         my $author=$filename;
                   3370:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3371:         my ($udom,$uname)=split(/\//,$author);
                   3372:         my $home=homeserver($uname,$udom);
                   3373:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3374:            my @parts=split(/\//,$filename);
                   3375:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3376:            if ($path ne "$londocroot/res") {
1.8       www      3377:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3378: 	       return 'bad_request';
1.8       www      3379:            }
                   3380:            my $count;
                   3381:            for ($count=5;$count<$#parts;$count++) {
                   3382:                $path.="/$parts[$count]";
                   3383:                if ((-e $path)!=1) {
                   3384: 		   mkdir($path,0777);
                   3385:                }
                   3386:            }
                   3387:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3388:            my $response;
                   3389:            if ($remoteurl =~ m{/raw/}) {
                   3390:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3391:            } else {
                   3392:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3393:            }
1.8       www      3394:            if ($response->is_error()) {
                   3395: 	       unlink($transname);
                   3396:                my $message=$response->status_line;
1.672     albertel 3397:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3398:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3399:                return 'unavailable';
1.8       www      3400:            } else {
1.16      www      3401: 	       if ($remoteurl!~/\.meta$/) {
                   3402:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3403:                   my $mresponse;
                   3404:                   if ($remoteurl =~ m{/raw/}) {
                   3405:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3406:                   } else {
                   3407:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3408:                   }
1.16      www      3409:                   if ($mresponse->is_error()) {
                   3410: 		      unlink($filename.'.meta');
                   3411:                       &logthis(
1.672     albertel 3412:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3413:                   }
                   3414: 	       }
1.8       www      3415:                rename($transname,$filename);
1.607     raeburn  3416:                return 'ok';
1.8       www      3417:            }
1.290     www      3418:        }
1.8       www      3419:     }
1.330     www      3420: }
                   3421: 
1.1422    raeburn  3422: # ------------------------------------------------- Unsubscribe from a resource
                   3423: 
                   3424: sub unsubscribe {
                   3425:     my ($fname) = @_;
                   3426:     my $answer;
                   3427:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3428:     $fname=~s/[\n\r]//g;
                   3429:     my $author=$fname;
                   3430:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3431:     my ($udom,$uname)=split(/\//,$author);
                   3432:     my $home=homeserver($uname,$udom);
                   3433:     if ($home eq 'no_host') {
                   3434:         $answer = 'no_host';
                   3435:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3436:         $answer = 'home';
                   3437:     } else {
                   3438:         my $defdom = $perlvar{'lonDefDomain'};
                   3439:         if (&will_trust('content',$defdom,$udom)) {
                   3440:             $answer = reply("unsub:$fname",$home);
                   3441:         } else {
                   3442:             $answer = 'untrusted';
                   3443:         }
                   3444:     }
                   3445:     return $answer;
                   3446: }
                   3447: 
1.330     www      3448: # ------------------------------------------------ Get server side include body
                   3449: sub ssi_body {
1.381     albertel 3450:     my ($filelink,%form)=@_;
1.606     matthew  3451:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3452:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3453:     }
1.953     www      3454:     my $output='';
                   3455:     my $response;
1.980     raeburn  3456:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3457:        ($output,$response)=&externalssi($filelink);
1.953     www      3458:     } else {
1.1004    droeschl 3459:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3460:        $filelink .= 'inhibitmenu=yes';
1.953     www      3461:        ($output,$response)=&ssi($filelink,%form);
                   3462:     }
1.778     albertel 3463:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3464:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3465:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3466:     if (wantarray) {
                   3467:         return ($output, $response);
                   3468:     } else {
                   3469:         return $output;
                   3470:     }
1.8       www      3471: }
                   3472: 
1.15      www      3473: # --------------------------------------------------------- Server Side Include
                   3474: 
1.782     albertel 3475: sub absolute_url {
                   3476:     my ($host_name) = @_;
                   3477:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3478:     if ($host_name eq '') {
                   3479: 	$host_name = $ENV{'SERVER_NAME'};
                   3480:     }
                   3481:     return $protocol.$host_name;
                   3482: }
                   3483: 
1.942     foxr     3484: #
                   3485: #   Server side include.
                   3486: # Parameters:
                   3487: #  fn     Possibly encrypted resource name/id.
                   3488: #  form   Hash that describes how the rendering should be done
                   3489: #         and other things.
1.944     foxr     3490: # Returns:
1.950     raeburn  3491: #   Scalar context: The content of the response.
                   3492: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3493: #     
1.15      www      3494: sub ssi {
                   3495: 
1.944     foxr     3496:     my ($fn,%form)=@_;
1.23      www      3497:     my $request;
1.711     albertel 3498: 
                   3499:     $form{'no_update_last_known'}=1;
1.895     albertel 3500:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3501:     if (%form) {
1.782     albertel 3502:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3503:       $request->content(join('&',map { 
                   3504:             my $name = escape($_);
                   3505:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3506:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3507:             : &escape($form{$_}) );    
                   3508:         } keys(%form)));
1.23      www      3509:     } else {
1.782     albertel 3510:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3511:     }
                   3512: 
1.15      www      3513:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3514:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3515:     my $islocal;
                   3516:     if (($env{'request.course.id'}) &&
                   3517:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3518:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3519:         ($form{'grade_symb'} ne '') &&
                   3520:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3521:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3522:         $islocal = 1;
                   3523:     }
1.1384    raeburn  3524:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3525:                                                 '','','',$islocal);
1.1182    foxr     3526: 
1.944     foxr     3527:     if (wantarray) {
1.1345    raeburn  3528: 	return ($response->content, $response);
1.944     foxr     3529:     } else {
1.1345    raeburn  3530: 	return $response->content;
1.942     foxr     3531:     }
1.324     www      3532: }
                   3533: 
                   3534: sub externalssi {
                   3535:     my ($url)=@_;
                   3536:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3537:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3538:     if (wantarray) {
                   3539:         return ($response->content, $response);
                   3540:     } else {
                   3541:         return $response->content;
                   3542:     }
1.15      www      3543: }
1.254     www      3544: 
1.1354    raeburn  3545: 
                   3546: # If the local copy of a replicated resource is outdated, trigger a  
                   3547: # connection from the homeserver to flush the delayed queue. If no update 
                   3548: # happens, remove local copies of outdated resource (and corresponding
                   3549: # metadata file).
                   3550: 
1.1352    raeburn  3551: sub remove_stale_resfile {
                   3552:     my ($url) = @_;
1.1354    raeburn  3553:     my $removed;
1.1352    raeburn  3554:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3555:         my $audom = $1;
                   3556:         my $auname = $2;
1.1353    raeburn  3557:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3558:             my $homeserver = &homeserver($auname,$audom);
                   3559:             unless (($homeserver eq 'no_host') ||
                   3560:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3561:                 my $fname = &filelocation('',$url);
                   3562:                 if (-e $fname) {
                   3563:                     my $hostname = &hostname($homeserver);
                   3564:                     if ($hostname) {
1.1397    raeburn  3565:                         my $protocol = $protocol{$homeserver};
                   3566:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3567:                         my $uri = &declutter($url);
                   3568:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3569:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3570:                         if ($response->is_success()) {
                   3571:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3572:                             my $locmodtime = (stat($fname))[9];
                   3573:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3574:                                 my $stale;
                   3575:                                 my $answer = &reply('pong',$homeserver);
                   3576:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3577:                                     sleep(0.2);
                   3578:                                     $locmodtime = (stat($fname))[9];
                   3579:                                     if ($locmodtime < $remmodtime) {
                   3580:                                         my $posstransfer = $fname.'.in.transfer';
                   3581:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3582:                                             $removed = 1;
                   3583:                                         } else {
                   3584:                                             $stale = 1;
                   3585:                                         }
                   3586:                                     } else {
                   3587:                                         $removed = 1;
                   3588:                                     }
                   3589:                                 } else {
                   3590:                                     $stale = 1;
                   3591:                                 }
                   3592:                                 if ($stale) {
1.1421    raeburn  3593:                                     if (unlink($fname)) {
                   3594:                                         if ($uri!~/\.meta$/) {
                   3595:                                             if (-e $fname.'.meta') {
                   3596:                                                 unlink($fname.'.meta');
                   3597:                                             }
                   3598:                                         }
1.1422    raeburn  3599:                                         my $unsubresult = &unsubscribe($fname);
                   3600:                                         unless ($unsubresult eq 'ok') {
                   3601:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3602:                                         }
1.1421    raeburn  3603:                                         $removed = 1;
1.1354    raeburn  3604:                                     }
1.1352    raeburn  3605:                                 }
                   3606:                             }
                   3607:                         }
                   3608:                     }
                   3609:                 }
                   3610:             }
                   3611:         }
                   3612:     }
1.1354    raeburn  3613:     return $removed;
1.1352    raeburn  3614: }
                   3615: 
1.492     albertel 3616: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3617: 
                   3618: sub allowuploaded {
                   3619:     my ($srcurl,$url)=@_;
                   3620:     $url=&clutter(&declutter($url));
                   3621:     my $dir=$url;
                   3622:     $dir=~s/\/[^\/]+$//;
                   3623:     my %httpref=();
                   3624:     my $httpurl=&hreflocation('',$url);
                   3625:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3626:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3627: }
1.477     raeburn  3628: 
1.1193    raeburn  3629: #
                   3630: # Determine if the current user should be able to edit a particular resource,
                   3631: # when viewing in course context.
                   3632: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3633: #     Functions.
                   3634: # (b) When displaying folder contents in course editor, used to determine if
                   3635: #     "Edit" link will be displayed alongside resource.
                   3636: #
1.1196    raeburn  3637: #  input: six args -- filename (decluttered), course number, course domain,
                   3638: #                   url, symb (if registered) and group (if this is a group
                   3639: #                   item -- e.g., bulletin board, group page etc.).
                   3640: #  output: array of five scalars -- 
1.1193    raeburn  3641: #          $cfile -- url for file editing if editable on current server
                   3642: #          $home -- homeserver of resource (i.e., for author if published,
                   3643: #                                           or course if uploaded.).
                   3644: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3645: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3646: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3647: #
                   3648: 
                   3649: sub can_edit_resource {
1.1194    raeburn  3650:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3651:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3652: #
                   3653: # For aboutme pages user can only edit his/her own.
                   3654: #
1.1199    raeburn  3655:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3656:         my ($sdom,$sname) = ($1,$2);
                   3657:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3658:             $home = $env{'user.home'};
                   3659:             $cfile = $resurl;
                   3660:             if ($env{'form.forceedit'}) {
                   3661:                 $forceview = 1;
                   3662:             } else {
                   3663:                 $forceedit = 1;
                   3664:             }
                   3665:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3666:         } else {
                   3667:             return;
                   3668:         }
                   3669:     }
                   3670: 
                   3671:     if ($env{'request.course.id'}) {
                   3672:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3673:         if ($group ne '') {
                   3674: # if this is a group homepage or group bulletin board, check group privs
                   3675:             my $allowed = 0;
1.1197    raeburn  3676:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3677:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3678:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3679:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3680:                     $allowed = 1;
                   3681:                 }
1.1197    raeburn  3682:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3683:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3684:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3685:                     $allowed = 1;
                   3686:                 }
                   3687:             }
                   3688:             if ($allowed) {
                   3689:                 $home=&homeserver($cnum,$cdom);
                   3690:                 if ($env{'form.forceedit'}) {
                   3691:                     $forceview = 1;
                   3692:                 } else {
                   3693:                     $forceedit = 1;
                   3694:                 }
                   3695:                 $cfile = $resurl;
                   3696:             } else {
                   3697:                 return;
                   3698:             }
                   3699:         } else {
1.1208    raeburn  3700:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3701:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3702:                     return;
                   3703:                 }
                   3704:             } elsif (!$crsedit) {
1.1194    raeburn  3705: #
                   3706: # No edit allowed where CC has switched to student role.
                   3707: #
                   3708:                 return;
                   3709:             }
                   3710:         }
                   3711:     }
                   3712: 
1.1193    raeburn  3713:     if ($file ne '') {
                   3714:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3715:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3716:                 $uploaded = 1;
                   3717:                 $incourse = 1;
1.1193    raeburn  3718:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3719:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3720:                     if ($env{'form.forceedit'}) {
                   3721:                         $forceview = 1;
                   3722:                     } else {
                   3723:                         $forceedit = 1;
                   3724:                     }
1.1194    raeburn  3725:                 }
                   3726:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3727:                 $incourse = 1;
                   3728:                 if ($env{'form.forceedit'}) {
                   3729:                     $forceview = 1;
                   3730:                 } else {
                   3731:                     $forceedit = 1;
                   3732:                 }
                   3733:                 $cfile = $resurl;
                   3734:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3735:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3736:                     $incourse = 1;
                   3737:                     if ($env{'form.forceedit'}) {
                   3738:                         $forceview = 1;
                   3739:                     } else {
                   3740:                         $forceedit = 1;
                   3741:                     }
                   3742:                     $cfile = $resurl;
1.1199    raeburn  3743:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3744:                     $incourse = 1;
                   3745:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3746:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3747:                     $incourse = 1;
1.1199    raeburn  3748:                     if ($env{'form.forceedit'}) {
                   3749:                         $forceview = 1;
                   3750:                     } else {
                   3751:                         $forceedit = 1;
                   3752:                     }
                   3753:                     $cfile = $resurl;
1.1419    raeburn  3754:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3755:                     my ($map,$id,$res) = &decode_symb($symb);
                   3756:                     if ($map =~ /\.page$/) {
                   3757:                         $incourse = 1;
                   3758:                         if ($env{'form.forceedit'}) {
                   3759:                             $forceview = 1;
                   3760:                             $cfile = $map;
                   3761:                         } else {
                   3762:                             $forceedit = 1;
                   3763:                             $cfile =  '/adm/wrapper'.$resurl;
                   3764:                         }
                   3765:                     }
1.1343    raeburn  3766:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3767:                     $incourse = 1;
                   3768:                     if ($env{'form.forceedit'}) {
                   3769:                         $forceview = 1;
                   3770:                     } else {
                   3771:                         $forceedit = 1;
                   3772:                     }
                   3773:                     $cfile = $resurl;
1.1208    raeburn  3774:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3775:                     $incourse = 1;
                   3776:                     if ($env{'form.forceedit'}) {
                   3777:                         $forceview = 1;
                   3778:                     } else {
                   3779:                         $forceedit = 1;
                   3780:                     }
                   3781:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3782:                 }
                   3783:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3784:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3785:                 if (&is_on_map($template)) { 
                   3786:                     $incourse = 1;
                   3787:                     $forceview = 1;
                   3788:                     $cfile = $template;
1.1193    raeburn  3789:                 }
1.1199    raeburn  3790:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  3791:                 $incourse = 1;
                   3792:                 if ($env{'form.forceedit'}) {
                   3793:                     $forceview = 1;
                   3794:                 } else {
                   3795:                     $forceedit = 1;
                   3796:                 }
                   3797:                 $cfile = $resurl;
1.1343    raeburn  3798:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3799:                 $incourse = 1;
                   3800:                 if ($env{'form.forceedit'}) {
                   3801:                     $forceview = 1;
                   3802:                 } else {
                   3803:                     $forceedit = 1;
                   3804:                 }
                   3805:                 $cfile = $resurl;
1.1199    raeburn  3806:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3807:                 $incourse = 1;
                   3808:                 $forceview = 1;
                   3809:                 if ($symb) {
                   3810:                     my ($map,$id,$res)=&decode_symb($symb);
                   3811:                     $env{'request.symb'} = $symb;
                   3812:                     $cfile = &clutter($res);
                   3813:                 } else {
                   3814:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3815:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3816:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3817:                         $cfile = '/adm/wrapper'.$escfile;
                   3818:                     } else {
                   3819:                         $escfile =~ s{^http://}{};
                   3820:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3821:                     }
1.1199    raeburn  3822:                 }
1.1234    raeburn  3823:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3824:                 if ($env{'form.forceedit'}) {
                   3825:                     $forceview = 1;
                   3826:                 } else {
                   3827:                     $forceedit = 1;
                   3828:                 }
                   3829:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3830:             }
                   3831:         }
1.1194    raeburn  3832:         if ($uploaded || $incourse) {
                   3833:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3834:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3835:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3836:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3837:             # Check that the user has permission to edit this resource
                   3838:             my $setpriv = 1;
                   3839:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3840:             if (defined($cfudom)) {
                   3841:                 $home=&homeserver($cfuname,$cfudom);
                   3842:                 $cfile=$file;
                   3843:             }
                   3844:         }
1.1194    raeburn  3845:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3846:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3847:             my @ids=&current_machine_ids();
                   3848:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3849:                 $switchserver=1;
                   3850:             }
                   3851:         }
                   3852:     }
1.1194    raeburn  3853:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3854: }
                   3855: 
                   3856: sub is_course_upload {
                   3857:     my ($file,$cnum,$cdom) = @_;
                   3858:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3859:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3860:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3861:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3862:         return 1;
                   3863:     }
                   3864:     return;
                   3865: }
                   3866: 
1.1194    raeburn  3867: sub in_course {
1.1195    raeburn  3868:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3869:     if ($hideprivileged) {
                   3870:         my $skipuser;
1.1219    raeburn  3871:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3872:         my @possdoms = ($cdom);  
                   3873:         if ($coursehash{'checkforpriv'}) { 
                   3874:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3875:         }
                   3876:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3877:             $skipuser = 1;
                   3878:             if ($coursehash{'nothideprivileged'}) {
                   3879:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3880:                     my $user;
                   3881:                     if ($item =~ /:/) {
                   3882:                         $user = $item;
                   3883:                     } else {
                   3884:                         $user = join(':',split(/[\@]/,$item));
                   3885:                     }
                   3886:                     if ($user eq $uname.':'.$udom) {
                   3887:                         undef($skipuser);
                   3888:                         last;
                   3889:                     }
                   3890:                 }
                   3891:             }
                   3892:             if ($skipuser) {
                   3893:                 return 0;
                   3894:             }
                   3895:         }
                   3896:     }
1.1194    raeburn  3897:     $type ||= 'any';
                   3898:     if (!defined($cdom) || !defined($cnum)) {
                   3899:         my $cid  = $env{'request.course.id'};
                   3900:         $cdom = $env{'course.'.$cid.'.domain'};
                   3901:         $cnum = $env{'course.'.$cid.'.num'};
                   3902:     }
                   3903:     my $typesref;
1.1195    raeburn  3904:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3905:         $typesref = ['active','previous','future'];
                   3906:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3907:         $typesref = [$type];
                   3908:     }
                   3909:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3910:                               $typesref,undef,[$cdom]);
                   3911:     my ($tmp) = keys(%roles);
                   3912:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3913:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3914:     if (@course_roles > 0) {
                   3915:         return 1;
                   3916:     }
                   3917:     return 0;
                   3918: }
                   3919: 
1.478     albertel 3920: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3921: # input: action, courseID, current domain, intended
1.637     raeburn  3922: #        path to file, source of file, instruction to parse file for objects,
                   3923: #        ref to hash for embedded objects,
                   3924: #        ref to hash for codebase of java objects.
1.1095    raeburn  3925: #        reference to scalar to accommodate mime type determined
                   3926: #          from File::MMagic if $parser = parse.
1.637     raeburn  3927: #
1.485     raeburn  3928: # output: url to file (if action was uploaddoc), 
                   3929: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3930: #
1.478     albertel 3931: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3932: # course.
1.477     raeburn  3933: #
1.478     albertel 3934: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3935: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3936: #          course's home server.
1.477     raeburn  3937: #
1.478     albertel 3938: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3939: #          be copied from $source (current location) to 
                   3940: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3941: #         and will then be copied to
                   3942: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3943: #         course's home server.
1.485     raeburn  3944: #
1.481     raeburn  3945: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3946: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3947: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3948: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3949: #         in course's home server.
1.637     raeburn  3950: #
1.477     raeburn  3951: 
                   3952: sub process_coursefile {
1.1095    raeburn  3953:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3954:         $mimetype)=@_;
1.477     raeburn  3955:     my $fetchresult;
1.638     albertel 3956:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3957:     if ($action eq 'propagate') {
1.638     albertel 3958:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3959: 			     $home);
1.481     raeburn  3960:     } else {
1.477     raeburn  3961:         my $fpath = '';
                   3962:         my $fname = $file;
1.478     albertel 3963:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3964:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3965:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3966:         if ($action eq 'copy') {
                   3967:             if ($source eq '') {
                   3968:                 $fetchresult = 'no source file';
                   3969:                 return $fetchresult;
                   3970:             } else {
                   3971:                 my $destination = $filepath.'/'.$fname;
                   3972:                 rename($source,$destination);
                   3973:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3974:                                  $home);
1.481     raeburn  3975:             }
                   3976:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3977:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3978:             print $fh $env{'form.'.$source};
1.481     raeburn  3979:             close($fh);
1.637     raeburn  3980:             if ($parser eq 'parse') {
1.1024    raeburn  3981:                 my $mm = new File::MMagic;
1.1095    raeburn  3982:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3983:                 if ($type eq 'text/html') {
1.1024    raeburn  3984:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3985:                     unless ($parse_result eq 'ok') {
                   3986:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3987:                     }
1.637     raeburn  3988:                 }
1.1095    raeburn  3989:                 if (ref($mimetype)) {
                   3990:                     $$mimetype = $type;
                   3991:                 } 
1.637     raeburn  3992:             }
1.477     raeburn  3993:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3994:                                  $home);
1.481     raeburn  3995:             if ($fetchresult eq 'ok') {
                   3996:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3997:             } else {
                   3998:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3999:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4000:                 return '/adm/notfound.html';
                   4001:             }
1.477     raeburn  4002:         }
                   4003:     }
1.485     raeburn  4004:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4005:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4006:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4007:     }
                   4008:     return $fetchresult;
                   4009: }
                   4010: 
1.637     raeburn  4011: sub build_filepath {
                   4012:     my ($fpath) = @_;
                   4013:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4014:     unless ($fpath eq '') {
                   4015:         my @parts=split('/',$fpath);
                   4016:         foreach my $part (@parts) {
                   4017:             $filepath.= '/'.$part;
                   4018:             if ((-e $filepath)!=1) {
                   4019:                 mkdir($filepath,0777);
                   4020:             }
                   4021:         }
                   4022:     }
                   4023:     return $filepath;
                   4024: }
                   4025: 
                   4026: sub store_edited_file {
1.638     albertel 4027:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4028:     my $file = $primary_url;
                   4029:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4030:     my $fpath = '';
                   4031:     my $fname = $file;
                   4032:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4033:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4034:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4035:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4036:     print $fh $content;
                   4037:     close($fh);
1.638     albertel 4038:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4039:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4040: 			  $home);
1.637     raeburn  4041:     if ($$fetchresult eq 'ok') {
                   4042:         return '/uploaded/'.$fpath.'/'.$fname;
                   4043:     } else {
1.638     albertel 4044:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4045: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4046:         return '/adm/notfound.html';
                   4047:     }
                   4048: }
                   4049: 
1.531     albertel 4050: sub clean_filename {
1.831     albertel 4051:     my ($fname,$args)=@_;
1.315     www      4052: # Replace Windows backslashes by forward slashes
1.257     www      4053:     $fname=~s/\\/\//g;
1.831     albertel 4054:     if (!$args->{'keep_path'}) {
                   4055:         # Get rid of everything but the actual filename
                   4056: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4057:     }
1.315     www      4058: # Replace spaces by underscores
                   4059:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4060: # Transliterate non-ascii text to ascii
                   4061:     my $lang = &Apache::lonlocal::current_language();
                   4062:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4063: # Replace all other weird characters by nothing
1.831     albertel 4064:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4065: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4066: # numbers
                   4067:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 4068:     return $fname;
                   4069: }
1.1406    raeburn  4070: 
1.1051    raeburn  4071: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4072: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4073: # image with the same aspect ratio as the original, but with dimensions which do 
                   4074: # not exceed $resizewidth and $resizeheight.
                   4075:  
1.984     neumanie 4076: sub resizeImage {
1.1051    raeburn  4077:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4078:     my $ima = Image::Magick->new;
                   4079:     my $resized;
                   4080:     if (-e $img_path) {
                   4081:         $ima->Read($img_path);
                   4082:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4083:             my $width = $ima->Get('width');
                   4084:             my $height = $ima->Get('height');
                   4085:             if ($width > $resizewidth) {
                   4086: 	        my $factor = $width/$resizewidth;
                   4087:                 my $newheight = $height/$factor;
                   4088:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4089:                 $resized = 1;
                   4090:             }
                   4091:         }
                   4092:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4093:             my $width = $ima->Get('width');
                   4094:             my $height = $ima->Get('height');
                   4095:             if ($height > $resizeheight) {
                   4096:                 my $factor = $height/$resizeheight;
                   4097:                 my $newwidth = $width/$factor;
                   4098:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4099:                 $resized = 1;
                   4100:             }
                   4101:         }
                   4102:         if ($resized) {
                   4103:             $ima->Write($img_path);
                   4104:         }
                   4105:     }
                   4106:     return;
1.977     amueller 4107: }
                   4108: 
1.608     albertel 4109: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4110: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4111: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4112: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4113: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4114: #                   if 'coursedoc': upload to the current course
                   4115: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4116: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4117: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4118: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4119: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4120: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4121: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4122: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4123: #        $allfiles - reference to hash for embedded objects
                   4124: #        $codebase - reference to hash for codebase of java objects
                   4125: #        $desuname - username for permanent storage of uploaded file
                   4126: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4127: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4128: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4129: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4130: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4131: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4132: #                    from File::MMagic.
1.858     raeburn  4133: # 
1.686     albertel 4134: # output: url of file in userspace, or error: <message> 
                   4135: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4136: 
1.531     albertel 4137: sub userfileupload {
1.1090    raeburn  4138:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4139:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4140:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4141:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4142:     $fname=&clean_filename($fname);
1.1090    raeburn  4143:     # See if there is anything left
1.257     www      4144:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4145:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4146:     if ($fname =~ /^\./) {
                   4147:         my ($s,$usec) = &gettimeofday();
                   4148:         while (length($usec) < 6) {
                   4149:             $usec = '0'.$usec;
                   4150:         }
                   4151:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4152:     }
1.1090    raeburn  4153:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4154:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4155:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4156:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4157:         my $now = time;
1.1090    raeburn  4158:         my $filepath;
1.1095    raeburn  4159:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4160:              $filepath = 'tmp/helprequests/'.$now;
                   4161:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4162:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4163:                          '_'.$env{'user.domain'}.'/pending';
                   4164:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4165:             my ($docuname,$docudom);
1.1350    raeburn  4166:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4167:                 $docudom = $destudom;
                   4168:             } else {
                   4169:                 $docudom = $env{'user.domain'};
                   4170:             }
1.1350    raeburn  4171:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4172:                 $docuname = $destuname;
                   4173:             } else {
                   4174:                 $docuname = $env{'user.name'};
                   4175:             }
                   4176:             if (exists($env{'form.group'})) {
                   4177:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4178:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4179:             }
                   4180:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4181:             if ($context eq 'canceloverwrite') {
                   4182:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4183:                 if (-e  $tempfile) {
                   4184:                     my @info = stat($tempfile);
                   4185:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4186:                         unlink($tempfile);
                   4187:                     }
                   4188:                 }
                   4189:                 return;
1.523     raeburn  4190:             }
                   4191:         }
1.1090    raeburn  4192:         # Create the directory if not present
1.741     raeburn  4193:         my @parts=split(/\//,$filepath);
                   4194:         my $fullpath = $perlvar{'lonDaemons'};
                   4195:         for (my $i=0;$i<@parts;$i++) {
                   4196:             $fullpath .= '/'.$parts[$i];
                   4197:             if ((-e $fullpath)!=1) {
                   4198:                 mkdir($fullpath,0777);
                   4199:             }
                   4200:         }
1.1359    raeburn  4201:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4202:         print $fh $env{'form.'.$formname};
                   4203:         close($fh);
1.1090    raeburn  4204:         if ($context eq 'existingfile') {
                   4205:             my @info = stat($fullpath.'/'.$fname);
                   4206:             return ($fullpath.'/'.$fname,$info[9]);
                   4207:         } else {
                   4208:             return $fullpath.'/'.$fname;
                   4209:         }
1.523     raeburn  4210:     }
1.995     raeburn  4211:     if ($subdir eq 'scantron') {
                   4212:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4213:     } else {
1.995     raeburn  4214:         $fname="$subdir/$fname";
                   4215:     }
1.1090    raeburn  4216:     if ($context eq 'coursedoc') {
1.638     albertel 4217: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4218: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4219:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4220:             return &finishuserfileupload($docuname,$docudom,
                   4221: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4222: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4223:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4224:         } else {
1.1218    raeburn  4225:             if ($env{'form.folder'}) {
                   4226:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4227:             }
1.638     albertel 4228:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4229: 				       $fname,$formname,$parser,
1.1095    raeburn  4230: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4231:         }
1.719     banghart 4232:     } elsif (defined($destuname)) {
                   4233:         my $docuname=$destuname;
                   4234:         my $docudom=$destudom;
1.860     raeburn  4235: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4236: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4237:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4238:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4239:     } else {
1.638     albertel 4240:         my $docuname=$env{'user.name'};
                   4241:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4242:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4243:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4244:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4245:         }
1.860     raeburn  4246: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4247: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4248:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4249:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4250:     }
1.271     www      4251: }
                   4252: 
                   4253: sub finishuserfileupload {
1.860     raeburn  4254:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4255:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4256:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4257:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4258:   
1.860     raeburn  4259:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4260:     $file=$fname;
                   4261:     if ($fname=~m|/|) {
                   4262:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4263: 	$path.=$fnamepath.'/';
                   4264:     }
1.259     www      4265:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4266:     my $count;
                   4267:     for ($count=4;$count<=$#parts;$count++) {
                   4268:         $filepath.="/$parts[$count]";
                   4269:         if ((-e $filepath)!=1) {
                   4270: 	    mkdir($filepath,0777);
                   4271:         }
                   4272:     }
1.984     neumanie 4273: 
1.258     www      4274: # Save the file
                   4275:     {
1.1359    raeburn  4276: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4277: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4278: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4279: 	    return '/adm/notfound.html';
                   4280: 	}
1.1090    raeburn  4281:         if ($context eq 'overwrite') {
1.1117    foxr     4282:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4283:             my $target = $filepath.'/'.$file;
                   4284:             if (-e $source) {
                   4285:                 my @info = stat($source);
                   4286:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4287:                     unless (&File::Copy::move($source,$target)) {
                   4288:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4289:                         return "Moving from $source failed";
                   4290:                     }
                   4291:                 } else {
                   4292:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4293:                 }
                   4294:             } else {
                   4295:                 return "Temporary file: $source missing";
                   4296:             }
                   4297:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4298: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4299: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4300: 	    return '/adm/notfound.html';
                   4301: 	}
1.570     albertel 4302: 	close(FH);
1.1051    raeburn  4303:         if ($resizewidth && $resizeheight) {
                   4304:             my $mm = new File::MMagic;
                   4305:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4306:             if ($mime_type =~ m{^image/}) {
                   4307: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4308:             }  
1.977     amueller 4309: 	}
1.258     www      4310:     }
1.1152    raeburn  4311:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4312:         if (ref($mimetype)) {
                   4313:             if ($$mimetype eq '') {
                   4314:                 my $mm = new File::MMagic;
                   4315:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4316:                 $$mimetype = $type;
                   4317:             }
                   4318:         }
                   4319:     }
1.1401    raeburn  4320:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4321:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4322:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4323:                                                        $allfiles,$codebase);
                   4324:             unless ($parse_result eq 'ok') {
                   4325:                 &logthis('Failed to parse '.$filepath.$file.
                   4326: 	   	         ' for embedded media: '.$parse_result); 
                   4327:             }
1.637     raeburn  4328:         }
1.1401    raeburn  4329:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4330:         my $format = $env{'form.scantron_format'};
                   4331:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4332:     }
1.860     raeburn  4333:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4334:         my $input = $filepath.'/'.$file;
                   4335:         my $output = $filepath.'/'.'tn-'.$file;
                   4336:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4337:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4338:         system({$args[0]} @args);
1.860     raeburn  4339:         if (-e $filepath.'/'.'tn-'.$file) {
                   4340:             $fetchthumb  = 1; 
                   4341:         }
                   4342:     }
1.858     raeburn  4343:  
1.259     www      4344: # Notify homeserver to grep it
                   4345: #
1.984     neumanie 4346:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4347:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4348:     if ($fetchresult eq 'ok') {
1.860     raeburn  4349:         if ($fetchthumb) {
                   4350:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4351:             if ($thumbresult ne 'ok') {
                   4352:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4353:                          $docuhome.': '.$thumbresult);
                   4354:             }
                   4355:         }
1.259     www      4356: #
1.258     www      4357: # Return the URL to it
1.494     albertel 4358:         return '/uploaded/'.$path.$file;
1.263     www      4359:     } else {
1.494     albertel 4360:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4361: 		 ': '.$fetchresult);
1.263     www      4362:         return '/adm/notfound.html';
1.858     raeburn  4363:     }
1.493     albertel 4364: }
                   4365: 
1.637     raeburn  4366: sub extract_embedded_items {
1.961     raeburn  4367:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4368:     my @state = ();
1.1164    raeburn  4369:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4370:     my %javafiles = (
                   4371:                       codebase => '',
                   4372:                       code => '',
                   4373:                       archive => ''
                   4374:                     );
                   4375:     my %mediafiles = (
                   4376:                       src => '',
                   4377:                       movie => '',
                   4378:                      );
1.648     raeburn  4379:     my $p;
                   4380:     if ($content) {
                   4381:         $p = HTML::LCParser->new($content);
                   4382:     } else {
1.961     raeburn  4383:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4384:     }
1.641     albertel 4385:     while (my $t=$p->get_token()) {
1.640     albertel 4386: 	if ($t->[0] eq 'S') {
                   4387: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4388: 	    push(@state, $tagname);
1.648     raeburn  4389:             if (lc($tagname) eq 'allow') {
                   4390:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4391:             }
1.640     albertel 4392: 	    if (lc($tagname) eq 'img') {
                   4393: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4394: 	    }
1.886     albertel 4395: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4396:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4397:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4398:                 }
1.886     albertel 4399: 	    }
1.645     raeburn  4400:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4401:                 my $src;
1.645     raeburn  4402:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4403:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4404:                 } else {
1.1164    raeburn  4405:                     if ($attr->{'src'} ne '') {
                   4406:                         $src = $attr->{'src'};
                   4407:                         &add_filetype($allfiles,$src,'src');
                   4408:                     }
                   4409:                 }
                   4410:                 my $text = $p->get_trimmed_text();
                   4411:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4412:                     my @swfargs = split(/,/,$1);
                   4413:                     foreach my $item (@swfargs) {
                   4414:                         $item =~ s/["']//g;
                   4415:                         $item =~ s/^\s+//;
                   4416:                         $item =~ s/\s+$//;
                   4417:                     }
                   4418:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4419:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4420:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4421:                         } else {
                   4422:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4423:                         }
                   4424:                     }
1.645     raeburn  4425:                 }
                   4426:             }
                   4427:             if (lc($tagname) eq 'link') {
                   4428:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4429:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4430:                 }
                   4431:             }
1.640     albertel 4432: 	    if (lc($tagname) eq 'object' ||
                   4433: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4434: 		foreach my $item (keys(%javafiles)) {
                   4435: 		    $javafiles{$item} = '';
                   4436: 		}
1.1164    raeburn  4437:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4438:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4439:                 }
1.640     albertel 4440: 	    }
                   4441: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4442: 		my $name = lc($attr->{'name'});
                   4443: 		foreach my $item (keys(%javafiles)) {
                   4444: 		    if ($name eq $item) {
                   4445: 			$javafiles{$item} = $attr->{'value'};
                   4446: 			last;
                   4447: 		    }
                   4448: 		}
1.1164    raeburn  4449:                 my $pathfrom;
1.640     albertel 4450: 		foreach my $item (keys(%mediafiles)) {
                   4451: 		    if ($name eq $item) {
1.1164    raeburn  4452:                         $pathfrom = $attr->{'value'};
                   4453:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4454: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4455: 			last;
                   4456: 		    }
                   4457: 		}
1.1164    raeburn  4458:                 if ($name eq 'flashvars') {
                   4459:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4460:                 }
                   4461:                 if ($pathfrom ne '') {
                   4462:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4463:                                          $pathfrom);
                   4464:                 }
1.640     albertel 4465: 	    }
                   4466: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4467: 		foreach my $item (keys(%javafiles)) {
                   4468: 		    if ($attr->{$item}) {
                   4469: 			$javafiles{$item} = $attr->{$item};
                   4470: 			last;
                   4471: 		    }
                   4472: 		}
                   4473: 		foreach my $item (keys(%mediafiles)) {
                   4474: 		    if ($attr->{$item}) {
                   4475: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4476: 			last;
                   4477: 		    }
                   4478: 		}
1.1164    raeburn  4479:                 if (lc($tagname) eq 'embed') {
                   4480:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4481:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4482:                                              $attr->{'src'});
                   4483:                     }
                   4484:                 }
1.640     albertel 4485: 	    }
1.1243    raeburn  4486:             if (lc($tagname) eq 'iframe') {
                   4487:                 my $src = $attr->{'src'} ;
                   4488:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4489:                     &add_filetype($allfiles,$src,'src');
                   4490:                 } elsif ($src =~ m{^/}) {
                   4491:                     if ($env{'request.course.id'}) {
                   4492:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4493:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4494:                         my $url = &hreflocation('',$fullpath);
                   4495:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4496:                             my $relpath = $1;
                   4497:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4498:                                 &add_filetype($allfiles,$1,'src');
                   4499:                             }
                   4500:                         }
                   4501:                     }
                   4502:                 }
                   4503:             }
1.1164    raeburn  4504:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4505:                 pop(@state);
1.1164    raeburn  4506:             }
1.640     albertel 4507: 	} elsif ($t->[0] eq 'E') {
                   4508: 	    my ($tagname) = ($t->[1]);
                   4509: 	    if ($javafiles{'codebase'} ne '') {
                   4510: 		$javafiles{'codebase'} .= '/';
                   4511: 	    }  
                   4512: 	    if (lc($tagname) eq 'applet' ||
                   4513: 		lc($tagname) eq 'object' ||
                   4514: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4515: 		) {
                   4516: 		foreach my $item (keys(%javafiles)) {
                   4517: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4518: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4519: 			&add_filetype($allfiles,$file,$item);
                   4520: 		    }
                   4521: 		}
                   4522: 	    } 
                   4523: 	    pop @state;
                   4524: 	}
                   4525:     }
1.1164    raeburn  4526:     foreach my $id (sort(keys(%flashvars))) {
                   4527:         if ($shockwave{$id} ne '') {
                   4528:             my @pairs = split(/\&/,$flashvars{$id});
                   4529:             foreach my $pair (@pairs) {
                   4530:                 my ($key,$value) = split(/\=/,$pair);
                   4531:                 if ($key eq 'thumb') {
                   4532:                     &add_filetype($allfiles,$value,$key);
                   4533:                 } elsif ($key eq 'content') {
                   4534:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4535:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4536:                     if ($ext ne '') {
                   4537:                         &add_filetype($allfiles,$path.$value,$ext);
                   4538:                     }
                   4539:                 }
                   4540:             }
                   4541:         }
                   4542:     }
1.637     raeburn  4543:     return 'ok';
                   4544: }
                   4545: 
1.639     albertel 4546: sub add_filetype {
                   4547:     my ($allfiles,$file,$type)=@_;
                   4548:     if (exists($allfiles->{$file})) {
                   4549: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4550: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4551: 	}
                   4552:     } else {
                   4553: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4554:     }
                   4555: }
                   4556: 
1.1164    raeburn  4557: sub embedded_dependency {
                   4558:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4559:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4560:         if (($identifier ne '') &&
                   4561:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4562:             ($pathfrom ne '')) {
                   4563:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4564:             foreach my $dep (@{$related->{$identifier}}) {
                   4565:                 &add_filetype($allfiles,$path.$dep,'object');
                   4566:             }
                   4567:         }
                   4568:     }
                   4569:     return;
                   4570: }
                   4571: 
1.1401    raeburn  4572: sub bubblesheet_converter {
                   4573:     my ($cdom,$fullpath,$config,$format) = @_;
                   4574:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4575:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4576:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4577:         my (%csvcols,%csvoptions);
                   4578:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4579:             %csvcols = %{$config->{'fields'}};
                   4580:         }
                   4581:         if (ref($config->{'options'}) eq 'HASH') {
                   4582:             %csvoptions = %{$config->{'options'}};
                   4583:         }
1.1401    raeburn  4584:         my %csvbynum = reverse(%csvcols);
                   4585:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4586:         if (keys(%scantronconf)) {
                   4587:             my %bynum = (
                   4588:                           $scantronconf{CODEstart} => 'CODEstart',
                   4589:                           $scantronconf{IDstart}   => 'IDstart',
                   4590:                           $scantronconf{PaperID}   => 'PaperID',
                   4591:                           $scantronconf{FirstName} => 'FirstName',
                   4592:                           $scantronconf{LastName}  => 'LastName',
                   4593:                           $scantronconf{Qstart}    => 'Qstart',
                   4594:                         );
                   4595:             my @ordered;
                   4596:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4597:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4598:             }
                   4599:             my %mapstart = (
                   4600:                               CODEstart => 'CODE',
                   4601:                               IDstart   => 'ID',
                   4602:                               PaperID   => 'PaperID',
                   4603:                               FirstName => 'FirstName',
                   4604:                               LastName  => 'LastName',
                   4605:                               Qstart    => 'FirstQuestion',
                   4606:                            );
                   4607:             my %maplength = (
                   4608:                               CODEstart => 'CODElength',
                   4609:                               IDstart   => 'IDlength',
                   4610:                               PaperID   => 'PaperIDlength',
                   4611:                               FirstName => 'FirstNamelength',
                   4612:                               LastName  => 'LastNamelength',
                   4613:             );
                   4614:             if (open(my $fh,'<',$fullpath)) {
                   4615:                 my $output;
1.1403    raeburn  4616:                 my %lettdig = &letter_to_digits();
                   4617:                 my %diglett = reverse(%lettdig);
                   4618:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4619:                 my $num = 0;
1.1401    raeburn  4620:                 while (my $line=<$fh>) {
1.1404    raeburn  4621:                     $num ++;
                   4622:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4623:                     $line =~ s{[\r\n]+$}{};
                   4624:                     my %found;
                   4625:                     my @values = split(/,/,$line);
                   4626:                     my ($qstart,$record);
                   4627:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4628:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4629:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4630:                             if ($values[$i] eq '') {
                   4631:                                 $values[$i] = $scantronconf{'Qoff'};
                   4632:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4633:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4634:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4635:                                 }
                   4636:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4637:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4638:                                     $values[$i] = $diglett{$values[$i]};
                   4639:                                 }
                   4640:                             } else {
                   4641:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4642:                                     my $digit;
                   4643:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4644:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4645:                                         if ($values[$i] eq 'J') {
                   4646:                                             $digit += $numletts;
                   4647:                                         }
                   4648:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4649:                                         $digit = $values[$i]-1;
                   4650:                                         if ($values[$i] eq '0') {
                   4651:                                             $digit += $numletts;
                   4652:                                         }
                   4653:                                     }
                   4654:                                     my $qval='';
                   4655:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4656:                                         if ($j == $digit) {
                   4657:                                             $qval .= $scantronconf{'Qon'};
                   4658:                                         } else {
                   4659:                                             $qval .= $scantronconf{'Qoff'};
                   4660:                                         }
                   4661:                                     }
                   4662:                                     $values[$i] = $qval;
                   4663:                                 }
                   4664:                             }
                   4665:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4666:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4667:                             }
                   4668:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4669:                             if ($numblank > 0) {
                   4670:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4671:                             }
1.1401    raeburn  4672:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4673:                                 $qstart = $i;
1.1403    raeburn  4674:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4675:                             } else {
1.1403    raeburn  4676:                                 $found{'FirstQuestion'} .= $values[$i];
                   4677:                             }
                   4678:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4679:                             if ($csvoptions{'rem'}) {
                   4680:                                 $values[$i] =~ s/^\s+//;
                   4681:                             }
                   4682:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4683:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4684:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4685:                                 }
                   4686:                             }
                   4687:                             $found{$csvbynum{$i}} = $values[$i];
                   4688:                         }
                   4689:                     }
                   4690:                     foreach my $item (@ordered) {
                   4691:                         my $currlength = 1+length($record);
                   4692:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4693:                         if ($numspaces > 0) {
                   4694:                             $record .= (' ' x $numspaces);
                   4695:                         }
                   4696:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4697:                             unless ($item eq 'Qstart') {
                   4698:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4699:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4700:                                 }
                   4701:                             }
                   4702:                             $record .= $found{$mapstart{$item}};
                   4703:                         }
                   4704:                     }
                   4705:                     $output .= "$record\n";
                   4706:                 }
                   4707:                 close($fh);
                   4708:                 if ($output) {
                   4709:                     if (open(my $fh,'>',$fullpath)) {
                   4710:                         print $fh $output;
                   4711:                         close($fh);
                   4712:                     }
                   4713:                 }
                   4714:             }
                   4715:         }
                   4716:         return;
                   4717:     }
                   4718: }
                   4719: 
1.1403    raeburn  4720: sub letter_to_digits {
                   4721:     my %lettdig = (
                   4722:                     A => 1,
                   4723:                     B => 2,
                   4724:                     C => 3,
                   4725:                     D => 4,
                   4726:                     E => 5,
                   4727:                     F => 6,
                   4728:                     G => 7,
                   4729:                     H => 8,
                   4730:                     I => 9,
                   4731:                     J => 0,
                   4732:                   );
                   4733:     return %lettdig;
                   4734: }
                   4735: 
1.1401    raeburn  4736: sub get_scantron_config {
                   4737:     my ($which,$cdom) = @_;
                   4738:     my @lines = &get_scantronformat_file($cdom);
                   4739:     my %config;
                   4740:     #FIXME probably should move to XML it has already gotten a bit much now
                   4741:     foreach my $line (@lines) {
                   4742:         my ($name,$descrip)=split(/:/,$line);
                   4743:         if ($name ne $which ) { next; }
                   4744:         chomp($line);
                   4745:         my @config=split(/:/,$line);
                   4746:         $config{'name'}=$config[0];
                   4747:         $config{'description'}=$config[1];
                   4748:         $config{'CODElocation'}=$config[2];
                   4749:         $config{'CODEstart'}=$config[3];
                   4750:         $config{'CODElength'}=$config[4];
                   4751:         $config{'IDstart'}=$config[5];
                   4752:         $config{'IDlength'}=$config[6];
                   4753:         $config{'Qstart'}=$config[7];
                   4754:         $config{'Qlength'}=$config[8];
                   4755:         $config{'Qoff'}=$config[9];
                   4756:         $config{'Qon'}=$config[10];
                   4757:         $config{'PaperID'}=$config[11];
                   4758:         $config{'PaperIDlength'}=$config[12];
                   4759:         $config{'FirstName'}=$config[13];
                   4760:         $config{'FirstNamelength'}=$config[14];
                   4761:         $config{'LastName'}=$config[15];
                   4762:         $config{'LastNamelength'}=$config[16];
                   4763:         $config{'BubblesPerRow'}=$config[17];
                   4764:         last;
                   4765:     }
                   4766:     return %config;
                   4767: }
                   4768: 
                   4769: sub get_scantronformat_file {
                   4770:     my ($cdom) = @_;
                   4771:     if ($cdom eq '') {
                   4772:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4773:     }
                   4774:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4775:     my $gottab = 0;
                   4776:     my @lines;
                   4777:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4778:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4779:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4780:             if ($formatfile ne '-1') {
                   4781:                 @lines = split("\n",$formatfile,-1);
                   4782:                 $gottab = 1;
                   4783:             }
                   4784:         }
                   4785:     }
                   4786:     if (!$gottab) {
                   4787:         my $confname = $cdom.'-domainconfig';
                   4788:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4789:         my $formatfile = &getfile($default);
                   4790:         if ($formatfile ne '-1') {
                   4791:             @lines = split("\n",$formatfile,-1);
                   4792:             $gottab = 1;
                   4793:         }
                   4794:     }
                   4795:     if (!$gottab) {
                   4796:         my @domains = &current_machine_domains();
                   4797:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4798:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4799:                 @lines = <$fh>;
                   4800:                 close($fh);
1.1403    raeburn  4801:             }
1.1401    raeburn  4802:         } else {
                   4803:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4804:                 @lines = <$fh>;
                   4805:                 close($fh);
                   4806:             }
                   4807:         }
                   4808:     }
                   4809:     return @lines;
                   4810: }
                   4811: 
1.493     albertel 4812: sub removeuploadedurl {
1.984     neumanie 4813:     my ($url)=@_;	
                   4814:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4815:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4816: }
                   4817: 
                   4818: sub removeuserfile {
                   4819:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4820:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4821:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4822:     if ($result eq 'ok') {	
1.798     raeburn  4823:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4824:             my $metafile = $fname.'.meta';
                   4825:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4826: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4827:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4828:             my $sqlresult = 
1.823     albertel 4829:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4830:                                         'portfolio_metadata',$group,
                   4831:                                         'delete');
1.798     raeburn  4832:         }
                   4833:     }
                   4834:     return $result;
1.257     www      4835: }
1.15      www      4836: 
1.530     albertel 4837: sub mkdiruserfile {
                   4838:     my ($docuname,$docudom,$dir)=@_;
                   4839:     my $home=&homeserver($docuname,$docudom);
                   4840:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4841: }
                   4842: 
1.531     albertel 4843: sub renameuserfile {
                   4844:     my ($docuname,$docudom,$old,$new)=@_;
                   4845:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4846:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4847:                         &escape("$old").':'.&escape("$new"),$home);
                   4848:     if ($result eq 'ok') {
                   4849:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4850:             my $oldmeta = $old.'.meta';
                   4851:             my $newmeta = $new.'.meta';
                   4852:             my $metaresult = 
                   4853:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4854: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4855:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4856:             my $sqlresult = 
1.823     albertel 4857:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4858:                                         'portfolio_metadata',$group,
                   4859:                                         'delete');
1.798     raeburn  4860:         }
                   4861:     }
                   4862:     return $result;
1.531     albertel 4863: }
                   4864: 
1.14      www      4865: # ------------------------------------------------------------------------- Log
                   4866: 
                   4867: sub log {
                   4868:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4869:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4870: }
                   4871: 
                   4872: # ------------------------------------------------------------------ Course Log
1.352     www      4873: #
                   4874: # This routine flushes several buffers of non-mission-critical nature
                   4875: #
1.157     www      4876: 
                   4877: sub flushcourselogs {
1.352     www      4878:     &logthis('Flushing log buffers');
                   4879: #
                   4880: # course logs
                   4881: # This is a log of all transactions in a course, which can be used
                   4882: # for data mining purposes
                   4883: #
                   4884: # It also collects the courseid database, which lists last transaction
                   4885: # times and course titles for all courseids
                   4886: #
                   4887:     my %courseidbuffer=();
1.921     raeburn  4888:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4889:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4890: 		          &escape($courselogs{$crsid}),
                   4891: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4892: 	    delete $courselogs{$crsid};
                   4893:         } else {
                   4894:             &logthis('Failed to flush log buffer for '.$crsid);
                   4895:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4896:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4897:                         " exceeded maximum size, deleting.</font>");
                   4898:                delete $courselogs{$crsid};
                   4899:             }
1.352     www      4900:         }
1.920     raeburn  4901:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4902:             'description' => $coursedescrbuf{$crsid},
                   4903:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4904:             'type'        => $coursetypebuf{$crsid},
                   4905:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4906:         };
1.191     harris41 4907:     }
1.352     www      4908: #
                   4909: # Write course id database (reverse lookup) to homeserver of courses 
                   4910: # Is used in pickcourse
                   4911: #
1.840     albertel 4912:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4913:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4914:                                     $courseidbuffer{$crs_home},
                   4915:                                     $crs_home,'timeonly');
1.352     www      4916:     }
                   4917: #
                   4918: # File accesses
                   4919: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4920: #
1.449     matthew  4921:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4922:         if ($entry =~ /___count$/) {
                   4923:             my ($dom,$name);
1.807     albertel 4924:             ($dom,$name,undef)=
1.811     albertel 4925: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4926:             if (! defined($dom) || $dom eq '' || 
                   4927:                 ! defined($name) || $name eq '') {
1.620     albertel 4928:                 my $cid = $env{'request.course.id'};
                   4929:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4930:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4931:             }
1.450     matthew  4932:             my $value = $accesshash{$entry};
                   4933:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4934:             my %temphash=($url => $value);
1.449     matthew  4935:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4936:             if ($result eq 'ok') {
                   4937:                 delete $accesshash{$entry};
                   4938:             }
                   4939:         } else {
1.811     albertel 4940:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4941:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4942:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4943:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4944:                 delete $accesshash{$entry};
                   4945:             }
1.185     www      4946:         }
1.191     harris41 4947:     }
1.352     www      4948: #
                   4949: # Roles
                   4950: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4951: #
1.800     albertel 4952:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4953:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4954: 	    split(/\:/,$entry);
                   4955:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4956:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4957:                 $rudom,$runame) eq 'ok') {
                   4958: 	    delete $userrolehash{$entry};
                   4959:         }
                   4960:     }
1.662     raeburn  4961: #
1.1334    raeburn  4962: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4963: #
                   4964:     my %domrolebuffer = ();
1.1000    raeburn  4965:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4966:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4967:         if ($domrolebuffer{$rudom}) {
                   4968:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4969:                       '='.&escape($domainrolehash{$entry});
                   4970:         } else {
                   4971:             $domrolebuffer{$rudom}.=&escape($entry).
                   4972:                       '='.&escape($domainrolehash{$entry});
                   4973:         }
                   4974:         delete $domainrolehash{$entry};
                   4975:     }
                   4976:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4977: 	my %servers;
                   4978: 	if (defined(&domain($dom,'primary'))) {
                   4979: 	    my $primary=&domain($dom,'primary');
                   4980: 	    my $hostname=&hostname($primary);
                   4981: 	    $servers{$primary} = $hostname;
                   4982: 	} else { 
                   4983: 	    %servers = &get_servers($dom,'library');
                   4984: 	}
1.841     albertel 4985: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4986: 	    if (&reply('domroleput:'.$dom.':'.
                   4987: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4988: 		last;
                   4989: 	    } else {  
1.841     albertel 4990: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4991: 	    }
1.662     raeburn  4992:         }
                   4993:     }
1.186     www      4994:     $dumpcount++;
1.157     www      4995: }
                   4996: 
                   4997: sub courselog {
                   4998:     my $what=shift;
1.158     www      4999:     $what=time.':'.$what;
1.620     albertel 5000:     unless ($env{'request.course.id'}) { return ''; }
                   5001:     $coursedombuf{$env{'request.course.id'}}=
                   5002:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5003:     $coursenumbuf{$env{'request.course.id'}}=
                   5004:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5005:     $coursehombuf{$env{'request.course.id'}}=
                   5006:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5007:     $coursedescrbuf{$env{'request.course.id'}}=
                   5008:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5009:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5010:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5011:     $courseownerbuf{$env{'request.course.id'}}=
                   5012:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5013:     $coursetypebuf{$env{'request.course.id'}}=
                   5014:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5015:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5016: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5017:     } else {
1.620     albertel 5018: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5019:     }
1.620     albertel 5020:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5021: 	&flushcourselogs();
                   5022:     }
1.158     www      5023: }
                   5024: 
                   5025: sub courseacclog {
                   5026:     my $fnsymb=shift;
1.620     albertel 5027:     unless ($env{'request.course.id'}) { return ''; }
                   5028:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5029:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5030:         $what.=':POST';
1.583     matthew  5031:         # FIXME: Probably ought to escape things....
1.800     albertel 5032: 	foreach my $key (keys(%env)) {
                   5033:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5034:                 my $formitem = $1;
                   5035:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5036:                     $what.=':'.$formitem.'='.$env{$key};
                   5037:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5038:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5039:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5040:                     } else {
                   5041:                         $what.=':'.$formitem.'='.$env{$key};
                   5042:                     }
1.975     raeburn  5043:                 }
1.158     www      5044:             }
1.191     harris41 5045:         }
1.583     matthew  5046:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5047:         # FIXME: We should not be depending on a form parameter that someone
                   5048:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5049:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5050:             $what.= ':POST';
                   5051:             # FIXME: Probably ought to escape things....
                   5052:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5053:                                  'crsdiscuss') {
1.620     albertel 5054:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5055:             }
                   5056:         }
1.158     www      5057:     }
                   5058:     &courselog($what);
1.149     www      5059: }
                   5060: 
1.185     www      5061: sub countacc {
                   5062:     my $url=&declutter(shift);
1.458     matthew  5063:     return if (! defined($url) || $url eq '');
1.620     albertel 5064:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5065: #
                   5066: # Mark that this url was used in this course
                   5067: #
1.620     albertel 5068:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5069: #
                   5070: # Increase the access count for this resource in this child process
                   5071: #
1.281     www      5072:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5073:     $accesshash{$key}++;
1.185     www      5074: }
1.349     www      5075: 
1.361     www      5076: sub linklog {
                   5077:     my ($from,$to)=@_;
                   5078:     $from=&declutter($from);
                   5079:     $to=&declutter($to);
                   5080:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5081:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5082: }
1.1160    www      5083: 
                   5084: sub statslog {
                   5085:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5086:     if ($users<2) { return; }
                   5087:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5088:             'course'       => $env{'request.course.id'},
                   5089:             'sections'     => '"all"',
                   5090:             'num_students' => $users,
                   5091:             'part'         => $part,
                   5092:             'symb'         => $symb,
                   5093:             'mean_tries'   => $av_attempts,
                   5094:             'deg_of_diff'  => $degdiff});
                   5095:     foreach my $key (keys(%dynstore)) {
                   5096:         $accesshash{$key}=$dynstore{$key};
                   5097:     }
                   5098: }
1.361     www      5099:   
1.349     www      5100: sub userrolelog {
                   5101:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5102:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5103:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5104:        $userrolehash
                   5105:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5106:                     =$tend.':'.$tstart;
1.662     raeburn  5107:     }
1.1169    droeschl 5108:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5109:        $userrolehash
                   5110:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5111:                     =$tend.':'.$tstart;
                   5112:     }
1.1334    raeburn  5113:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5114:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5115:        $domainrolehash
                   5116:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5117:                     = $tend.':'.$tstart;
                   5118:     }
1.351     www      5119: }
                   5120: 
1.957     raeburn  5121: sub courserolelog {
                   5122:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5123:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5124:         my $cdom = $1;
                   5125:         my $cnum = $2;
                   5126:         my $sec = $3;
                   5127:         my $namespace = 'rolelog';
                   5128:         my %storehash = (
                   5129:                            role    => $trole,
                   5130:                            start   => $tstart,
                   5131:                            end     => $tend,
                   5132:                            selfenroll => $selfenroll,
                   5133:                            context    => $context,
                   5134:                         );
                   5135:         if ($trole eq 'gr') {
                   5136:             $namespace = 'groupslog';
                   5137:             $storehash{'group'} = $sec;
                   5138:         } else {
                   5139:             $storehash{'section'} = $sec;
                   5140:         }
1.1188    raeburn  5141:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5142:                    $domain,$cnum,$cdom);
1.1184    raeburn  5143:         if (($trole ne 'st') || ($sec ne '')) {
                   5144:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5145:         }
                   5146:     }
                   5147:     return;
                   5148: }
                   5149: 
1.1184    raeburn  5150: sub domainrolelog {
                   5151:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5152:     if ($area =~ m{^/($match_domain)/$}) {
                   5153:         my $cdom = $1;
                   5154:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5155:         my $namespace = 'rolelog';
                   5156:         my %storehash = (
                   5157:                            role    => $trole,
                   5158:                            start   => $tstart,
                   5159:                            end     => $tend,
                   5160:                            context => $context,
                   5161:                         );
1.1188    raeburn  5162:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5163:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5164:     }
                   5165:     return;
                   5166: 
                   5167: }
                   5168: 
                   5169: sub coauthorrolelog {
                   5170:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5171:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5172:         my $audom = $1;
                   5173:         my $auname = $2;
                   5174:         my $namespace = 'rolelog';
                   5175:         my %storehash = (
                   5176:                            role    => $trole,
                   5177:                            start   => $tstart,
                   5178:                            end     => $tend,
                   5179:                            context => $context,
                   5180:                         );
1.1188    raeburn  5181:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5182:                    $domain,$auname,$audom);
1.1184    raeburn  5183:     }
                   5184:     return;
                   5185: }
                   5186: 
1.351     www      5187: sub get_course_adv_roles {
1.948     raeburn  5188:     my ($cid,$codes) = @_;
1.620     albertel 5189:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5190:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5191:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5192:     my %nothide=();
1.800     albertel 5193:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5194:         if ($user !~ /:/) {
                   5195: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5196:         } else {
                   5197:             $nothide{$user}=1;
                   5198:         }
1.470     www      5199:     }
1.1219    raeburn  5200:     my @possdoms = ($coursehash{'domain'});
                   5201:     if ($coursehash{'checkforpriv'}) {
                   5202:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5203:     }
1.351     www      5204:     my %returnhash=();
                   5205:     my %dumphash=
                   5206:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5207:     my $now=time;
1.997     raeburn  5208:     my %privileged;
1.1000    raeburn  5209:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5210: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5211:         if (($tstart) && ($tstart<0)) { next; }
                   5212:         if (($tend) && ($tend<$now)) { next; }
                   5213:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5214:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5215: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5216:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5217:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5218: 	if ($role eq 'cr') { next; }
1.948     raeburn  5219:         if ($codes) {
                   5220:             if ($section) { $role .= ':'.$section; }
                   5221:             if ($returnhash{$role}) {
                   5222:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5223:             } else {
                   5224:                 $returnhash{$role}=$username.':'.$domain;
                   5225:             }
1.351     www      5226:         } else {
1.988     raeburn  5227:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5228:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5229:             if ($returnhash{$key}) {
                   5230: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5231:             } else {
                   5232:                 $returnhash{$key}=$username.':'.$domain;
                   5233:             }
1.351     www      5234:         }
1.948     raeburn  5235:     }
1.400     www      5236:     return %returnhash;
                   5237: }
                   5238: 
                   5239: sub get_my_roles {
1.937     raeburn  5240:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5241:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5242:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5243:     my (%dumphash,%nothide);
1.1086    raeburn  5244:     if ($context eq 'userroles') {
1.1166    raeburn  5245:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5246:     } else {
1.1219    raeburn  5247:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5248:         if ($hidepriv) {
                   5249:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5250:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5251:                 if ($user !~ /:/) {
                   5252:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5253:                 } else {
                   5254:                     $nothide{$user} = 1;
                   5255:                 }
                   5256:             }
                   5257:         }
1.858     raeburn  5258:     }
1.400     www      5259:     my %returnhash=();
                   5260:     my $now=time;
1.999     raeburn  5261:     my %privileged;
1.800     albertel 5262:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5263:         my ($role,$tend,$tstart);
                   5264:         if ($context eq 'userroles') {
1.1149    raeburn  5265:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5266: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5267:         } else {
                   5268:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5269:         }
1.400     www      5270:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5271:         my $status = 'active';
1.939     raeburn  5272:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5273:             $status = 'previous';
                   5274:         } 
                   5275:         if (($tstart) && ($now<$tstart)) {
                   5276:             $status = 'future';
                   5277:         }
                   5278:         if (ref($types) eq 'ARRAY') {
                   5279:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5280:                 next;
                   5281:             } 
                   5282:         } else {
                   5283:             if ($status ne 'active') {
                   5284:                 next;
                   5285:             }
                   5286:         }
1.867     raeburn  5287:         my ($rolecode,$username,$domain,$section,$area);
                   5288:         if ($context eq 'userroles') {
1.1186    raeburn  5289:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5290:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5291:         } else {
                   5292:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5293:         }
1.832     raeburn  5294:         if (ref($roledoms) eq 'ARRAY') {
                   5295:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5296:                 next;
                   5297:             }
                   5298:         }
                   5299:         if (ref($roles) eq 'ARRAY') {
                   5300:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5301:                 if ($role =~ /^cr\//) {
                   5302:                     if (!grep(/^cr$/,@{$roles})) {
                   5303:                         next;
                   5304:                     }
1.1104    raeburn  5305:                 } elsif ($role =~ /^gr\//) {
                   5306:                     if (!grep(/^gr$/,@{$roles})) {
                   5307:                         next;
                   5308:                     }
1.922     raeburn  5309:                 } else {
                   5310:                     next;
                   5311:                 }
1.832     raeburn  5312:             }
1.867     raeburn  5313:         }
1.937     raeburn  5314:         if ($hidepriv) {
1.1219    raeburn  5315:             my @privroles = ('dc','su');
1.999     raeburn  5316:             if ($context eq 'userroles') {
1.1219    raeburn  5317:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5318:             } else {
1.1219    raeburn  5319:                 my $possdoms = [$domain];
                   5320:                 if (ref($roledoms) eq 'ARRAY') {
                   5321:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5322:                 }
1.1219    raeburn  5323:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5324:                     if (!$nothide{$username.':'.$domain}) {
                   5325:                         next;
                   5326:                     }
                   5327:                 }
1.937     raeburn  5328:             }
                   5329:         }
1.933     raeburn  5330:         if ($withsec) {
                   5331:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5332:                 $tstart.':'.$tend;
                   5333:         } else {
                   5334:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5335:         }
1.832     raeburn  5336:     }
1.373     www      5337:     return %returnhash;
1.399     www      5338: }
                   5339: 
1.1333    raeburn  5340: sub get_all_adhocroles {
                   5341:     my ($dom) = @_;
                   5342:     my @roles_by_num = ();
                   5343:     my %domdefaults = &get_domain_defaults($dom);
                   5344:     my (%description,%access_in_dom,%access_info);
                   5345:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5346:         my $count = 0;
                   5347:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5348:         my %ordered;
                   5349:         foreach my $role (sort(keys(%domcurrent))) {
                   5350:             my ($order,$desc,$access_in_dom);
                   5351:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5352:                 $order = $domcurrent{$role}{'order'};
                   5353:                 $desc = $domcurrent{$role}{'desc'};
                   5354:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5355:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5356:             }
                   5357:             if ($order eq '') {
                   5358:                 $order = $count;
                   5359:             }
                   5360:             $ordered{$order} = $role;
                   5361:             if ($desc ne '') {
                   5362:                 $description{$role} = $desc;
                   5363:             } else {
                   5364:                 $description{$role}= $role;
                   5365:             }
                   5366:             $count++;
                   5367:         }
                   5368:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5369:             push(@roles_by_num,$ordered{$item});
                   5370:         }
                   5371:     }
                   5372:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5373: }
                   5374: 
1.1332    raeburn  5375: sub get_my_adhocroles {
1.1333    raeburn  5376:     my ($cid,$checkreg) = @_;
                   5377:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5378:     if ($env{'request.course.id'} eq $cid) {
                   5379:         $cdom = $env{'course.'.$cid.'.domain'};
                   5380:         $cnum = $env{'course.'.$cid.'.num'};
                   5381:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5382:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5383:         $cdom = $1;
                   5384:         $cnum = $2;
                   5385:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5386:                                      $cdom,$cnum);
                   5387:     }
                   5388:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5389:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5390:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5391:         if ($rosterhash{$user} ne '') {
                   5392:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5393:             return ([],{}) if ($type eq 'auto');
                   5394:         }
                   5395:     }
                   5396:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5397:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5398:             my $then=$env{'user.login.time'};
                   5399:             my $update=$env{'user.update.time'};
1.1335    raeburn  5400:             if (!$update) {
                   5401:                 $update = $then;
                   5402:             }
                   5403:             my @liveroles;
1.1334    raeburn  5404:             foreach my $role ('dh','da') {
                   5405:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5406:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5407:                     my $limit = $update;
                   5408:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5409:                         $limit = $then;
                   5410:                     }
1.1335    raeburn  5411:                     my $activerole = 1;
                   5412:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5413:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5414:                     if ($activerole) {
                   5415:                         push(@liveroles,$role);
                   5416:                     }
1.1334    raeburn  5417:                 }
1.1332    raeburn  5418:             }
1.1335    raeburn  5419:             if (@liveroles) {
1.1332    raeburn  5420:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5421:                     my ($accessref,$accessinfo,%access_in_dom);
                   5422:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5423:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5424:                         if (@{$roles_by_num}) {
1.1332    raeburn  5425:                             my %settings;
                   5426:                             if ($env{'request.course.id'} eq $cid) {
                   5427:                                 foreach my $envkey (keys(%env)) {
                   5428:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5429:                                         $settings{$1} = $env{$envkey};
                   5430:                                     }
                   5431:                                 }
                   5432:                             } else {
                   5433:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5434:                             }
                   5435:                             my %setincrs;
                   5436:                             if ($settings{'internal.adhocaccess'}) {
                   5437:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5438:                             }
                   5439:                             my @statuses;
                   5440:                             if ($env{'environment.inststatus'}) {
                   5441:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5442:                             }
                   5443:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5444:                             if (ref($accessref) eq 'HASH') {
                   5445:                                 %access_in_dom = %{$accessref};
                   5446:                             }
                   5447:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5448:                                 my ($curraccess,@okstatus,@personnel);
                   5449:                                 if ($setincrs{$role}) {
                   5450:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5451:                                     if ($curraccess eq 'status') {
                   5452:                                         @okstatus = split(/\&/,$rest);
                   5453:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5454:                                         @personnel = split(/\&/,$rest);
                   5455:                                     }
                   5456:                                 } else {
                   5457:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5458:                                     if (ref($accessinfo) eq 'HASH') {
                   5459:                                         if ($curraccess eq 'status') {
                   5460:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5461:                                                 @okstatus = @{$accessinfo->{$role}};
                   5462:                                             }
                   5463:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5464:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5465:                                                 @personnel = @{$accessinfo->{$role}};
                   5466:                                             }
1.1332    raeburn  5467:                                         }
                   5468:                                     }
                   5469:                                 }
                   5470:                                 if ($curraccess eq 'none') {
                   5471:                                     next;
                   5472:                                 } elsif ($curraccess eq 'all') {
                   5473:                                     push(@possroles,$role);
1.1336    raeburn  5474:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5475:                                     if (grep(/^dh$/,@liveroles)) {
                   5476:                                         push(@possroles,$role);
                   5477:                                     } else {
                   5478:                                         next;
                   5479:                                     }
1.1336    raeburn  5480:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5481:                                     if (grep(/^da$/,@liveroles)) {
                   5482:                                         push(@possroles,$role);
                   5483:                                     } else {
                   5484:                                         next;
                   5485:                                     }
1.1332    raeburn  5486:                                 } elsif ($curraccess eq 'status') {
                   5487:                                     if (@okstatus) {
                   5488:                                         if (!@statuses) {
                   5489:                                             if (grep(/^default$/,@okstatus)) {
                   5490:                                                 push(@possroles,$role);
                   5491:                                             }
                   5492:                                         } else {
                   5493:                                             foreach my $status (@okstatus) {
                   5494:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5495:                                                     push(@possroles,$role);
                   5496:                                                     last;
                   5497:                                                 }
                   5498:                                             }
                   5499:                                         }
                   5500:                                     }
                   5501:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5502:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5503:                                         if ($curraccess eq 'exc') {
                   5504:                                             push(@possroles,$role);
                   5505:                                         }
                   5506:                                     } elsif ($curraccess eq 'inc') {
                   5507:                                         push(@possroles,$role);
                   5508:                                     }
                   5509:                                 }
                   5510:                             }
                   5511:                         }
                   5512:                     }
                   5513:                 }
                   5514:             }
                   5515:         }
                   5516:     }
1.1333    raeburn  5517:     unless (ref($description) eq 'HASH') {
                   5518:         if (ref($roles_by_num) eq 'ARRAY') {
                   5519:             my %desc;
                   5520:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5521:             $description = \%desc;
                   5522:         } else {
                   5523:             $description = {};
                   5524:         }
                   5525:     }
                   5526:     return (\@possroles,$description);
1.1332    raeburn  5527: }
                   5528: 
1.399     www      5529: # ----------------------------------------------------- Frontpage Announcements
                   5530: #
                   5531: #
                   5532: 
                   5533: sub postannounce {
                   5534:     my ($server,$text)=@_;
1.844     albertel 5535:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5536:     unless ($text=~/\w/) { $text=''; }
                   5537:     return &reply('setannounce:'.&escape($text),$server);
                   5538: }
                   5539: 
                   5540: sub getannounce {
1.448     albertel 5541: 
1.1359    raeburn  5542:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5543: 	my $announcement='';
1.800     albertel 5544: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5545: 	close($fh);
1.399     www      5546: 	if ($announcement=~/\w/) { 
                   5547: 	    return 
                   5548:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5549:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5550: 	} else {
                   5551: 	    return '';
                   5552: 	}
                   5553:     } else {
                   5554: 	return '';
                   5555:     }
1.351     www      5556: }
1.353     www      5557: 
                   5558: # ---------------------------------------------------------- Course ID routines
                   5559: # Deal with domain's nohist_courseid.db files
                   5560: #
                   5561: 
                   5562: sub courseidput {
1.921     raeburn  5563:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5564:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5565:     my $outcome;
                   5566:     if ($caller eq 'timeonly') {
                   5567:         my $cids = '';
                   5568:         foreach my $item (keys(%$storehash)) {
                   5569:             $cids.=&escape($item).'&';
                   5570:         }
                   5571:         $cids=~s/\&$//;
                   5572:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5573:                           $coursehome);       
                   5574:     } else {
                   5575:         my $items = '';
                   5576:         foreach my $item (keys(%$storehash)) {
                   5577:             $items.= &escape($item).'='.
                   5578:                      &freeze_escape($$storehash{$item}).'&';
                   5579:         }
                   5580:         $items=~s/\&$//;
                   5581:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5582:                           $coursehome);
1.918     raeburn  5583:     }
                   5584:     if ($outcome eq 'unknown_cmd') {
                   5585:         my $what;
                   5586:         foreach my $cid (keys(%$storehash)) {
                   5587:             $what .= &escape($cid).'=';
1.921     raeburn  5588:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5589:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5590:             }
                   5591:             $what =~ s/\:$/&/;
                   5592:         }
                   5593:         $what =~ s/\&$//;  
                   5594:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5595:     } else {
                   5596:         return $outcome;
                   5597:     }
1.353     www      5598: }
                   5599: 
                   5600: sub courseiddump {
1.921     raeburn  5601:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5602:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5603:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5604:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5605:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5606:     my $as_hash = 1;
                   5607:     my %returnhash;
                   5608:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5609:     my %libserv = &all_library();
                   5610:     foreach my $tryserver (keys(%libserv)) {
                   5611:         if ( (  $hostidflag == 1 
                   5612: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5613: 	     || (!defined($hostidflag)) ) {
                   5614: 
1.918     raeburn  5615: 	    if (($domfilter eq '') ||
                   5616: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5617:                 my $rep;
                   5618:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5619:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5620:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5621:                                 &escape($descfilter), &escape($instcodefilter), 
                   5622:                                 &escape($ownerfilter), &escape($coursefilter),
                   5623:                                 &escape($typefilter), &escape($regexp_ok), 
                   5624:                                 $as_hash, &escape($selfenrollonly), 
                   5625:                                 &escape($catfilter), $showhidden, $caller, 
                   5626:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5627:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5628:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5629:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5630:                 } else {
                   5631:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5632:                              $sincefilter.':'.&escape($descfilter).':'.
                   5633:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5634:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5635:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5636:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5637:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5638:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5639:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5640:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5641:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5642:                 }
                   5643:                      
1.918     raeburn  5644:                 my @pairs=split(/\&/,$rep);
                   5645:                 foreach my $item (@pairs) {
                   5646:                     my ($key,$value)=split(/\=/,$item,2);
                   5647:                     $key = &unescape($key);
                   5648:                     next if ($key =~ /^error: 2 /);
                   5649:                     my $result = &thaw_unescape($value);
                   5650:                     if (ref($result) eq 'HASH') {
                   5651:                         $returnhash{$key}=$result;
                   5652:                     } else {
1.921     raeburn  5653:                         my @responses = split(/:/,$value);
                   5654:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5655:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5656:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5657:                         }
1.1008    raeburn  5658:                     }
1.353     www      5659:                 }
                   5660:             }
                   5661:         }
                   5662:     }
                   5663:     return %returnhash;
                   5664: }
                   5665: 
1.1055    raeburn  5666: sub courselastaccess {
                   5667:     my ($cdom,$cnum,$hostidref) = @_;
                   5668:     my %returnhash;
                   5669:     if ($cdom && $cnum) {
                   5670:         my $chome = &homeserver($cnum,$cdom);
                   5671:         if ($chome ne 'no_host') {
                   5672:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5673:             &extract_lastaccess(\%returnhash,$rep);
                   5674:         }
                   5675:     } else {
                   5676:         if (!$cdom) { $cdom=''; }
                   5677:         my %libserv = &all_library();
                   5678:         foreach my $tryserver (keys(%libserv)) {
                   5679:             if (ref($hostidref) eq 'ARRAY') {
                   5680:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5681:             } 
                   5682:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5683:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5684:                 &extract_lastaccess(\%returnhash,$rep);
                   5685:             }
                   5686:         }
                   5687:     }
                   5688:     return %returnhash;
                   5689: }
                   5690: 
                   5691: sub extract_lastaccess {
                   5692:     my ($returnhash,$rep) = @_;
                   5693:     if (ref($returnhash) eq 'HASH') {
                   5694:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5695:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5696:                  $rep eq '') {
                   5697:             my @pairs=split(/\&/,$rep);
                   5698:             foreach my $item (@pairs) {
                   5699:                 my ($key,$value)=split(/\=/,$item,2);
                   5700:                 $key = &unescape($key);
                   5701:                 next if ($key =~ /^error: 2 /);
                   5702:                 $returnhash->{$key} = &thaw_unescape($value);
                   5703:             }
                   5704:         }
                   5705:     }
                   5706:     return;
                   5707: }
                   5708: 
1.658     raeburn  5709: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5710: 
                   5711: sub dcmailput {
1.685     raeburn  5712:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5713:     my $status = &Apache::lonnet::critical(
1.740     www      5714:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5715:        &escape($message),$server);
1.662     raeburn  5716:     return $status;
                   5717: }
                   5718: 
1.658     raeburn  5719: sub dcmaildump {
                   5720:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5721:     my %returnhash=();
1.846     albertel 5722: 
                   5723:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5724:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5725:                                                          &escape($enddate).':';
                   5726: 	my @esc_senders=map { &escape($_)} @$senders;
                   5727: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5728: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5729:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5730:             if (($key) && ($value)) {
                   5731:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5732:             }
                   5733:         }
                   5734:     }
                   5735:     return %returnhash;
                   5736: }
1.662     raeburn  5737: # ---------------------------------------------------------- Domain roles
                   5738: 
                   5739: sub get_domain_roles {
                   5740:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5741:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5742:         $startdate = '.';
                   5743:     }
1.1018    raeburn  5744:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5745:         $enddate = '.';
                   5746:     }
1.922     raeburn  5747:     my $rolelist;
                   5748:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5749:         $rolelist = join('&',@{$roles});
1.922     raeburn  5750:     }
1.662     raeburn  5751:     my %personnel = ();
1.841     albertel 5752: 
                   5753:     my %servers = &get_servers($dom,'library');
                   5754:     foreach my $tryserver (keys(%servers)) {
                   5755: 	%{$personnel{$tryserver}}=();
                   5756: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5757: 					    &escape($startdate).':'.
                   5758: 					    &escape($enddate).':'.
                   5759: 					    &escape($rolelist), $tryserver))) {
                   5760: 	    my ($key,$value) = split(/\=/,$line,2);
                   5761: 	    if (($key) && ($value)) {
                   5762: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5763: 	    }
                   5764: 	}
1.662     raeburn  5765:     }
                   5766:     return %personnel;
                   5767: }
1.658     raeburn  5768: 
1.1332    raeburn  5769: sub get_active_domroles {
                   5770:     my ($dom,$roles) = @_;
                   5771:     return () unless (ref($roles) eq 'ARRAY');
                   5772:     my $now = time;
                   5773:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5774:     my %domroles;
                   5775:     foreach my $server (keys(%dompersonnel)) {
                   5776:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5777:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5778:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5779:         }
                   5780:     }
                   5781:     return %domroles;
                   5782: }
                   5783: 
1.1057    www      5784: # ----------------------------------------------------------- Interval timing 
1.149     www      5785: 
1.1153    www      5786: {
                   5787: # Caches needed for speedup of navmaps
                   5788: # We don't want to cache this for very long at all (5 seconds at most)
                   5789: # 
                   5790: # The user for whom we cache
                   5791: my $cachedkey='';
                   5792: # The cached times for this user
                   5793: my %cachedtimes=();
                   5794: # When this was last done
1.1282    raeburn  5795: my $cachedtime='';
1.1153    www      5796: 
                   5797: sub load_all_first_access {
1.1308    raeburn  5798:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5799:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5800:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5801:         (!$ignorecache)) {
1.1154    raeburn  5802:         return;
                   5803:     }
                   5804:     $cachedtime=time;
                   5805:     $cachedkey=$uname.':'.$udom;
                   5806:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5807: }
                   5808: 
1.504     albertel 5809: sub get_first_access {
1.1308    raeburn  5810:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5811:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5812:     if ($argsymb) { $symb=$argsymb; }
                   5813:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5814:     if ($argmap) { $map = $argmap; }
1.926     albertel 5815:     if ($type eq 'course') {
                   5816: 	$res='course';
                   5817:     } elsif ($type eq 'map') {
1.588     albertel 5818: 	$res=&symbread($map);
                   5819:     } else {
                   5820: 	$res=$symb;
                   5821:     }
1.1308    raeburn  5822:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5823:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5824: }
                   5825: 
                   5826: sub set_first_access {
1.1162    raeburn  5827:     my ($type,$interval)=@_;
1.790     albertel 5828:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5829:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5830:     if ($type eq 'course') {
                   5831: 	$res='course';
                   5832:     } elsif ($type eq 'map') {
1.588     albertel 5833: 	$res=&symbread($map);
                   5834:     } else {
                   5835: 	$res=$symb;
                   5836:     }
1.1153    www      5837:     $cachedkey='';
1.1162    raeburn  5838:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5839:     if ($firstaccess) {
                   5840:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5841:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5842:                  "in $courseid");
1.1386    raeburn  5843:         return 'already_set';
                   5844:     } else {
1.1162    raeburn  5845:         my $start = time;
                   5846: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5847:                           $udom,$uname);
                   5848:         if ($putres eq 'ok') {
                   5849:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5850:                  $udom,$uname); 
                   5851:             &appenv(
                   5852:                      {
                   5853:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5854:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5855:                      }
                   5856:                   );
1.1365    raeburn  5857:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5858:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5859:             }
1.1386    raeburn  5860:         } elsif ($putres ne 'refused') {
                   5861:             &logthis("Result: $putres when attempting to set first access time ".
                   5862:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5863:         }
                   5864:         return $putres;
1.505     albertel 5865:     }
                   5866:     return 'already_set';
1.504     albertel 5867: }
1.1153    www      5868: }
1.1282    raeburn  5869: 
1.110     www      5870: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5871: 
                   5872: sub expirespread {
                   5873:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5874:     my $cid=$env{'request.course.id'}; 
1.110     www      5875:     if ($cid) {
                   5876:        my $now=time;
                   5877:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5878:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5879:                             $env{'course.'.$cid.'.num'}.
1.110     www      5880: 	        	    ':nohist_expirationdates:'.
                   5881:                             &escape($key).'='.$now,
1.620     albertel 5882:                             $env{'course.'.$cid.'.home'})
1.110     www      5883:     }
                   5884:     return 'ok';
1.14      www      5885: }
                   5886: 
1.109     www      5887: # ----------------------------------------------------- Devalidate Spreadsheets
                   5888: 
                   5889: sub devalidate {
1.325     www      5890:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5891:     my $cid=$env{'request.course.id'}; 
1.109     www      5892:     if ($cid) {
1.391     matthew  5893:         # delete the stored spreadsheets for
                   5894:         # - the student level sheet of this user in course's homespace
                   5895:         # - the assessment level sheet for this resource 
                   5896:         #   for this user in user's homespace
1.553     albertel 5897: 	# - current conditional state info
1.325     www      5898: 	my $key=$uname.':'.$udom.':';
1.109     www      5899:         my $status=
1.299     matthew  5900: 	    &del('nohist_calculatedsheets',
1.391     matthew  5901: 		 [$key.'studentcalc:'],
1.620     albertel 5902: 		 $env{'course.'.$cid.'.domain'},
                   5903: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5904: 		.' '.
                   5905: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5906: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5907:         unless ($status eq 'ok ok') {
                   5908:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5909:                     $uname.' at '.$udom.' for '.
1.109     www      5910: 		    $symb.': '.$status);
1.133     albertel 5911:         }
1.553     albertel 5912: 	&delenv('user.state.'.$cid);
1.109     www      5913:     }
                   5914: }
                   5915: 
1.265     albertel 5916: sub get_scalar {
                   5917:     my ($string,$end) = @_;
                   5918:     my $value;
                   5919:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5920: 	$value = $1;
                   5921:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5922: 	$value = $1;
                   5923:     }
                   5924:     return &unescape($value);
                   5925: }
                   5926: 
                   5927: sub array2str {
                   5928:   my (@array) = @_;
                   5929:   my $result=&arrayref2str(\@array);
                   5930:   $result=~s/^__ARRAY_REF__//;
                   5931:   $result=~s/__END_ARRAY_REF__$//;
                   5932:   return $result;
                   5933: }
                   5934: 
1.204     albertel 5935: sub arrayref2str {
                   5936:   my ($arrayref) = @_;
1.265     albertel 5937:   my $result='__ARRAY_REF__';
1.204     albertel 5938:   foreach my $elem (@$arrayref) {
1.265     albertel 5939:     if(ref($elem) eq 'ARRAY') {
                   5940:       $result.=&arrayref2str($elem).'&';
                   5941:     } elsif(ref($elem) eq 'HASH') {
                   5942:       $result.=&hashref2str($elem).'&';
                   5943:     } elsif(ref($elem)) {
                   5944:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5945:     } else {
                   5946:       $result.=&escape($elem).'&';
                   5947:     }
                   5948:   }
                   5949:   $result=~s/\&$//;
1.265     albertel 5950:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5951:   return $result;
                   5952: }
                   5953: 
1.168     albertel 5954: sub hash2str {
1.204     albertel 5955:   my (%hash) = @_;
                   5956:   my $result=&hashref2str(\%hash);
1.265     albertel 5957:   $result=~s/^__HASH_REF__//;
                   5958:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5959:   return $result;
                   5960: }
                   5961: 
                   5962: sub hashref2str {
                   5963:   my ($hashref)=@_;
1.265     albertel 5964:   my $result='__HASH_REF__';
1.800     albertel 5965:   foreach my $key (sort(keys(%$hashref))) {
                   5966:     if (ref($key) eq 'ARRAY') {
                   5967:       $result.=&arrayref2str($key).'=';
                   5968:     } elsif (ref($key) eq 'HASH') {
                   5969:       $result.=&hashref2str($key).'=';
                   5970:     } elsif (ref($key)) {
1.265     albertel 5971:       $result.='=';
1.800     albertel 5972:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5973:     } else {
1.1132    raeburn  5974: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5975:     }
                   5976: 
1.800     albertel 5977:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5978:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5979:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5980:       $result.=&hashref2str($hashref->{$key}).'&';
                   5981:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5982:        $result.='&';
1.800     albertel 5983:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5984:     } else {
1.800     albertel 5985:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5986:     }
                   5987:   }
1.168     albertel 5988:   $result=~s/\&$//;
1.265     albertel 5989:   $result .= '__END_HASH_REF__';
1.168     albertel 5990:   return $result;
                   5991: }
                   5992: 
                   5993: sub str2hash {
1.265     albertel 5994:     my ($string)=@_;
                   5995:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5996:     return %$hash;
                   5997: }
                   5998: 
                   5999: sub str2hashref {
1.168     albertel 6000:   my ($string) = @_;
1.265     albertel 6001: 
                   6002:   my %hash;
                   6003: 
                   6004:   if($string !~ /^__HASH_REF__/) {
                   6005:       if (! ($string eq '' || !defined($string))) {
                   6006: 	  $hash{'error'}='Not hash reference';
                   6007:       }
                   6008:       return (\%hash, $string);
                   6009:   }
                   6010: 
                   6011:   $string =~ s/^__HASH_REF__//;
                   6012: 
                   6013:   while($string !~ /^__END_HASH_REF__/) {
                   6014:       #key
                   6015:       my $key='';
                   6016:       if($string =~ /^__HASH_REF__/) {
                   6017:           ($key, $string)=&str2hashref($string);
                   6018:           if(defined($key->{'error'})) {
                   6019:               $hash{'error'}='Bad data';
                   6020:               return (\%hash, $string);
                   6021:           }
                   6022:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6023:           ($key, $string)=&str2arrayref($string);
                   6024:           if($key->[0] eq 'Array reference error') {
                   6025:               $hash{'error'}='Bad data';
                   6026:               return (\%hash, $string);
                   6027:           }
                   6028:       } else {
                   6029:           $string =~ s/^(.*?)=//;
1.267     albertel 6030: 	  $key=&unescape($1);
1.265     albertel 6031:       }
                   6032:       $string =~ s/^=//;
                   6033: 
                   6034:       #value
                   6035:       my $value='';
                   6036:       if($string =~ /^__HASH_REF__/) {
                   6037:           ($value, $string)=&str2hashref($string);
                   6038:           if(defined($value->{'error'})) {
                   6039:               $hash{'error'}='Bad data';
                   6040:               return (\%hash, $string);
                   6041:           }
                   6042:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6043:           ($value, $string)=&str2arrayref($string);
                   6044:           if($value->[0] eq 'Array reference error') {
                   6045:               $hash{'error'}='Bad data';
                   6046:               return (\%hash, $string);
                   6047:           }
                   6048:       } else {
                   6049: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6050:       }
                   6051:       $string =~ s/^&//;
                   6052: 
                   6053:       $hash{$key}=$value;
1.204     albertel 6054:   }
1.265     albertel 6055: 
                   6056:   $string =~ s/^__END_HASH_REF__//;
                   6057: 
                   6058:   return (\%hash, $string);
1.204     albertel 6059: }
                   6060: 
                   6061: sub str2array {
1.265     albertel 6062:     my ($string)=@_;
                   6063:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6064:     return @$array;
                   6065: }
                   6066: 
                   6067: sub str2arrayref {
1.204     albertel 6068:   my ($string) = @_;
1.265     albertel 6069:   my @array;
                   6070: 
                   6071:   if($string !~ /^__ARRAY_REF__/) {
                   6072:       if (! ($string eq '' || !defined($string))) {
                   6073: 	  $array[0]='Array reference error';
                   6074:       }
                   6075:       return (\@array, $string);
                   6076:   }
                   6077: 
                   6078:   $string =~ s/^__ARRAY_REF__//;
                   6079: 
                   6080:   while($string !~ /^__END_ARRAY_REF__/) {
                   6081:       my $value='';
                   6082:       if($string =~ /^__HASH_REF__/) {
                   6083:           ($value, $string)=&str2hashref($string);
                   6084:           if(defined($value->{'error'})) {
                   6085:               $array[0] ='Array reference error';
                   6086:               return (\@array, $string);
                   6087:           }
                   6088:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6089:           ($value, $string)=&str2arrayref($string);
                   6090:           if($value->[0] eq 'Array reference error') {
                   6091:               $array[0] ='Array reference error';
                   6092:               return (\@array, $string);
                   6093:           }
                   6094:       } else {
                   6095: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6096:       }
                   6097:       $string =~ s/^&//;
                   6098: 
                   6099:       push(@array, $value);
1.191     harris41 6100:   }
1.265     albertel 6101: 
                   6102:   $string =~ s/^__END_ARRAY_REF__//;
                   6103: 
                   6104:   return (\@array, $string);
1.168     albertel 6105: }
                   6106: 
1.167     albertel 6107: # -------------------------------------------------------------------Temp Store
                   6108: 
1.168     albertel 6109: sub tmpreset {
                   6110:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6111:   if (!$symb) {
                   6112:     $symb=&symbread();
1.620     albertel 6113:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6114:   }
                   6115:   $symb=escape($symb);
                   6116: 
1.620     albertel 6117:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6118:   $namespace=~s/\//\_/g;
                   6119:   $namespace=~s/\W//g;
                   6120: 
1.620     albertel 6121:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6122:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6123:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6124:       $stuname=&get_requestor_ip();
1.591     albertel 6125:   }
1.1117    foxr     6126:   my $path=LONCAPA::tempdir();
1.168     albertel 6127:   my %hash;
                   6128:   if (tie(%hash,'GDBM_File',
                   6129: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6130: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6131:     foreach my $key (keys(%hash)) {
1.180     albertel 6132:       if ($key=~ /:$symb/) {
1.168     albertel 6133: 	delete($hash{$key});
                   6134:       }
                   6135:     }
                   6136:   }
                   6137: }
                   6138: 
1.167     albertel 6139: sub tmpstore {
1.168     albertel 6140:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6141: 
                   6142:   if (!$symb) {
                   6143:     $symb=&symbread();
1.620     albertel 6144:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6145:   }
                   6146:   $symb=escape($symb);
                   6147: 
                   6148:   if (!$namespace) {
                   6149:     # I don't think we would ever want to store this for a course.
                   6150:     # it seems this will only be used if we don't have a course.
1.620     albertel 6151:     #$namespace=$env{'request.course.id'};
1.168     albertel 6152:     #if (!$namespace) {
1.620     albertel 6153:       $namespace=$env{'request.state'};
1.168     albertel 6154:     #}
                   6155:   }
                   6156:   $namespace=~s/\//\_/g;
                   6157:   $namespace=~s/\W//g;
1.620     albertel 6158:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6159:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6160:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6161:       $stuname=&get_requestor_ip();
1.591     albertel 6162:   }
1.168     albertel 6163:   my $now=time;
                   6164:   my %hash;
1.1117    foxr     6165:   my $path=LONCAPA::tempdir();
1.168     albertel 6166:   if (tie(%hash,'GDBM_File',
                   6167: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6168: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6169:     $hash{"version:$symb"}++;
                   6170:     my $version=$hash{"version:$symb"};
                   6171:     my $allkeys=''; 
                   6172:     foreach my $key (keys(%$storehash)) {
                   6173:       $allkeys.=$key.':';
1.591     albertel 6174:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6175:     }
                   6176:     $hash{"$version:$symb:timestamp"}=$now;
                   6177:     $allkeys.='timestamp';
                   6178:     $hash{"$version:keys:$symb"}=$allkeys;
                   6179:     if (untie(%hash)) {
                   6180:       return 'ok';
                   6181:     } else {
                   6182:       return "error:$!";
                   6183:     }
                   6184:   } else {
                   6185:     return "error:$!";
                   6186:   }
                   6187: }
1.167     albertel 6188: 
1.168     albertel 6189: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6190: 
1.168     albertel 6191: sub tmprestore {
                   6192:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6193: 
1.168     albertel 6194:   if (!$symb) {
                   6195:     $symb=&symbread();
1.620     albertel 6196:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6197:   }
                   6198:   $symb=escape($symb);
                   6199: 
1.620     albertel 6200:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6201: 
1.620     albertel 6202:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6203:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6204:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6205:       $stuname=&get_requestor_ip();
1.591     albertel 6206:   }
1.168     albertel 6207:   my %returnhash;
                   6208:   $namespace=~s/\//\_/g;
                   6209:   $namespace=~s/\W//g;
                   6210:   my %hash;
1.1117    foxr     6211:   my $path=LONCAPA::tempdir();
1.168     albertel 6212:   if (tie(%hash,'GDBM_File',
                   6213: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6214: 	  &GDBM_READER(),0640)) {
1.168     albertel 6215:     my $version=$hash{"version:$symb"};
                   6216:     $returnhash{'version'}=$version;
                   6217:     my $scope;
                   6218:     for ($scope=1;$scope<=$version;$scope++) {
                   6219:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6220:       my @keys=split(/:/,$vkeys);
                   6221:       my $key;
                   6222:       $returnhash{"$scope:keys"}=$vkeys;
                   6223:       foreach $key (@keys) {
1.591     albertel 6224: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6225: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6226:       }
                   6227:     }
1.168     albertel 6228:     if (!(untie(%hash))) {
                   6229:       return "error:$!";
                   6230:     }
                   6231:   } else {
                   6232:     return "error:$!";
                   6233:   }
                   6234:   return %returnhash;
1.167     albertel 6235: }
                   6236: 
1.9       www      6237: # ----------------------------------------------------------------------- Store
                   6238: 
                   6239: sub store {
1.1269    raeburn  6240:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6241:     my $home='';
                   6242: 
1.168     albertel 6243:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6244: 
1.213     www      6245:     $symb=&symbclean($symb);
1.122     albertel 6246:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6247: 
1.620     albertel 6248:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6249:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6250: 
                   6251:     &devalidate($symb,$stuname,$domain);
1.109     www      6252: 
                   6253:     $symb=escape($symb);
1.187     www      6254:     if (!$namespace) { 
1.620     albertel 6255:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6256:           return ''; 
                   6257:        } 
                   6258:     }
1.620     albertel 6259:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6260: 
1.1434    raeburn  6261:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6262:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6263: 
1.12      www      6264:     my $namevalue='';
1.800     albertel 6265:     foreach my $key (keys(%$storehash)) {
                   6266:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6267:     }
1.12      www      6268:     $namevalue=~s/\&$//;
1.187     www      6269:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6270:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6271: }
                   6272: 
1.47      www      6273: # -------------------------------------------------------------- Critical Store
                   6274: 
                   6275: sub cstore {
1.1269    raeburn  6276:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6277:     my $home='';
                   6278: 
1.168     albertel 6279:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6280: 
1.213     www      6281:     $symb=&symbclean($symb);
1.122     albertel 6282:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6283: 
1.620     albertel 6284:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6285:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6286: 
                   6287:     &devalidate($symb,$stuname,$domain);
1.109     www      6288: 
                   6289:     $symb=escape($symb);
1.187     www      6290:     if (!$namespace) { 
1.620     albertel 6291:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6292:           return ''; 
                   6293:        } 
                   6294:     }
1.620     albertel 6295:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6296: 
1.1434    raeburn  6297:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6298:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6299: 
1.47      www      6300:     my $namevalue='';
1.800     albertel 6301:     foreach my $key (keys(%$storehash)) {
                   6302:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6303:     }
1.47      www      6304:     $namevalue=~s/\&$//;
1.187     www      6305:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6306:     return critical
1.1269    raeburn  6307:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6308: }
                   6309: 
1.9       www      6310: # --------------------------------------------------------------------- Restore
                   6311: 
                   6312: sub restore {
1.124     www      6313:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6314:     my $home='';
                   6315: 
1.168     albertel 6316:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6317: 
1.122     albertel 6318:     if (!$symb) {
1.1224    raeburn  6319:         return if ($namespace eq 'courserequests');
                   6320:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6321:     } else {
1.1224    raeburn  6322:         unless ($namespace eq 'courserequests') {
                   6323:             $symb=&escape(&symbclean($symb));
                   6324:         }
1.122     albertel 6325:     }
1.188     www      6326:     if (!$namespace) { 
1.620     albertel 6327:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6328:           return ''; 
                   6329:        } 
                   6330:     }
1.620     albertel 6331:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6332:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6333:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6334:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6335: 
1.12      www      6336:     my %returnhash=();
1.800     albertel 6337:     foreach my $line (split(/\&/,$answer)) {
                   6338: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6339:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6340:     }
1.75      www      6341:     my $version;
                   6342:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6343:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6344:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6345:        }
1.75      www      6346:     }
1.13      www      6347:     return %returnhash;
1.34      www      6348: }
                   6349: 
                   6350: # ---------------------------------------------------------- Course Description
1.1118    foxr     6351: #
                   6352: #  
1.34      www      6353: 
                   6354: sub coursedescription {
1.731     albertel 6355:     my ($courseid,$args)=@_;
1.34      www      6356:     $courseid=~s/^\///;
1.49      www      6357:     $courseid=~s/\_/\//g;
1.34      www      6358:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6359:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6360:     my $normalid=$cdomain.'_'.$cnum;
                   6361:     # need to always cache even if we get errors otherwise we keep 
                   6362:     # trying and trying and trying to get the course description.
                   6363:     my %envhash=();
                   6364:     my %returnhash=();
1.731     albertel 6365:     
                   6366:     my $expiretime=600;
                   6367:     if ($env{'request.course.id'} eq $normalid) {
                   6368: 	$expiretime=120;
                   6369:     }
                   6370: 
                   6371:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6372:     if (!$args->{'freshen_cache'}
                   6373: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6374: 	foreach my $key (keys(%env)) {
                   6375: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6376: 	    my ($setting) = $1;
                   6377: 	    $returnhash{$setting} = $env{$key};
                   6378: 	}
                   6379: 	return %returnhash;
                   6380:     }
                   6381: 
1.1118    foxr     6382:     # get the data again
                   6383: 
1.731     albertel 6384:     if (!$args->{'one_time'}) {
                   6385: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6386:     }
1.811     albertel 6387: 
1.34      www      6388:     if ($chome ne 'no_host') {
1.302     albertel 6389:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6390:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6391: 	   my $username = $env{'user.name'}; # Defult username
                   6392: 	   if(defined $args->{'user'}) {
                   6393: 	       $username = $args->{'user'};
                   6394: 	   }
1.129     albertel 6395:            $returnhash{'home'}= $chome;
                   6396: 	   $returnhash{'domain'} = $cdomain;
                   6397: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6398:            if (!defined($returnhash{'type'})) {
                   6399:                $returnhash{'type'} = 'Course';
                   6400:            }
1.130     albertel 6401:            while (my ($name,$value) = each %returnhash) {
1.53      www      6402:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6403:            }
1.270     www      6404:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6405:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6406: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6407:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6408:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6409:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6410:        }
                   6411:     }
1.731     albertel 6412:     if (!$args->{'one_time'}) {
1.949     raeburn  6413: 	&appenv(\%envhash);
1.731     albertel 6414:     }
1.302     albertel 6415:     return %returnhash;
1.461     www      6416: }
                   6417: 
1.1080    raeburn  6418: sub update_released_required {
                   6419:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6420:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6421:         $cid = $env{'request.course.id'};
                   6422:         $cdom = $env{'course.'.$cid.'.domain'};
                   6423:         $cnum = $env{'course.'.$cid.'.num'};
                   6424:         $chome = $env{'course.'.$cid.'.home'};
                   6425:     }
                   6426:     if ($needsrelease) {
                   6427:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6428:         my $needsupdate;
                   6429:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6430:             $needsupdate = 1;
                   6431:         } else {
                   6432:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6433:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6434:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6435:                 $needsupdate = 1;
                   6436:             }
                   6437:         }
                   6438:         if ($needsupdate) {
                   6439:             my %needshash = (
                   6440:                              'internal.releaserequired' => $needsrelease,
                   6441:                             );
                   6442:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6443:             if ($putresult eq 'ok') {
                   6444:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6445:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6446:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6447:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6448:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6449:                 }
                   6450:             }
                   6451:         }
                   6452:     }
                   6453:     return;
                   6454: }
                   6455: 
1.461     www      6456: # -------------------------------------------------See if a user is privileged
                   6457: 
                   6458: sub privileged {
1.1219    raeburn  6459:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6460:     my $now = time;
1.1219    raeburn  6461:     my $roles;
                   6462:     if (ref($possroles) eq 'ARRAY') {
                   6463:         $roles = $possroles; 
                   6464:     } else {
                   6465:         $roles = ['dc','su'];
                   6466:     }
                   6467:     if (ref($possdomains) eq 'ARRAY') {
                   6468:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6469:         foreach my $dom (@{$possdomains}) {
                   6470:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6471:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6472:                 foreach my $role (@{$roles}) {
                   6473:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6474:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6475:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6476:                             return 1 unless (($end && $end < $now) ||
                   6477:                                              ($start && $start > $now));
                   6478:                         }
                   6479:                     }
                   6480:                 }
                   6481:             }
                   6482:         }
                   6483:     } else {
                   6484:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6485:         my $now = time;
1.1170    droeschl 6486: 
1.1275    musolffc 6487:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6488:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6489:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6490:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6491:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6492:             }
1.1219    raeburn  6493:         }
                   6494:     }
                   6495:     return 0;
                   6496: }
1.1170    droeschl 6497: 
1.1219    raeburn  6498: sub privileged_by_domain {
                   6499:     my ($domains,$roles) = @_;
                   6500:     my %privileged = ();
                   6501:     my $cachetime = 60*60*24;
                   6502:     my $now = time;
                   6503:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6504:         return %privileged;
                   6505:     }
                   6506:     foreach my $dom (@{$domains}) {
                   6507:         next if (ref($privileged{$dom}) eq 'HASH');
                   6508:         my $needroles;
                   6509:         foreach my $role (@{$roles}) {
                   6510:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6511:             if (defined($cached)) {
                   6512:                 if (ref($result) eq 'HASH') {
                   6513:                     $privileged{$dom}{$role} = $result;
                   6514:                 }
                   6515:             } else {
                   6516:                 $needroles = 1;
                   6517:             }
                   6518:         }
                   6519:         if ($needroles) {
                   6520:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6521:             $privileged{$dom} = {};
                   6522:             foreach my $server (keys(%dompersonnel)) {
                   6523:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6524:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6525:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6526:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6527:                         next if ($end && $end < $now);
                   6528:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6529:                             $dompersonnel{$server}{$item};
                   6530:                     }
                   6531:                 }
                   6532:             }
                   6533:             if (ref($privileged{$dom}) eq 'HASH') {
                   6534:                 foreach my $role (@{$roles}) {
                   6535:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6536:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6537:                     } else {
                   6538:                         my %hash = ();
                   6539:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6540:                     }
                   6541:                 }
                   6542:             }
                   6543:         }
                   6544:     }
                   6545:     return %privileged;
1.9       www      6546: }
1.1       albertel 6547: 
1.103     harris41 6548: # -------------------------------------------------------- Get user privileges
1.11      www      6549: 
                   6550: sub rolesinit {
1.1169    droeschl 6551:     my ($domain, $username) = @_;
                   6552:     my %userroles = ('user.login.time' => time);
                   6553:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6554: 
                   6555:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6556:     # also, blocking can be triggered by an activating timer
                   6557:     # it's saved in the user's %env.
                   6558:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6559:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6560:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6561:         %timerintchk, %timerintenv);
                   6562: 
1.1162    raeburn  6563:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6564:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6565:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6566:     }
1.1169    droeschl 6567: 
1.1162    raeburn  6568:     foreach my $key (keys(%timerinterval)) {
                   6569:         my ($cid,$rest) = split(/\0/,$key);
                   6570:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6571:     }
1.1169    droeschl 6572: 
1.11      www      6573:     my %allroles=();
1.1162    raeburn  6574:     my %allgroups=();
1.11      www      6575: 
1.1274    raeburn  6576:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6577:         my $role = $rolesdump{$area};
                   6578:         $area =~ s/\_\w\w$//;
                   6579: 
                   6580:         my ($trole, $tend, $tstart, $group_privs);
                   6581: 
                   6582:         if ($role =~ /^cr/) {
                   6583:         # Custom role, defined by a user 
                   6584:         # e.g., user.role.cr/msu/smith/mynewrole
                   6585:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6586:                 $trole = $1;
                   6587:                 ($tend, $tstart) = split('_', $2);
                   6588:             } else {
                   6589:                 $trole = $role;
                   6590:             }
                   6591:         } elsif ($role =~ m|^gr/|) {
                   6592:         # Role of member in a group, defined within a course/community
                   6593:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6594:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6595:             next if $tstart eq '-1';
                   6596:             ($trole, $group_privs) = split(/\//, $trole);
                   6597:             $group_privs = &unescape($group_privs);
                   6598:         } else {
                   6599:         # Just a normal role, defined in roles.tab
                   6600:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6601:         }
                   6602: 
                   6603:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6604:                  $username);
                   6605:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6606: 
                   6607:         # role expired or not available yet?
                   6608:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6609:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6610: 
                   6611:         next if $area eq '' or $trole eq '';
                   6612: 
                   6613:         my $spec = "$trole.$area";
                   6614:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6615: 
                   6616:         if ($trole =~ /^cr\//) {
                   6617:         # Custom role, defined by a user
                   6618:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6619:         } elsif ($trole eq 'gr') {
                   6620:         # Role of a member in a group, defined within a course/community
                   6621:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6622:             next;
                   6623:         } else {
                   6624:         # Normal role, defined in roles.tab
                   6625:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6626:         }
                   6627: 
                   6628:         my $cid = $tdomain.'_'.$trest;
                   6629:         unless ($firstaccchk{$cid}) {
                   6630:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6631:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6632:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6633:                         $coursetimerstarts{$cid}{$item}; 
                   6634:                 }
                   6635:             }
                   6636:             $firstaccchk{$cid} = 1;
                   6637:         }
                   6638:         unless ($timerintchk{$cid}) {
                   6639:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6640:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6641:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6642:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6643:                 }
1.12      www      6644:             }
1.1169    droeschl 6645:             $timerintchk{$cid} = 1;
1.191     harris41 6646:         }
1.11      www      6647:     }
1.1169    droeschl 6648: 
1.1341    raeburn  6649:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6650:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6651:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6652:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6653: 
1.1162    raeburn  6654:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6655: }
                   6656: 
1.567     raeburn  6657: sub set_arearole {
1.1215    raeburn  6658:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6659:     unless ($nolog) {
1.567     raeburn  6660: # log the associated role with the area
1.1215    raeburn  6661:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6662:     }
1.743     albertel 6663:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6664: }
                   6665: 
                   6666: sub custom_roleprivs {
                   6667:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6668:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6669:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6670:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6671:         my ($rdummy,$roledef)=
                   6672:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6673:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6674:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6675:             if (defined($syspriv)) {
1.1043    raeburn  6676:                 if ($trest =~ /^$match_community$/) {
                   6677:                     $syspriv =~ s/bre\&S//; 
                   6678:                 }
1.567     raeburn  6679:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6680:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6681:             }
                   6682:             if ($tdomain ne '') {
                   6683:                 if (defined($dompriv)) {
                   6684:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6685:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6686:                 }
                   6687:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6688:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6689:                         my $rolename = $1;
                   6690:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6691:                     }
1.567     raeburn  6692:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6693:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6694:                 }
                   6695:             }
                   6696:         }
                   6697:     }
                   6698: }
                   6699: 
1.1332    raeburn  6700: sub course_adhocrole_privs {
                   6701:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6702:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6703:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6704:         my (%currprivs,%storeprivs);
                   6705:         foreach my $item (split(/:/,$coursepriv)) {
                   6706:             my ($priv,$restrict) = split(/\&/,$item);
                   6707:             $currprivs{$priv} = $restrict;
                   6708:         }
                   6709:         my (%possadd,%possremove,%full);
                   6710:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6711:             my ($priv,$restrict)=split(/\&/,$item);
                   6712:             $full{$priv} = $restrict;
                   6713:         }
                   6714:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6715:              next if ($item eq '');
                   6716:              my ($rule,$rest) = split(/=/,$item);
                   6717:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6718:              foreach my $priv (split(/:/,$rest)) {
                   6719:                  if ($priv ne '') {
                   6720:                      if ($rule eq 'off') {
                   6721:                          $possremove{$priv} = 1;
                   6722:                      } else {
                   6723:                          $possadd{$priv} = 1;
                   6724:                      }
                   6725:                  }
                   6726:              }
                   6727:          }
                   6728:          foreach my $priv (sort(keys(%full))) {
                   6729:              if (exists($currprivs{$priv})) {
                   6730:                  unless (exists($possremove{$priv})) {
                   6731:                      $storeprivs{$priv} = $currprivs{$priv};
                   6732:                  }
                   6733:              } elsif (exists($possadd{$priv})) {
                   6734:                  $storeprivs{$priv} = $full{$priv};
                   6735:              }
                   6736:          }
                   6737:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6738:      }
                   6739:      return $coursepriv;
                   6740: }
                   6741: 
1.678     raeburn  6742: sub group_roleprivs {
                   6743:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6744:     my $access = 1;
                   6745:     my $now = time;
                   6746:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6747:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6748:     if ($access) {
1.811     albertel 6749:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6750:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6751:     }
                   6752: }
1.567     raeburn  6753: 
                   6754: sub standard_roleprivs {
                   6755:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6756:     if (defined($pr{$trole.':s'})) {
                   6757:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6758:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6759:     }
                   6760:     if ($tdomain ne '') {
                   6761:         if (defined($pr{$trole.':d'})) {
                   6762:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6763:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6764:         }
                   6765:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6766:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6767:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6768:         }
                   6769:     }
                   6770: }
                   6771: 
                   6772: sub set_userprivs {
1.1064    raeburn  6773:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6774:     my $author=0;
                   6775:     my $adv=0;
1.1341    raeburn  6776:     my $rar=0;
1.678     raeburn  6777:     my %grouproles = ();
                   6778:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6779:         my @groupkeys; 
1.1000    raeburn  6780:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6781:             push(@groupkeys,$role);
                   6782:         }
                   6783:         if (ref($groups_roles) eq 'HASH') {
                   6784:             foreach my $key (keys(%{$groups_roles})) {
                   6785:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6786:                     push(@groupkeys,$key);
                   6787:                 }
                   6788:             }
                   6789:         }
                   6790:         if (@groupkeys > 0) {
                   6791:             foreach my $role (@groupkeys) {
                   6792:                 my ($trole,$area,$sec,$extendedarea);
                   6793:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6794:                     $trole = $1;
                   6795:                     $area = $2;
                   6796:                     $sec = $3;
                   6797:                     $extendedarea = $area.$sec;
                   6798:                     if (exists($$allgroups{$area})) {
                   6799:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6800:                             my $spec = $trole.'.'.$extendedarea;
                   6801:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6802:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6803:                         }
1.678     raeburn  6804:                     }
                   6805:                 }
                   6806:             }
                   6807:         }
                   6808:     }
1.800     albertel 6809:     foreach my $group (keys(%grouproles)) {
                   6810:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6811:     }
1.800     albertel 6812:     foreach my $role (keys(%{$allroles})) {
                   6813:         my %thesepriv;
1.941     raeburn  6814:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6815:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6816:             if ($item ne '') {
                   6817:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6818:                 if ($restrictions eq '') {
                   6819:                     $thesepriv{$privilege}='F';
                   6820:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6821:                     $thesepriv{$privilege}.=$restrictions;
                   6822:                 }
                   6823:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6824:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6825:             }
                   6826:         }
                   6827:         my $thesestr='';
1.1104    raeburn  6828:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6829: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6830: 	}
                   6831:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6832:     }
1.1341    raeburn  6833:     return ($author,$adv,$rar);
1.567     raeburn  6834: }
                   6835: 
1.994     raeburn  6836: sub role_status {
1.1104    raeburn  6837:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6838:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6839:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6840:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6841:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6842:             $$where = '/'.$two;
1.994     raeburn  6843:             $$trolecode=$$role.'.'.$$where;
                   6844:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6845:             $$tstatus='is';
1.1104    raeburn  6846:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6847:                 $$tstatus='future';
1.1034    raeburn  6848:                 if ($$tstart<$now) {
                   6849:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6850:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6851:                             my (%allroles,%allgroups,$group_privs,
                   6852:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6853:                             my %userroles = (
                   6854:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6855:                             );
1.1064    raeburn  6856:                             @rolecodes = ('cm'); 
1.1002    raeburn  6857:                             my $spec=$$role.'.'.$$where;
                   6858:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6859:                             if ($$role =~ /^cr\//) {
                   6860:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6861:                                 push(@rolecodes,'cr');
1.1002    raeburn  6862:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6863:                                 push(@rolecodes,$$role);
1.1002    raeburn  6864:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6865:                                                     $env{'user.name'});
1.1064    raeburn  6866:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6867:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6868:                                 $group_privs = &unescape($group_privs);
                   6869:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6870:                                 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  6871:                                 &get_groups_roles($tdomain,$trest,
                   6872:                                                   \%course_roles,\@rolecodes,
                   6873:                                                   \%groups_roles);
1.1002    raeburn  6874:                             } else {
1.1064    raeburn  6875:                                 push(@rolecodes,$$role);
1.1002    raeburn  6876:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6877:                             }
1.1341    raeburn  6878:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6879:                                                                    \%groups_roles);
1.1064    raeburn  6880:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6881:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6882:                         }
                   6883:                     }
1.1034    raeburn  6884:                     $$tstatus = 'is';
1.1002    raeburn  6885:                 }
1.994     raeburn  6886:             }
                   6887:             if ($$tend) {
1.1104    raeburn  6888:                 if ($$tend<$update) {
1.994     raeburn  6889:                     $$tstatus='expired';
                   6890:                 } elsif ($$tend<$now) {
                   6891:                     $$tstatus='will_not';
                   6892:                 }
                   6893:             }
                   6894:         }
                   6895:     }
                   6896: }
                   6897: 
1.1104    raeburn  6898: sub get_groups_roles {
                   6899:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6900:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6901:                   (ref($rolecodes) eq 'ARRAY') && 
                   6902:                   (ref($groups_roles) eq 'HASH')); 
                   6903:     if (keys(%{$cdom_courseroles}) > 0) {
                   6904:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6905:         if ($cdom ne '' && $cnum ne '') {
                   6906:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6907:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6908:                     my $crsrole = $1;
                   6909:                     my $crssec = $2;
                   6910:                     if ($crsrole =~ /^cr/) {
                   6911:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6912:                             push(@{$rolecodes},'cr');
                   6913:                         }
                   6914:                     } else {
                   6915:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6916:                             push(@{$rolecodes},$crsrole);
                   6917:                         }
                   6918:                     }
                   6919:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6920:                     if ($crssec ne '') {
                   6921:                         $rolekey .= "/$crssec";
                   6922:                     }
                   6923:                     $rolekey .= './';
                   6924:                     $groups_roles->{$rolekey} = $rolecodes;
                   6925:                 }
                   6926:             }
                   6927:         }
                   6928:     }
                   6929:     return;
                   6930: }
                   6931: 
                   6932: sub delete_env_groupprivs {
                   6933:     my ($where,$courseroles,$possroles) = @_;
                   6934:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6935:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6936:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6937:         %{$courseroles->{$udom}} =
                   6938:             &get_my_roles('','','userroles',['active'],
                   6939:                           $possroles,[$udom],1);
                   6940:     }
                   6941:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6942:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6943:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6944:             my $area = '/'.$cdom.'/'.$cnum;
                   6945:             my $privkey = "user.priv.$crsrole.$area";
                   6946:             if ($crssec ne '') {
                   6947:                 $privkey .= '/'.$crssec;
                   6948:             }
                   6949:             $privkey .= ".$area/$group";
                   6950:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6951:         }
                   6952:     }
                   6953:     return;
                   6954: }
                   6955: 
1.994     raeburn  6956: sub check_adhoc_privs {
1.1329    raeburn  6957:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6958:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6959:     if ($sec) {
                   6960:         $cckey .= '/'.$sec;
                   6961:     } 
1.1185    raeburn  6962:     my $setprivs;
1.994     raeburn  6963:     if ($env{$cckey}) {
                   6964:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6965:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6966:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6967:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6968:             $setprivs = 1;
1.994     raeburn  6969:         }
                   6970:     } else {
1.1330    raeburn  6971:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6972:         $setprivs = 1;
1.994     raeburn  6973:     }
1.1185    raeburn  6974:     return $setprivs;
1.994     raeburn  6975: }
                   6976: 
                   6977: sub set_adhoc_privileges {
1.1326    raeburn  6978: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6979:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6980:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6981:     if ($sec ne '') {
                   6982:         $area .= '/'.$sec;
                   6983:     }
1.994     raeburn  6984:     my $spec = $role.'.'.$area;
                   6985:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6986:                                   $env{'user.name'},1);
1.1326    raeburn  6987:     my %rolehash = ();
1.1332    raeburn  6988:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6989:         my $rolename = $1;
1.1326    raeburn  6990:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6991:         my %domdef = &get_domain_defaults($dcdom);
                   6992:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6993:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6994:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6995:             }
                   6996:         }
1.1326    raeburn  6997:     } else {
                   6998:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6999:     }
1.1341    raeburn  7000:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7001:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7002:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7003:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7004:             ($caller eq 'tiny')) {
1.1088    raeburn  7005:         &appenv( {'request.role'        => $spec,
                   7006:                   'request.role.domain' => $dcdom,
1.1332    raeburn  7007:                   'request.course.sec'  => $sec,
1.1088    raeburn  7008:                  }
                   7009:                );
                   7010:         my $tadv=0;
                   7011:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7012:         &appenv({'request.role.adv'    => $tadv});
                   7013:     }
1.994     raeburn  7014: }
                   7015: 
1.12      www      7016: # --------------------------------------------------------------- get interface
                   7017: 
                   7018: sub get {
1.131     albertel 7019:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7020:    my $items='';
1.800     albertel 7021:    foreach my $item (@$storearr) {
                   7022:        $items.=&escape($item).'&';
1.191     harris41 7023:    }
1.12      www      7024:    $items=~s/\&$//;
1.620     albertel 7025:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7026:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7027:    my $uhome=&homeserver($uname,$udomain);
                   7028: 
1.133     albertel 7029:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7030:    my @pairs=split(/\&/,$rep);
1.273     albertel 7031:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7032:      return @pairs;
                   7033:    }
1.15      www      7034:    my %returnhash=();
1.42      www      7035:    my $i=0;
1.800     albertel 7036:    foreach my $item (@$storearr) {
                   7037:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7038:       $i++;
1.191     harris41 7039:    }
1.15      www      7040:    return %returnhash;
1.27      www      7041: }
                   7042: 
                   7043: # --------------------------------------------------------------- del interface
                   7044: 
                   7045: sub del {
1.133     albertel 7046:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7047:    my $items='';
1.800     albertel 7048:    foreach my $item (@$storearr) {
                   7049:        $items.=&escape($item).'&';
1.191     harris41 7050:    }
1.984     neumanie 7051: 
1.27      www      7052:    $items=~s/\&$//;
1.620     albertel 7053:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7054:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7055:    my $uhome=&homeserver($uname,$udomain);
                   7056:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7057: }
                   7058: 
                   7059: # -------------------------------------------------------------- dump interface
                   7060: 
1.1180    droeschl 7061: sub unserialize {
                   7062:     my ($rep, $escapedkeys) = @_;
                   7063: 
                   7064:     return {} if $rep =~ /^error/;
                   7065: 
                   7066:     my %returnhash=();
1.1252    raeburn  7067: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7068: 	    my ($key, $value) = split(/=/, $item, 2);
                   7069: 	    $key = unescape($key) unless $escapedkeys;
                   7070: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7071: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7072: 	}
                   7073:     #return %returnhash;
                   7074:     return \%returnhash;
                   7075: }        
                   7076: 
                   7077: # see Lond::dump_with_regexp
                   7078: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7079: sub dump {
1.1180    droeschl 7080:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 7081:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7082:     if (!$uname) { $uname=$env{'user.name'}; }
                   7083:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7084: 
1.1266    raeburn  7085:     if ($regexp) {
                   7086:         $regexp=&escape($regexp);
                   7087:     } else {
                   7088:         $regexp='.';
                   7089:     }
1.1180    droeschl 7090:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7091:         # user is hosted on this machine
1.1266    raeburn  7092:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7093:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7094:         return %{unserialize($reply, $escapedkeys)};
                   7095:     }
1.1166    raeburn  7096:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 7097:     my @pairs=split(/\&/,$rep);
                   7098:     my %returnhash=();
1.1098    foxr     7099:     if (!($rep =~ /^error/ )) {
                   7100: 	foreach my $item (@pairs) {
                   7101: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7102:         $key = unescape($key) unless $escapedkeys;
                   7103:         #$key = &unescape($key);
1.1098    foxr     7104: 	    next if ($key =~ /^error: 2 /);
                   7105: 	    $returnhash{$key}=&thaw_unescape($value);
                   7106: 	}
1.755     albertel 7107:     }
                   7108:     return %returnhash;
1.407     www      7109: }
                   7110: 
1.1098    foxr     7111: 
1.717     albertel 7112: # --------------------------------------------------------- dumpstore interface
                   7113: 
                   7114: sub dumpstore {
                   7115:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7116:    # same as dump but keys must be escaped. They may contain colon separated
                   7117:    # lists of values that may themself contain colons (e.g. symbs).
                   7118:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7119: }
                   7120: 
1.407     www      7121: # -------------------------------------------------------------- keys interface
                   7122: 
                   7123: sub getkeys {
                   7124:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7125:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7126:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7127:    my $uhome=&homeserver($uname,$udomain);
                   7128:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7129:    my @keyarray=();
1.800     albertel 7130:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7131:       next if ($key =~ /^error: 2 /);
1.800     albertel 7132:       push(@keyarray,&unescape($key));
1.407     www      7133:    }
                   7134:    return @keyarray;
1.318     matthew  7135: }
                   7136: 
1.319     matthew  7137: # --------------------------------------------------------------- currentdump
                   7138: sub currentdump {
1.328     matthew  7139:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7140:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7141:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7142:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7143:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7144:    my $rep;
                   7145: 
                   7146:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7147:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7148:                    $courseid)));
                   7149:    } else {
                   7150:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7151:    }
                   7152: 
1.318     matthew  7153:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7154:    #
1.318     matthew  7155:    my %returnhash=();
1.319     matthew  7156:    #
1.1343    raeburn  7157:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7158:        # an old lond will not know currentdump
                   7159:        # Do a dump and make it look like a currentdump
1.822     albertel 7160:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7161:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7162:        my %hash = @tmp;
                   7163:        @tmp=();
1.424     matthew  7164:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7165:    } else {
                   7166:        my @pairs=split(/\&/,$rep);
1.800     albertel 7167:        foreach my $pair (@pairs) {
                   7168:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7169:            my ($symb,$param) = split(/:/,$key);
                   7170:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7171:                                                         &thaw_unescape($value);
1.319     matthew  7172:        }
1.191     harris41 7173:    }
1.12      www      7174:    return %returnhash;
1.424     matthew  7175: }
                   7176: 
                   7177: sub convert_dump_to_currentdump{
                   7178:     my %hash = %{shift()};
                   7179:     my %returnhash;
                   7180:     # Code ripped from lond, essentially.  The only difference
                   7181:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7182:     # we might run in to problems with parameter names =~ /^v\./
                   7183:     while (my ($key,$value) = each(%hash)) {
                   7184:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7185: 	$symb  = &unescape($symb);
                   7186: 	$param = &unescape($param);
1.424     matthew  7187:         next if ($v eq 'version' || $symb eq 'keys');
                   7188:         next if (exists($returnhash{$symb}) &&
                   7189:                  exists($returnhash{$symb}->{$param}) &&
                   7190:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7191:         $returnhash{$symb}->{$param}=$value;
                   7192:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7193:     }
                   7194:     #
                   7195:     # Remove all of the keys in the hashes which keep track of
                   7196:     # the version of the parameter.
                   7197:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7198:         # use a foreach because we are going to delete from the hash.
                   7199:         foreach my $key (keys(%$param_hash)) {
                   7200:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7201:         }
                   7202:     }
                   7203:     return \%returnhash;
1.12      www      7204: }
                   7205: 
1.627     albertel 7206: # ------------------------------------------------------ critical inc interface
                   7207: 
                   7208: sub cinc {
                   7209:     return &inc(@_,'critical');
                   7210: }
                   7211: 
1.449     matthew  7212: # --------------------------------------------------------------- inc interface
                   7213: 
                   7214: sub inc {
1.627     albertel 7215:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7216:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7217:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7218:     my $uhome=&homeserver($uname,$udomain);
                   7219:     my $items='';
                   7220:     if (! ref($store)) {
                   7221:         # got a single value, so use that instead
                   7222:         $items = &escape($store).'=&';
                   7223:     } elsif (ref($store) eq 'SCALAR') {
                   7224:         $items = &escape($$store).'=&';        
                   7225:     } elsif (ref($store) eq 'ARRAY') {
                   7226:         $items = join('=&',map {&escape($_);} @{$store});
                   7227:     } elsif (ref($store) eq 'HASH') {
                   7228:         while (my($key,$value) = each(%{$store})) {
                   7229:             $items.= &escape($key).'='.&escape($value).'&';
                   7230:         }
                   7231:     }
                   7232:     $items=~s/\&$//;
1.627     albertel 7233:     if ($critical) {
                   7234: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7235:     } else {
                   7236: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7237:     }
1.449     matthew  7238: }
                   7239: 
1.12      www      7240: # --------------------------------------------------------------- put interface
                   7241: 
                   7242: sub put {
1.134     albertel 7243:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7244:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7245:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7246:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7247:    my $items='';
1.800     albertel 7248:    foreach my $item (keys(%$storehash)) {
                   7249:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7250:    }
1.12      www      7251:    $items=~s/\&$//;
1.134     albertel 7252:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7253: }
                   7254: 
1.631     albertel 7255: # ------------------------------------------------------------ newput interface
                   7256: 
                   7257: sub newput {
                   7258:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7259:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7260:    if (!$uname) { $uname=$env{'user.name'}; }
                   7261:    my $uhome=&homeserver($uname,$udomain);
                   7262:    my $items='';
                   7263:    foreach my $key (keys(%$storehash)) {
                   7264:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7265:    }
                   7266:    $items=~s/\&$//;
                   7267:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7268: }
                   7269: 
                   7270: # ---------------------------------------------------------  putstore interface
                   7271: 
1.524     raeburn  7272: sub putstore {
1.1269    raeburn  7273:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7274:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7275:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7276:    my $uhome=&homeserver($uname,$udomain);
                   7277:    my $items='';
1.715     albertel 7278:    foreach my $key (keys(%$storehash)) {
                   7279:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7280:    }
1.715     albertel 7281:    $items=~s/\&$//;
1.716     albertel 7282:    my $esc_symb=&escape($symb);
                   7283:    my $esc_v=&escape($version);
1.715     albertel 7284:    my $reply =
1.716     albertel 7285:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7286: 	      $uhome);
1.1269    raeburn  7287:    if (($tolog) && ($reply eq 'ok')) {
                   7288:        my $namevalue='';
                   7289:        foreach my $key (keys(%{$storehash})) {
                   7290:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7291:        }
1.1434    raeburn  7292:        my $ip = &get_requestor_ip();
                   7293:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7294:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7295:                      '&version='.$esc_v.
                   7296:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7297:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7298:    }
1.715     albertel 7299:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7300:        # gfall back to way things use to be done
1.715     albertel 7301:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7302: 			    $uname);
1.524     raeburn  7303:    }
1.715     albertel 7304:    return $reply;
                   7305: }
                   7306: 
                   7307: sub old_putstore {
1.716     albertel 7308:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7309:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7310:     if (!$uname) { $uname=$env{'user.name'}; }
                   7311:     my $uhome=&homeserver($uname,$udomain);
                   7312:     my %newstorehash;
1.800     albertel 7313:     foreach my $item (keys(%$storehash)) {
                   7314: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7315: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7316:     }
                   7317:     my $items='';
                   7318:     my %allitems = ();
1.800     albertel 7319:     foreach my $item (keys(%newstorehash)) {
                   7320: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7321: 	    my $key = $1.':keys:'.$2;
                   7322: 	    $allitems{$key} .= $3.':';
                   7323: 	}
1.800     albertel 7324: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7325:     }
1.800     albertel 7326:     foreach my $item (keys(%allitems)) {
                   7327: 	$allitems{$item} =~ s/\:$//;
                   7328: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7329:     }
                   7330:     $items=~s/\&$//;
                   7331:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7332: }
                   7333: 
1.47      www      7334: # ------------------------------------------------------ critical put interface
                   7335: 
                   7336: sub cput {
1.134     albertel 7337:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7338:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7339:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7340:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7341:    my $items='';
1.800     albertel 7342:    foreach my $item (keys(%$storehash)) {
                   7343:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7344:    }
1.47      www      7345:    $items=~s/\&$//;
1.134     albertel 7346:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7347: }
                   7348: 
                   7349: # -------------------------------------------------------------- eget interface
                   7350: 
                   7351: sub eget {
1.133     albertel 7352:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7353:    my $items='';
1.800     albertel 7354:    foreach my $item (@$storearr) {
                   7355:        $items.=&escape($item).'&';
1.191     harris41 7356:    }
1.12      www      7357:    $items=~s/\&$//;
1.620     albertel 7358:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7359:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7360:    my $uhome=&homeserver($uname,$udomain);
                   7361:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7362:    my @pairs=split(/\&/,$rep);
                   7363:    my %returnhash=();
1.42      www      7364:    my $i=0;
1.800     albertel 7365:    foreach my $item (@$storearr) {
                   7366:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7367:       $i++;
1.191     harris41 7368:    }
1.12      www      7369:    return %returnhash;
                   7370: }
                   7371: 
1.667     albertel 7372: # ------------------------------------------------------------ tmpput interface
                   7373: sub tmpput {
1.802     raeburn  7374:     my ($storehash,$server,$context)=@_;
1.667     albertel 7375:     my $items='';
1.800     albertel 7376:     foreach my $item (keys(%$storehash)) {
                   7377: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7378:     }
                   7379:     $items=~s/\&$//;
1.802     raeburn  7380:     if (defined($context)) {
                   7381:         $items .= ':'.&escape($context);
                   7382:     }
1.667     albertel 7383:     return &reply("tmpput:$items",$server);
                   7384: }
                   7385: 
                   7386: # ------------------------------------------------------------ tmpget interface
                   7387: sub tmpget {
1.688     albertel 7388:     my ($token,$server)=@_;
                   7389:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7390:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7391:     my %returnhash;
1.1328    raeburn  7392:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7393:         return %returnhash;
                   7394:     }
1.667     albertel 7395:     foreach my $item (split(/\&/,$rep)) {
                   7396: 	my ($key,$value)=split(/=/,$item);
                   7397: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7398:     }
                   7399:     return %returnhash;
                   7400: }
                   7401: 
1.1113    raeburn  7402: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7403: sub tmpdel {
                   7404:     my ($token,$server)=@_;
                   7405:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7406:     return &reply("tmpdel:$token",$server);
                   7407: }
                   7408: 
1.1198    raeburn  7409: # ------------------------------------------------------------ get_timebased_id 
                   7410: 
                   7411: sub get_timebased_id {
                   7412:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7413:         $maxtries) = @_;
                   7414:     my ($newid,$error,$dellock);
                   7415:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7416:         return ('','ok','invalid call to get suffix');
                   7417:     }
                   7418: 
                   7419: # set defaults for any optional args for which values were not supplied
                   7420:     if ($who eq '') {
                   7421:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7422:     }
                   7423:     if (!$locktries) {
                   7424:         $locktries = 3;
                   7425:     }
                   7426:     if (!$maxtries) {
                   7427:         $maxtries = 10;
                   7428:     }
                   7429:     
                   7430:     if (($cdom eq '') || ($cnum eq '')) {
                   7431:         if ($env{'request.course.id'}) {
                   7432:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7433:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7434:         }
                   7435:         if (($cdom eq '') || ($cnum eq '')) {
                   7436:             return ('','ok','call to get suffix not in course context');
                   7437:         }
                   7438:     }
                   7439: 
                   7440: # construct locking item
                   7441:     my $lockhash = {
                   7442:                       $prefix."\0".'locked_'.$keyid => $who,
                   7443:                    };
                   7444:     my $tries = 0;
                   7445: 
                   7446: # attempt to get lock on nohist_$namespace file
                   7447:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7448:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7449:         $tries ++;
                   7450:         sleep 1;
                   7451:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7452:     }
                   7453: 
                   7454: # attempt to get unique identifier, based on current timestamp
                   7455:     if ($gotlock eq 'ok') {
                   7456:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7457:         my $id = time;
                   7458:         $newid = $id;
1.1268    raeburn  7459:         if ($idtype eq 'addcode') {
                   7460:             $newid .= &sixnum_code();
                   7461:         }
1.1198    raeburn  7462:         my $idtries = 0;
                   7463:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7464:             if ($idtype eq 'concat') {
                   7465:                 $newid = $id.$idtries;
1.1268    raeburn  7466:             } elsif ($idtype eq 'addcode') {
                   7467:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7468:             } else {
                   7469:                 $newid ++;
                   7470:             }
                   7471:             $idtries ++;
                   7472:         }
                   7473:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7474:             my %new_item =  (
                   7475:                               $prefix."\0".$newid => $who,
                   7476:                             );
                   7477:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7478:                                                  $cdom,$cnum);
                   7479:             if ($putresult ne 'ok') {
                   7480:                 undef($newid);
                   7481:                 $error = 'error saving new item: '.$putresult;
                   7482:             }
                   7483:         } else {
1.1268    raeburn  7484:              undef($newid);
1.1198    raeburn  7485:              $error = ('error: no unique suffix available for the new item ');
                   7486:         }
                   7487: #  remove lock
                   7488:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7489:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7490:     } else {
                   7491:         $error = "error: could not obtain lockfile\n";
                   7492:         $dellock = 'ok';
1.1276    raeburn  7493:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7494:             $dellock = 'nolock';
                   7495:         }
1.1198    raeburn  7496:     }
                   7497:     return ($newid,$dellock,$error);
                   7498: }
                   7499: 
1.1268    raeburn  7500: sub sixnum_code {
                   7501:     my $code;
                   7502:     for (0..6) {
                   7503:         $code .= int( rand(9) );
                   7504:     }
                   7505:     return $code;
                   7506: }
                   7507: 
1.765     albertel 7508: # -------------------------------------------------- portfolio access checking
                   7509: 
                   7510: sub portfolio_access {
1.1270    raeburn  7511:     my ($requrl,$clientip) = @_;
1.765     albertel 7512:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7513:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7514:     if ($result) {
                   7515:         my %setters;
                   7516:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7517:             my ($startblock,$endblock) =
                   7518:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7519:             if ($startblock && $endblock) {
                   7520:                 return 'B';
                   7521:             }
                   7522:         } else {
                   7523:             my ($startblock,$endblock) =
                   7524:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7525:             if ($startblock && $endblock) {
                   7526:                 return 'B';
                   7527:             }
                   7528:         }
                   7529:     }
1.765     albertel 7530:     if ($result eq 'ok') {
1.766     albertel 7531:        return 'F';
1.765     albertel 7532:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7533:        return 'A';
1.765     albertel 7534:     }
1.766     albertel 7535:     return '';
1.765     albertel 7536: }
                   7537: 
                   7538: sub get_portfolio_access {
1.1270    raeburn  7539:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7540: 
                   7541:     if (!ref($access_hash)) {
                   7542: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7543: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7544: 						   $file_name);
                   7545: 	$access_hash = $access_controls{$file_name};
                   7546:     }
                   7547: 
1.1270    raeburn  7548:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7549:     my $now = time;
                   7550:     if (ref($access_hash) eq 'HASH') {
                   7551:         foreach my $key (keys(%{$access_hash})) {
                   7552:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7553:             if ($start > $now) {
                   7554:                 next;
                   7555:             }
                   7556:             if ($end && $end<$now) {
                   7557:                 next;
                   7558:             }
                   7559:             if ($scope eq 'public') {
                   7560:                 $public = $key;
                   7561:                 last;
                   7562:             } elsif ($scope eq 'guest') {
                   7563:                 $guest = $key;
                   7564:             } elsif ($scope eq 'domains') {
                   7565:                 push(@domains,$key);
                   7566:             } elsif ($scope eq 'users') {
                   7567:                 push(@users,$key);
                   7568:             } elsif ($scope eq 'course') {
                   7569:                 push(@courses,$key);
                   7570:             } elsif ($scope eq 'group') {
                   7571:                 push(@groups,$key);
1.1270    raeburn  7572:             } elsif ($scope eq 'ip') {
                   7573:                 push(@ips,$key);
1.765     albertel 7574:             }
                   7575:         }
                   7576:         if ($public) {
                   7577:             return 'ok';
1.1270    raeburn  7578:         } elsif (@ips > 0) {
                   7579:             my $allowed;
                   7580:             foreach my $ipkey (@ips) {
                   7581:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7582:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7583:                         $allowed = 1;
                   7584:                         last; 
                   7585:                     }
                   7586:                 }
                   7587:             }
                   7588:             if ($allowed) {
                   7589:                 return 'ok';
                   7590:             }
1.765     albertel 7591:         }
                   7592:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7593:             if ($guest) {
                   7594:                 return $guest;
                   7595:             }
                   7596:         } else {
                   7597:             if (@domains > 0) {
                   7598:                 foreach my $domkey (@domains) {
                   7599:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7600:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7601:                             return 'ok';
                   7602:                         }
                   7603:                     }
                   7604:                 }
                   7605:             }
                   7606:             if (@users > 0) {
                   7607:                 foreach my $userkey (@users) {
1.865     raeburn  7608:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7609:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7610:                             if (ref($item) eq 'HASH') {
                   7611:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7612:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7613:                                     return 'ok';
                   7614:                                 }
                   7615:                             }
                   7616:                         }
                   7617:                     } 
1.765     albertel 7618:                 }
                   7619:             }
                   7620:             my %roleshash;
                   7621:             my @courses_and_groups = @courses;
                   7622:             push(@courses_and_groups,@groups); 
                   7623:             if (@courses_and_groups > 0) {
                   7624:                 my (%allgroups,%allroles); 
                   7625:                 my ($start,$end,$role,$sec,$group);
                   7626:                 foreach my $envkey (%env) {
1.1060    raeburn  7627:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7628:                         my $cid = $2.'_'.$3; 
                   7629:                         if ($1 eq 'gr') {
                   7630:                             $group = $4;
                   7631:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7632:                         } else {
                   7633:                             if ($4 eq '') {
                   7634:                                 $sec = 'none';
                   7635:                             } else {
                   7636:                                 $sec = $4;
                   7637:                             }
                   7638:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7639:                         }
1.811     albertel 7640:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7641:                         my $cid = $2.'_'.$3;
                   7642:                         if ($4 eq '') {
                   7643:                             $sec = 'none';
                   7644:                         } else {
                   7645:                             $sec = $4;
                   7646:                         }
                   7647:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7648:                     }
                   7649:                 }
                   7650:                 if (keys(%allroles) == 0) {
                   7651:                     return;
                   7652:                 }
                   7653:                 foreach my $key (@courses_and_groups) {
                   7654:                     my %content = %{$$access_hash{$key}};
                   7655:                     my $cnum = $content{'number'};
                   7656:                     my $cdom = $content{'domain'};
                   7657:                     my $cid = $cdom.'_'.$cnum;
                   7658:                     if (!exists($allroles{$cid})) {
                   7659:                         next;
                   7660:                     }    
                   7661:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7662:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7663:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7664:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7665:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7666:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7667:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7668:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7669:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7670:                                         if (grep/^all$/,@sections) {
                   7671:                                             return 'ok';
                   7672:                                         } else {
                   7673:                                             if (grep/^$sec$/,@sections) {
                   7674:                                                 return 'ok';
                   7675:                                             }
                   7676:                                         }
                   7677:                                     }
                   7678:                                 }
                   7679:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7680:                                     if (grep/^none$/,@groups) {
                   7681:                                         return 'ok';
                   7682:                                     }
                   7683:                                 } else {
                   7684:                                     if (grep/^all$/,@groups) {
                   7685:                                         return 'ok';
                   7686:                                     } 
                   7687:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7688:                                         if (grep/^$group$/,@groups) {
                   7689:                                             return 'ok';
                   7690:                                         }
                   7691:                                     }
                   7692:                                 } 
                   7693:                             }
                   7694:                         }
                   7695:                     }
                   7696:                 }
                   7697:             }
                   7698:             if ($guest) {
                   7699:                 return $guest;
                   7700:             }
                   7701:         }
                   7702:     }
                   7703:     return;
                   7704: }
                   7705: 
                   7706: sub course_group_datechecker {
                   7707:     my ($dates,$now,$status) = @_;
                   7708:     my ($start,$end) = split(/\./,$dates);
                   7709:     if (!$start && !$end) {
                   7710:         return 'ok';
                   7711:     }
                   7712:     if (grep/^active$/,@{$status}) {
                   7713:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7714:             return 'ok';
                   7715:         }
                   7716:     }
                   7717:     if (grep/^previous$/,@{$status}) {
                   7718:         if ($end > $now ) {
                   7719:             return 'ok';
                   7720:         }
                   7721:     }
                   7722:     if (grep/^future$/,@{$status}) {
                   7723:         if ($start > $now) {
                   7724:             return 'ok';
                   7725:         }
                   7726:     }
                   7727:     return; 
                   7728: }
                   7729: 
                   7730: sub parse_portfolio_url {
                   7731:     my ($url) = @_;
                   7732: 
                   7733:     my ($type,$udom,$unum,$group,$file_name);
                   7734:     
1.823     albertel 7735:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7736: 	$type = 1;
                   7737:         $udom = $1;
                   7738:         $unum = $2;
                   7739:         $file_name = $3;
1.823     albertel 7740:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7741: 	$type = 2;
                   7742:         $udom = $1;
                   7743:         $unum = $2;
                   7744:         $group = $3;
                   7745:         $file_name = $3.'/'.$4;
                   7746:     }
                   7747:     if (wantarray) {
                   7748: 	return ($type,$udom,$unum,$file_name,$group);
                   7749:     }
                   7750:     return $type;
                   7751: }
                   7752: 
                   7753: sub is_portfolio_url {
                   7754:     my ($url) = @_;
                   7755:     return scalar(&parse_portfolio_url($url));
                   7756: }
                   7757: 
1.798     raeburn  7758: sub is_portfolio_file {
                   7759:     my ($file) = @_;
1.820     raeburn  7760:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7761:         return 1;
                   7762:     }
                   7763:     return;
                   7764: }
                   7765: 
1.976     raeburn  7766: sub usertools_access {
1.1084    raeburn  7767:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7768:     my ($access,%tools);
                   7769:     if ($context eq '') {
                   7770:         $context = 'tools';
                   7771:     }
                   7772:     if ($context eq 'requestcourses') {
                   7773:         %tools = (
                   7774:                       official   => 1,
                   7775:                       unofficial => 1,
1.1006    raeburn  7776:                       community  => 1,
1.1246    raeburn  7777:                       textbook   => 1,
1.1305    raeburn  7778:                       placement  => 1,
1.1368    raeburn  7779:                       lti        => 1,
1.985     raeburn  7780:                  );
1.1183    raeburn  7781:     } elsif ($context eq 'requestauthor') {
                   7782:         %tools = (
                   7783:                       requestauthor => 1,
                   7784:                  );
1.985     raeburn  7785:     } else {
                   7786:         %tools = (
                   7787:                       aboutme   => 1,
                   7788:                       blog      => 1,
1.1177    raeburn  7789:                       webdav    => 1,
1.985     raeburn  7790:                       portfolio => 1,
                   7791:                  );
                   7792:     }
1.976     raeburn  7793:     return if (!defined($tools{$tool}));
                   7794: 
1.1242    raeburn  7795:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7796:         $udom = $env{'user.domain'};
                   7797:         $uname = $env{'user.name'};
                   7798:     }
                   7799: 
1.978     raeburn  7800:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7801:         if ($action ne 'reload') {
1.985     raeburn  7802:             if ($context eq 'requestcourses') {
                   7803:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7804:             } elsif ($context eq 'requestauthor') {
                   7805:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7806:             } else {
                   7807:                 return $env{'environment.availabletools.'.$tool};
                   7808:             }
                   7809:         }
1.976     raeburn  7810:     }
                   7811: 
1.1183    raeburn  7812:     my ($toolstatus,$inststatus,$envkey);
                   7813:     if ($context eq 'requestauthor') {
                   7814:         $envkey = $context; 
                   7815:     } else {
                   7816:         $envkey = $context.'.'.$tool;
                   7817:     }
1.976     raeburn  7818: 
1.985     raeburn  7819:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7820:          ($action ne 'reload')) {
1.1183    raeburn  7821:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7822:         $inststatus = $env{'environment.inststatus'};
                   7823:     } else {
1.1084    raeburn  7824:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7825:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7826:             $inststatus = $userenvref->{'inststatus'};
                   7827:         } else {
1.1183    raeburn  7828:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7829:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7830:             $inststatus = $userenv{'inststatus'};
                   7831:         }
1.976     raeburn  7832:     }
                   7833: 
                   7834:     if ($toolstatus ne '') {
                   7835:         if ($toolstatus) {
                   7836:             $access = 1;
                   7837:         } else {
                   7838:             $access = 0;
                   7839:         }
                   7840:         return $access;
                   7841:     }
                   7842: 
1.1084    raeburn  7843:     my ($is_adv,%domdef);
                   7844:     if (ref($is_advref) eq 'HASH') {
                   7845:         $is_adv = $is_advref->{'is_adv'};
                   7846:     } else {
                   7847:         $is_adv = &is_advanced_user($udom,$uname);
                   7848:     }
                   7849:     if (ref($domdefref) eq 'HASH') {
                   7850:         %domdef = %{$domdefref};
                   7851:     } else {
                   7852:         %domdef = &get_domain_defaults($udom);
                   7853:     }
1.976     raeburn  7854:     if (ref($domdef{$tool}) eq 'HASH') {
                   7855:         if ($is_adv) {
                   7856:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7857:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7858:                     $access = 1;
                   7859:                 } else {
                   7860:                     $access = 0;
                   7861:                 }
                   7862:                 return $access;
                   7863:             }
                   7864:         }
                   7865:         if ($inststatus ne '') {
                   7866:             my ($hasaccess,$hasnoaccess);
                   7867:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7868:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7869:                     if ($domdef{$tool}{$affiliation}) {
                   7870:                         $hasaccess = 1;
                   7871:                     } else {
                   7872:                         $hasnoaccess = 1;
                   7873:                     }
                   7874:                 }
                   7875:             }
                   7876:             if ($hasaccess || $hasnoaccess) {
                   7877:                 if ($hasaccess) {
                   7878:                     $access = 1;
                   7879:                 } elsif ($hasnoaccess) {
                   7880:                     $access = 0; 
                   7881:                 }
                   7882:                 return $access;
                   7883:             }
                   7884:         } else {
                   7885:             if ($domdef{$tool}{'default'} ne '') {
                   7886:                 if ($domdef{$tool}{'default'}) {
                   7887:                     $access = 1;
                   7888:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7889:                     $access = 0;
                   7890:                 }
                   7891:                 return $access;
                   7892:             }
                   7893:         }
                   7894:     } else {
1.1177    raeburn  7895:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7896:             $access = 1;
                   7897:         } else {
                   7898:             $access = 0;
                   7899:         }
1.976     raeburn  7900:         return $access;
                   7901:     }
                   7902: }
                   7903: 
1.1050    raeburn  7904: sub is_course_owner {
                   7905:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7906:     if (($udom eq '') || ($uname eq '')) {
                   7907:         $udom = $env{'user.domain'};
                   7908:         $uname = $env{'user.name'};
                   7909:     }
                   7910:     unless (($udom eq '') || ($uname eq '')) {
                   7911:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7912:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7913:                 return 1;
                   7914:             } else {
                   7915:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7916:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7917:                     return 1;
                   7918:                 }
                   7919:             }
                   7920:         }
                   7921:     }
                   7922:     return;
                   7923: }
                   7924: 
1.976     raeburn  7925: sub is_advanced_user {
                   7926:     my ($udom,$uname) = @_;
1.1085    raeburn  7927:     if ($udom ne '' && $uname ne '') {
                   7928:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7929:             if (wantarray) {
                   7930:                 return ($env{'user.adv'},$env{'user.author'});
                   7931:             } else {
                   7932:                 return $env{'user.adv'};
                   7933:             }
1.1085    raeburn  7934:         }
                   7935:     }
1.976     raeburn  7936:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7937:     my %allroles;
1.1128    raeburn  7938:     my ($is_adv,$is_author);
1.976     raeburn  7939:     foreach my $role (keys(%roleshash)) {
                   7940:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7941:         my $area = '/'.$tdomain.'/'.$trest;
                   7942:         if ($sec ne '') {
                   7943:             $area .= '/'.$sec;
                   7944:         }
                   7945:         if (($area ne '') && ($trole ne '')) {
                   7946:             my $spec=$trole.'.'.$area;
                   7947:             if ($trole =~ /^cr\//) {
                   7948:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7949:             } elsif ($trole ne 'gr') {
                   7950:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7951:             }
1.1128    raeburn  7952:             if ($trole eq 'au') {
                   7953:                 $is_author = 1;
                   7954:             }
1.976     raeburn  7955:         }
                   7956:     }
                   7957:     foreach my $role (keys(%allroles)) {
                   7958:         last if ($is_adv);
                   7959:         foreach my $item (split(/:/,$allroles{$role})) {
                   7960:             if ($item ne '') {
                   7961:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7962:                 if ($privilege eq 'adv') {
                   7963:                     $is_adv = 1;
                   7964:                     last;
                   7965:                 }
                   7966:             }
                   7967:         }
                   7968:     }
1.1128    raeburn  7969:     if (wantarray) {
                   7970:         return ($is_adv,$is_author);
                   7971:     }
1.976     raeburn  7972:     return $is_adv;
                   7973: }
1.798     raeburn  7974: 
1.1035    raeburn  7975: sub check_can_request {
1.1368    raeburn  7976:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7977:     my $canreq = 0;
1.1368    raeburn  7978:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7979:         $uname = $env{'user.name'};
                   7980:         $udom = $env{'user.domain'};
                   7981:     }
1.1035    raeburn  7982:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7983:     my @options = ('approval','validate','autolimit');
                   7984:     my $optregex = join('|',@options);
                   7985:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7986:         foreach my $type (@{$types}) {
1.1368    raeburn  7987:             if (&usertools_access($uname,$udom,$type,undef,
                   7988:                                   'requestcourses')) {
1.1035    raeburn  7989:                 $canreq ++;
1.1036    raeburn  7990:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7991:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7992:                 }
1.1368    raeburn  7993:                 if ($dom eq $udom) {
1.1035    raeburn  7994:                     $can_request->{$type} = 1;
                   7995:                 }
                   7996:             }
1.1368    raeburn  7997:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7998:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7999:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8000:                 if (@curr > 0) {
1.1036    raeburn  8001:                     foreach my $item (@curr) {
                   8002:                         if (ref($request_domains) eq 'HASH') {
                   8003:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8004:                             if ($otherdom ne '') {
                   8005:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8006:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8007:                                         push(@{$request_domains->{$type}},$otherdom);
                   8008:                                     }
                   8009:                                 } else {
                   8010:                                     push(@{$request_domains->{$type}},$otherdom);
                   8011:                                 }
                   8012:                             }
                   8013:                         }
                   8014:                     }
1.1368    raeburn  8015:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8016:                         $canreq ++;
1.1035    raeburn  8017:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8018:                             $can_request->{$type} = 1;
                   8019:                         }
                   8020:                     }
                   8021:                 }
                   8022:             }
                   8023:         }
                   8024:     }
                   8025:     return $canreq;
                   8026: }
                   8027: 
1.341     www      8028: # ---------------------------------------------- Custom access rule evaluation
                   8029: 
                   8030: sub customaccess {
                   8031:     my ($priv,$uri)=@_;
1.807     albertel 8032:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8033:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8034:     $udom = &LONCAPA::clean_domain($udom);
                   8035:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8036:     my $access=0;
1.800     albertel 8037:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8038: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8039: 	if ($type eq 'user') {
                   8040: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8041: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8042: 		if ($tdom) {
                   8043: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8044: 		}
1.896     albertel 8045: 		if ($tuname) {
                   8046: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8047: 		}
                   8048: 		$access=($effect eq 'allow');
                   8049: 		last;
                   8050: 	    }
                   8051: 	} else {
                   8052: 	    if ($role) {
                   8053: 		if ($role ne $urole) { next; }
                   8054: 	    }
                   8055: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8056: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8057: 		if ($tdom) {
                   8058: 		    if ($tdom ne $udom) { next; }
                   8059: 		}
                   8060: 		if ($tcrs) {
                   8061: 		    if ($tcrs ne $ucrs) { next; }
                   8062: 		}
                   8063: 		if ($tsec) {
                   8064: 		    if ($tsec ne $usec) { next; }
                   8065: 		}
                   8066: 		$access=($effect eq 'allow');
                   8067: 		last;
                   8068: 	    }
                   8069: 	    if ($realm eq '' && $role eq '') {
                   8070: 		$access=($effect eq 'allow');
                   8071: 	    }
1.402     bowersj2 8072: 	}
1.341     www      8073:     }
                   8074:     return $access;
                   8075: }
                   8076: 
1.103     harris41 8077: # ------------------------------------------------- Check for a user privilege
1.12      www      8078: 
                   8079: sub allowed {
1.1424    raeburn  8080:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 8081:     my $ver_orguri=$uri;
1.439     www      8082:     $uri=&deversion($uri);
1.152     www      8083:     my $orguri=$uri;
1.52      www      8084:     $uri=&declutter($uri);
1.809     raeburn  8085: 
1.810     raeburn  8086:     if ($priv eq 'evb') {
                   8087: # Evade communication block restrictions for specified role in a course
                   8088:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8089:             return $1;
                   8090:         } else {
                   8091:             return;
                   8092:         }
                   8093:     }
                   8094: 
1.620     albertel 8095:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8096: # Free bre access to adm and meta resources
1.1436    raeburn  8097:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8098: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8099: 	&& ($priv eq 'bre')) {
1.14      www      8100: 	return 'F';
1.159     www      8101:     }
                   8102: 
1.545     banghart 8103: # Free bre access to user's own portfolio contents
1.714     raeburn  8104:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8105:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8106: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8107:         my %setters;
                   8108:         my ($startblock,$endblock) = 
                   8109:             &Apache::loncommon::blockcheck(\%setters,'port');
                   8110:         if ($startblock && $endblock) {
                   8111:             return 'B';
                   8112:         } else {
                   8113:             return 'F';
                   8114:         }
1.545     banghart 8115:     }
                   8116: 
1.762     raeburn  8117: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8118:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8119:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8120:         if (exists($env{'request.course.id'})) {
                   8121:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8122:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8123:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8124:                 my $courseprivid=$env{'request.course.id'};
                   8125:                 $courseprivid=~s/\_/\//;
                   8126:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8127:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8128:                     return $1; 
1.762     raeburn  8129:                 } else {
                   8130:                     if ($env{'request.course.sec'}) {
                   8131:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8132:                     }
                   8133:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8134:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8135:                         return $2;
                   8136:                     }
1.714     raeburn  8137:                 }
                   8138:             }
                   8139:         }
                   8140:     }
                   8141: 
1.159     www      8142: # Free bre to public access
                   8143: 
                   8144:     if ($priv eq 'bre') {
1.1362    raeburn  8145:         my $copyright;
                   8146:         unless ($uri =~ /ext\.tool/) {
                   8147:             $copyright=&metadata($uri,'copyright');
                   8148:         }
1.620     albertel 8149: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8150:            return 'F'; 
                   8151:         }
1.238     www      8152:         if ($copyright eq 'priv') {
                   8153:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8154: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8155: 		return '';
                   8156:             }
                   8157:         }
                   8158:         if ($copyright eq 'domain') {
                   8159:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8160: 	    unless (($env{'user.domain'} eq $1) ||
                   8161:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8162: 		return '';
                   8163:             }
1.262     matthew  8164:         }
1.620     albertel 8165:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8166:             # Library role, so allow browsing of resources in this domain.
                   8167:             return 'F';
1.238     www      8168:         }
1.341     www      8169:         if ($copyright eq 'custom') {
                   8170: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8171:         }
1.14      www      8172:     }
1.264     matthew  8173:     # Domain coordinator is trying to create a course
1.620     albertel 8174:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8175:         # uri is the requested domain in this case.
                   8176:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8177:         # a role of dc for the domain in question.
1.620     albertel 8178:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8179:     }
1.29      www      8180: 
1.52      www      8181:     my $thisallowed='';
                   8182:     my $statecond=0;
                   8183:     my $courseprivid='';
                   8184: 
1.1039    raeburn  8185:     my $ownaccess;
1.1043    raeburn  8186:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8187:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8188:         if ($uri eq '') {
                   8189:             $ownaccess = 1;
                   8190:         } else {
                   8191:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8192:                 my $udom = $env{'user.domain'};
                   8193:                 my $uname = $env{'user.name'};
                   8194:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8195:                     $ownaccess = 1;
1.1040    raeburn  8196:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8197:                     unless ($uri =~ m{\.\./}) {
                   8198:                         $ownaccess = 1;
                   8199:                     }
                   8200:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8201:                     my $now = time;
                   8202:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8203:                         my $adom = $1;
                   8204:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8205:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  8206:                                 my ($start,$end) = split('.',$env{$key});
                   8207:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8208:                                     $ownaccess = 1;
                   8209:                                     last;
                   8210:                                 }
                   8211:                             }
                   8212:                         }
                   8213:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8214:                         my $adom = $1;
                   8215:                         my $aname = $2;
1.1042    raeburn  8216:                         foreach my $role ('ca','aa') { 
                   8217:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8218:                                 my ($start,$end) =
                   8219:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   8220:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8221:                                     $ownaccess = 1;
                   8222:                                     last;
                   8223:                                 }
1.1039    raeburn  8224:                             }
                   8225:                         }
                   8226:                     }
                   8227:                 }
                   8228:             }
                   8229:         }
                   8230:     }
                   8231: 
1.52      www      8232: # Course
                   8233: 
1.620     albertel 8234:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8235:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8236:             $thisallowed.=$1;
                   8237:         }
1.52      www      8238:     }
1.29      www      8239: 
1.52      www      8240: # Domain
                   8241: 
1.620     albertel 8242:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8243:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8244:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8245:             $thisallowed.=$1;
                   8246:         }
1.12      www      8247:     }
1.52      www      8248: 
1.1141    raeburn  8249: # User who is not author or co-author might still be able to edit
                   8250: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8251:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8252:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8253:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8254:             $thisallowed.=$1;
                   8255:         }
                   8256:     }
                   8257: 
1.52      www      8258: # Course: uri itself is a course
1.66      www      8259:     my $courseuri=$uri;
                   8260:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8261:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8262: 
1.620     albertel 8263:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8264:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8265:         if ($priv eq 'mip') {
                   8266:             my $rem = $1;
                   8267:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8268:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8269:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8270:                 if ($cdom ne '') {
1.1410    raeburn  8271:                     my %passwdconf = &get_passwdconf($cdom);
                   8272:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8273:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8274:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8275:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8276:                                 unless (@inststatuses) {
                   8277:                                     @inststatuses = ('default');
                   8278:                                 }
                   8279:                                 foreach my $status (@inststatuses) {
                   8280:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8281:                                         $thisallowed.=$rem;
                   8282:                                     }
                   8283:                                 }
                   8284:                             }
                   8285:                         }
1.1409    raeburn  8286:                     }
                   8287:                 }
                   8288:             }
                   8289:         } else {
                   8290:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8291:                 $thisallowed.=$1;
                   8292:             }
1.1039    raeburn  8293:         }
1.12      www      8294:     }
1.29      www      8295: 
1.665     albertel 8296: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8297: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8298:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8299: 	$thisallowed='';
1.671     raeburn  8300:         my ($match)=&is_on_map($uri);
                   8301:         if ($match) {
                   8302:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8303:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8304:                 my $value = $1;
1.1402    raeburn  8305:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8306:                 if ($deeplinkblock) {
                   8307:                     $thisallowed='D';
                   8308:                 } elsif ($noblockcheck) {
1.1281    raeburn  8309:                     $thisallowed.=$value;
1.1162    raeburn  8310:                 } else {
1.1424    raeburn  8311:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8312:                     if (@blockers > 0) {
                   8313:                         $thisallowed = 'B';
                   8314:                     } else {
                   8315:                         $thisallowed.=$value;
                   8316:                     }
1.1162    raeburn  8317:                 }
1.671     raeburn  8318:             }
                   8319:         } else {
1.705     albertel 8320:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8321:             if ($refuri) {
                   8322:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8323:                     $thisallowed='F';
1.671     raeburn  8324:                 } else {
                   8325:                     $refuri=&declutter($refuri);
                   8326:                     my ($match) = &is_on_map($refuri);
                   8327:                     if ($match) {
1.1402    raeburn  8328:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8329:                         if ($deeplinkblock) {
                   8330:                             $thisallowed='D';
                   8331:                         } elsif ($noblockcheck) {
1.1281    raeburn  8332:                             $thisallowed='F';
1.1162    raeburn  8333:                         } else {
1.1426    raeburn  8334:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8335:                             if (@blockers > 0) {
                   8336:                                 $thisallowed = 'B';
                   8337:                             } else {
                   8338:                                 $thisallowed='F';
                   8339:                             }
1.1162    raeburn  8340:                         }
1.671     raeburn  8341:                     }
1.669     raeburn  8342:                 }
1.671     raeburn  8343:             }
                   8344:         }
1.314     www      8345:     }
1.492     albertel 8346: 
1.766     albertel 8347:     if ($priv eq 'bre'
                   8348: 	&& $thisallowed ne 'F' 
                   8349: 	&& $thisallowed ne '2'
                   8350: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8351: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8352:     }
1.1250    raeburn  8353: 
1.52      www      8354: # Full access at system, domain or course-wide level? Exit.
1.29      www      8355:     if ($thisallowed=~/F/) {
                   8356: 	return 'F';
                   8357:     }
                   8358: 
1.52      www      8359: # If this is generating or modifying users, exit with special codes
1.29      www      8360: 
1.643     www      8361:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8362: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8363: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8364: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8365: 	    unless ($auname) { return $thisallowed; }
                   8366: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8367: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8368: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8369: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8370: 	}
1.52      www      8371: 	return $thisallowed;
                   8372:     }
                   8373: #
1.103     harris41 8374: # Gathered so far: system, domain and course wide privileges
1.52      www      8375: #
                   8376: # Course: See if uri or referer is an individual resource that is part of 
                   8377: # the course
                   8378: 
1.620     albertel 8379:     if ($env{'request.course.id'}) {
1.232     www      8380: 
1.1409    raeburn  8381: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8382: 
                   8383:         if ($priv eq 'mip') {
                   8384:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8385:                 return $thisallowed;
                   8386:             } else {
                   8387:                 return '';
                   8388:             }
                   8389:         }
                   8390: 
1.620     albertel 8391:        $courseprivid=$env{'request.course.id'};
                   8392:        if ($env{'request.course.sec'}) {
                   8393:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8394:        }
                   8395:        $courseprivid=~s/\_/\//;
                   8396:        my $checkreferer=1;
1.232     www      8397:        my ($match,$cond)=&is_on_map($uri);
                   8398:        if ($match) {
                   8399:            $statecond=$cond;
1.620     albertel 8400:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8401:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8402:                my $value = $1;
                   8403:                if ($priv eq 'bre') {
1.1281    raeburn  8404:                    if ($noblockcheck) {
                   8405:                        $thisallowed.=$value;
1.1162    raeburn  8406:                    } else {
1.1424    raeburn  8407:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8408:                        if (@blockers > 0) {
                   8409:                            $thisallowed = 'B';
                   8410:                        } else {
                   8411:                            $thisallowed.=$value;
                   8412:                        }
1.1162    raeburn  8413:                    }
                   8414:                } else {
                   8415:                    $thisallowed.=$value;
                   8416:                }
1.52      www      8417:                $checkreferer=0;
                   8418:            }
1.29      www      8419:        }
1.1424    raeburn  8420: 
1.148     www      8421:        if ($checkreferer) {
1.620     albertel 8422: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8423:             unless ($refuri) {
1.800     albertel 8424:                 foreach my $key (keys(%env)) {
                   8425: 		    if ($key=~/^httpref\..*\*/) {
                   8426: 			my $pattern=$key;
1.156     www      8427:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8428:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8429:                         $pattern=~s/\//\\\//g;
1.152     www      8430:                         if ($orguri=~/$pattern/) {
1.800     albertel 8431: 			    $refuri=$env{$key};
1.148     www      8432:                         }
                   8433:                     }
1.191     harris41 8434:                 }
1.148     www      8435:             }
1.232     www      8436: 
1.148     www      8437:          if ($refuri) { 
1.152     www      8438: 	  $refuri=&declutter($refuri);
1.232     www      8439:           my ($match,$cond)=&is_on_map($refuri);
                   8440:             if ($match) {
                   8441:               my $refstatecond=$cond;
1.620     albertel 8442:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8443:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8444:                   my $value = $1;
                   8445:                   if ($priv eq 'bre') {
1.1402    raeburn  8446:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8447:                       if ($deeplinkblock) {
                   8448:                           $thisallowed = 'D';
                   8449:                       } elsif ($noblockcheck) {
1.1281    raeburn  8450:                           $thisallowed.=$value;
1.1162    raeburn  8451:                       } else {
1.1426    raeburn  8452:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8453:                           if (@blockers > 0) {
                   8454:                               $thisallowed = 'B';
                   8455:                           } else {
                   8456:                               $thisallowed.=$value;
                   8457:                           }
1.1162    raeburn  8458:                       }
                   8459:                   } else {
                   8460:                       $thisallowed.=$value;
                   8461:                   }
1.53      www      8462:                   $uri=$refuri;
                   8463:                   $statecond=$refstatecond;
1.52      www      8464:               }
                   8465:           }
1.148     www      8466:         }
1.29      www      8467:        }
1.52      www      8468:    }
1.29      www      8469: 
1.52      www      8470: #
1.103     harris41 8471: # Gathered now: all privileges that could apply, and condition number
1.52      www      8472: # 
                   8473: #
                   8474: # Full or no access?
                   8475: #
1.29      www      8476: 
1.52      www      8477:     if ($thisallowed=~/F/) {
                   8478: 	return 'F';
                   8479:     }
1.29      www      8480: 
1.52      www      8481:     unless ($thisallowed) {
                   8482:         return '';
                   8483:     }
1.29      www      8484: 
1.52      www      8485: # Restrictions exist, deal with them
                   8486: #
                   8487: #   C:according to course preferences
                   8488: #   R:according to resource settings
                   8489: #   L:unless locked
                   8490: #   X:according to user session state
                   8491: #
                   8492: 
                   8493: # Possibly locked functionality, check all courses
1.54      www      8494: # Locks might take effect only after 10 minutes cache expiration for other
                   8495: # courses, and 2 minutes for current course
1.52      www      8496: 
                   8497:     my $envkey;
                   8498:     if ($thisallowed=~/L/) {
1.1000    raeburn  8499:         foreach $envkey (keys(%env)) {
1.54      www      8500:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8501:                my $courseid=$2;
                   8502:                my $roleid=$1.'.'.$2;
1.92      www      8503:                $courseid=~s/^\///;
1.54      www      8504:                my $expiretime=600;
1.620     albertel 8505:                if ($env{'request.role'} eq $roleid) {
1.54      www      8506: 		  $expiretime=120;
                   8507:                }
                   8508: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8509:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8510:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8511: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8512:                }
1.620     albertel 8513:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8514:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8515: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8516:                        &log($env{'user.domain'},$env{'user.name'},
                   8517:                             $env{'user.home'},
1.57      www      8518:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8519:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8520:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8521: 		       return '';
                   8522:                    }
                   8523:                }
1.620     albertel 8524:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8525:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8526: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8527:                        &log($env{'user.domain'},$env{'user.name'},
                   8528:                             $env{'user.home'},
1.57      www      8529:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8530:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8531:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8532: 		       return '';
                   8533:                    }
                   8534:                }
                   8535: 	   }
1.29      www      8536:        }
1.52      www      8537:     }
1.1424    raeburn  8538: 
1.52      www      8539: #
                   8540: # Rest of the restrictions depend on selected course
                   8541: #
                   8542: 
1.620     albertel 8543:     unless ($env{'request.course.id'}) {
1.766     albertel 8544: 	if ($thisallowed eq 'A') {
                   8545: 	    return 'A';
1.814     raeburn  8546:         } elsif ($thisallowed eq 'B') {
                   8547:             return 'B';
1.766     albertel 8548: 	} else {
                   8549: 	    return '1';
                   8550: 	}
1.52      www      8551:     }
1.29      www      8552: 
1.52      www      8553: #
                   8554: # Now user is definitely in a course
                   8555: #
1.53      www      8556: 
                   8557: 
                   8558: # Course preferences
                   8559: 
                   8560:    if ($thisallowed=~/C/) {
1.620     albertel 8561:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8562:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8563:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8564: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8565: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8566: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8567: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8568: 			$env{'request.course.id'});
                   8569: 	   }
1.237     www      8570:            return '';
                   8571:        }
                   8572: 
1.620     albertel 8573:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8574: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8575: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8576: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8577: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8578: 			$env{'request.course.id'});
                   8579: 	   }
1.54      www      8580:            return '';
                   8581:        }
1.53      www      8582:    }
                   8583: 
                   8584: # Resource preferences
                   8585: 
                   8586:    if ($thisallowed=~/R/) {
1.620     albertel 8587:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8588:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8589: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8590: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8591: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8592: 	   }
                   8593: 	   return '';
1.54      www      8594:        }
1.53      www      8595:    }
1.30      www      8596: 
1.246     www      8597: # Restricted by state or randomout?
1.30      www      8598: 
1.52      www      8599:    if ($thisallowed=~/X/) {
1.620     albertel 8600:       if ($env{'acc.randomout'}) {
1.579     albertel 8601: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8602:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8603:             return ''; 
                   8604:          }
1.247     www      8605:       }
                   8606:       if (&condval($statecond)) {
1.52      www      8607: 	 return '2';
                   8608:       } else {
                   8609:          return '';
                   8610:       }
                   8611:    }
1.30      www      8612: 
1.766     albertel 8613:     if ($thisallowed eq 'A') {
                   8614: 	return 'A';
1.814     raeburn  8615:     } elsif ($thisallowed eq 'B') {
                   8616:         return 'B';
1.1402    raeburn  8617:     } elsif ($thisallowed eq 'D') {
                   8618:         return 'D';
1.766     albertel 8619:     }
1.52      www      8620:    return 'F';
1.232     www      8621: }
1.1162    raeburn  8622: 
1.1192    raeburn  8623: # ------------------------------------------- Check construction space access
                   8624: 
                   8625: sub constructaccess {
                   8626:     my ($url,$setpriv)=@_;
                   8627: 
                   8628: # We do not allow editing of previous versions of files
                   8629:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8630: 
                   8631: # Get username and domain from URL
                   8632:     my ($ownername,$ownerdomain,$ownerhome);
                   8633: 
                   8634:     ($ownerdomain,$ownername) =
1.1325    raeburn  8635:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8636: 
                   8637: # The URL does not really point to any authorspace, forget it
                   8638:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8639: 
                   8640: # Now we need to see if the user has access to the authorspace of
                   8641: # $ownername at $ownerdomain
                   8642: 
                   8643:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8644: # Real author for this?
                   8645:        $ownerhome = $env{'user.home'};
                   8646:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8647:           return ($ownername,$ownerdomain,$ownerhome);
                   8648:        }
                   8649:     } else {
                   8650: # Co-author for this?
                   8651:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8652:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8653:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8654:             return ($ownername,$ownerdomain,$ownerhome);
                   8655:         }
1.1312    raeburn  8656:         if ($env{'request.course.id'}) {
                   8657:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8658:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8659:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8660:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8661:                     return ($ownername,$ownerdomain,$ownerhome);
                   8662:                 }
                   8663:             }
                   8664:         }
1.1192    raeburn  8665:     }
                   8666: 
                   8667: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8668: # we might as well leave
                   8669:    unless ($setpriv) { return ''; }
                   8670: 
                   8671: # Backdoor access?
                   8672:     my $allowed=&allowed('eco',$ownerdomain);
                   8673: # Nope
                   8674:     unless ($allowed) { return ''; }
                   8675: # Looks like we may have access, but could be locked by the owner of the construction space
                   8676:     if ($allowed eq 'U') {
                   8677:         my %blocked=&get('environment',['domcoord.author'],
                   8678:                          $ownerdomain,$ownername);
                   8679: # Is blocked by owner
                   8680:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8681:     }
                   8682:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8683: # Grant temporary access
                   8684:         my $then=$env{'user.login.time'};
1.1209    raeburn  8685:         my $update=$env{'user.update.time'};
1.1192    raeburn  8686:         if (!$update) { $update = $then; }
                   8687:         my $refresh=$env{'user.refresh.time'};
                   8688:         if (!$refresh) { $refresh = $update; }
                   8689:         my $now = time;
                   8690:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8691:                            $now,'ca','constructaccess');
                   8692:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8693:         return($ownername,$ownerdomain,$ownerhome);
                   8694:     }
                   8695: # No business here
                   8696:     return '';
                   8697: }
                   8698: 
1.1282    raeburn  8699: # ----------------------------------------------------------- Content Blocking
                   8700: 
                   8701: {
                   8702: # Caches for faster Course Contents display where content blocking
                   8703: # is in operation (i.e., interval param set) for timed quiz.
                   8704: #
                   8705: # User for whom data are being temporarily cached.
                   8706: my $cacheduser='';
1.1424    raeburn  8707: # Course for which data are being temporarily cached.
                   8708: my $cachedcid='';
1.1282    raeburn  8709: # Cached blockers for this user (a hash of blocking items). 
                   8710: my %cachedblockers=();
                   8711: # When the data were last cached.
                   8712: my $cachedlast='';
                   8713: 
                   8714: sub load_all_blockers {
1.1427    raeburn  8715:     my ($uname,$udom)=@_;
1.1282    raeburn  8716:     if (($uname ne '') && ($udom ne '')) { 
                   8717:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  8718:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  8719:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  8720:             return;
                   8721:         }
                   8722:     }
                   8723:     $cachedlast=time;
                   8724:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  8725:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  8726:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  8727:     return;
1.1282    raeburn  8728: }
                   8729: 
1.1162    raeburn  8730: sub get_comm_blocks {
                   8731:     my ($cdom,$cnum) = @_;
                   8732:     if ($cdom eq '' || $cnum eq '') {
                   8733:         return unless ($env{'request.course.id'});
                   8734:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8735:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8736:     }
                   8737:     my %commblocks;
                   8738:     my $hashid=$cdom.'_'.$cnum;
                   8739:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8740:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8741:         %commblocks = %{$blocksref};
                   8742:     } else {
                   8743:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8744:         my $cachetime = 600;
                   8745:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8746:     }
                   8747:     return %commblocks;
                   8748: }
                   8749: 
1.1282    raeburn  8750: sub get_commblock_resources {
                   8751:     my ($blocks) = @_;
                   8752:     my %blockers = ();
                   8753:     return %blockers unless ($env{'request.course.id'});
                   8754:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8755:     my %commblocks;
                   8756:     if (ref($blocks) eq 'HASH') {
                   8757:         %commblocks = %{$blocks};
                   8758:     } else {
                   8759:         %commblocks = &get_comm_blocks();
                   8760:     }
1.1282    raeburn  8761:     return %blockers unless (keys(%commblocks) > 0); 
                   8762:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8763:     return %blockers unless (ref($navmap));
1.1162    raeburn  8764:     my $now = time;
                   8765:     foreach my $block (keys(%commblocks)) {
                   8766:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8767:             my ($start,$end) = ($1,$2);
                   8768:             if ($start <= $now && $end >= $now) {
                   8769:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8770:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8771:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8772:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8773:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8774:                             }
                   8775:                         }
                   8776:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8777:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8778:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8779:                             }
                   8780:                         }
                   8781:                     }
                   8782:                 }
                   8783:             }
                   8784:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8785:             my $item = $1;
1.1163    raeburn  8786:             my @to_test;
1.1162    raeburn  8787:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8788:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8789:                     my @interval;
                   8790:                     my $type = 'map';
                   8791:                     if ($item eq 'course') {
                   8792:                         $type = 'course';
                   8793:                         @interval=&EXT("resource.0.interval");
                   8794:                     } else {
                   8795:                         if ($item =~ /___\d+___/) {
                   8796:                             $type = 'resource';
                   8797:                             @interval=&EXT("resource.0.interval",$item);
                   8798:                             if (ref($navmap)) {                        
                   8799:                                 my $res = $navmap->getBySymb($item); 
                   8800:                                 push(@to_test,$res);
                   8801:                             }
1.1162    raeburn  8802:                         } else {
1.1282    raeburn  8803:                             my $mapsymb = &symbread($item,1);
                   8804:                             if ($mapsymb) {
                   8805:                                 if (ref($navmap)) {
                   8806:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1428    raeburn  8807:                                     if (ref($mapres)) {
                   8808:                                         my $first = $mapres->map_start();
                   8809:                                         my $finish = $mapres->map_finish();
                   8810:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
1.1429    raeburn  8811:                                         if (ref($it)) {
                   8812:                                             my $res;
                   8813:                                             while ($res = $it->next(undef,1)) {
                   8814:                                                 next unless (ref($res));
                   8815:                                                 my $symb = $res->symb();
                   8816:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8817:                                                 @interval=&EXT("resource.0.interval",$symb);
                   8818:                                                 if ($interval[1] eq 'map') {
                   8819:                                                     if ($res->answerable()) {
                   8820:                                                         push(@to_test,$res);
                   8821:                                                         last;
                   8822:                                                     }
1.1428    raeburn  8823:                                                 }
1.1162    raeburn  8824:                                             }
                   8825:                                         }
                   8826:                                     }
                   8827:                                 }
                   8828:                             }
                   8829:                         }
1.1282    raeburn  8830:                     }
1.1310    raeburn  8831:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8832:                         my $timelimit = $1; 
1.1282    raeburn  8833:                         my $first_access;
                   8834:                         if ($type eq 'resource') {
                   8835:                             $first_access=&get_first_access($interval[1],$item);
                   8836:                         } elsif ($type eq 'map') {
                   8837:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8838:                         } else {
                   8839:                             $first_access=&get_first_access($interval[1]);
                   8840:                         }
                   8841:                         if ($first_access) {
1.1292    raeburn  8842:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8843:                             if ($timesup > $now) {
                   8844:                                 my $activeblock;
                   8845:                                 foreach my $res (@to_test) {
1.1283    raeburn  8846:                                     if ($res->answerable()) {
1.1282    raeburn  8847:                                         $activeblock = 1;
                   8848:                                         last;
                   8849:                                     }
                   8850:                                 }
                   8851:                                 if ($activeblock) {
                   8852:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8853:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8854:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8855:                                          }
                   8856:                                     }
                   8857:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8858:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8859:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8860:                                         }
1.1162    raeburn  8861:                                     }
                   8862:                                 }
                   8863:                             }
                   8864:                         }
                   8865:                     }
                   8866:                 }
                   8867:             }
                   8868:         }
                   8869:     }
1.1282    raeburn  8870:     return %blockers;
1.1162    raeburn  8871: }
                   8872: 
1.1282    raeburn  8873: sub has_comm_blocking {
1.1427    raeburn  8874:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  8875:     my @blockers;
                   8876:     return unless ($env{'request.course.id'});
                   8877:     return unless ($priv eq 'bre');
                   8878:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8879:     return if ($env{'request.state'} eq 'construct');
1.1427    raeburn  8880:     my %blockinfo;
                   8881:     if (ref($blocks) eq 'HASH') {
                   8882:         %blockinfo = &get_commblock_resources($blocks);
                   8883:     } else {
                   8884:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8885:         %blockinfo = %cachedblockers;
                   8886:     }
                   8887:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  8888:     my (%possibles,@symbs);
                   8889:     if (!$symb) {
1.1427    raeburn  8890:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8891:     }
1.1282    raeburn  8892:     if ($symb) {
                   8893:         @symbs = ($symb);
                   8894:     } elsif (keys(%possibles)) { 
                   8895:         @symbs = keys(%possibles);
                   8896:     }
                   8897:     my $noblock;
                   8898:     foreach my $symb (@symbs) {
                   8899:         last if ($noblock);
                   8900:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  8901:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  8902:             if ($block =~ /^firstaccess____(.+)$/) {
                   8903:                 my $item = $1;
1.1424    raeburn  8904:                 unless ($blocked) {
                   8905:                     if (($item eq $map) || ($item eq $symb)) {
                   8906:                         $noblock = 1;
                   8907:                         last;
                   8908:                     }
1.1282    raeburn  8909:                 }
                   8910:             }
1.1427    raeburn  8911:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8912:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8913:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  8914:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8915:                             push(@blockers,$block);
                   8916:                         }
                   8917:                     }
                   8918:                 }
1.1427    raeburn  8919:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8920:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  8921:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8922:                             push(@blockers,$block);
                   8923:                         }
1.1282    raeburn  8924:                     }
                   8925:                 }
1.1162    raeburn  8926:             }
                   8927:         }
                   8928:     }
1.1424    raeburn  8929:     unless ($noblock) { 
                   8930:         return @blockers;
                   8931:     }
                   8932:     return;
1.1282    raeburn  8933: }
1.1162    raeburn  8934: }
                   8935: 
1.1402    raeburn  8936: sub deeplink_check {
                   8937:     my ($priv,$symb,$uri) = @_;
                   8938:     return unless ($env{'request.course.id'});
                   8939:     return unless ($priv eq 'bre');
                   8940:     return if ($env{'request.state'} eq 'construct');
                   8941:     return if ($env{'request.role.adv'});
                   8942:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8943:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8944:     my (%possibles,@symbs);
                   8945:     if (!$symb) {
                   8946:         $symb = &symbread($uri,1,1,1,\%possibles);
                   8947:     }
                   8948:     if ($symb) {
                   8949:         @symbs = ($symb);
                   8950:     } elsif (keys(%possibles)) {
                   8951:         @symbs = keys(%possibles);
                   8952:     }
                   8953: 
                   8954:     my ($login,$switchrole,$allow);
                   8955:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   8956:         my $key = $1;
                   8957:         my $tinyurl;
                   8958:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   8959:         if (defined($cached)) {
                   8960:              $tinyurl = $result;
                   8961:         } else {
                   8962:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   8963:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   8964:              if ($currtiny{$key} ne '') {
                   8965:                  $tinyurl = $currtiny{$key};
                   8966:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   8967:              }
                   8968:         }
                   8969:         if ($tinyurl ne '') {
                   8970:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
                   8971:             if ($cnumreq eq $cnum) {
                   8972:                 $login = $posslogin;
                   8973:             } else {
                   8974:                 $switchrole = 1;
                   8975:             }
                   8976:         }
                   8977:     }
                   8978:     foreach my $symb (@symbs) {
                   8979:         last if ($allow);
                   8980:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8981:         if ($deeplink eq '') {
                   8982:             $allow = 1;
                   8983:         } else {
                   8984:             my ($listed,$scope,$access) = split(/,/,$deeplink);
                   8985:             if ($access eq 'any') {
                   8986:                 $allow = 1;
                   8987:             } elsif ($login) {
                   8988:                 if ($access eq 'only') {
                   8989:                     if ($scope eq 'res') {
                   8990:                         if ($symb eq $login) {
                   8991:                             $allow = 1;
                   8992:                         }
                   8993:                     } elsif ($scope eq 'map') {
                   8994: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
                   8995:                     } elsif ($scope eq 'rec') {
                   8996: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
                   8997:                     }
                   8998:                 } else {
                   8999:                     my ($acctype,$item) = split(/:/,$access);
                   9000:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
                   9001:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
                   9002:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   9003:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
                   9004:                                 $allow = 1;
                   9005:                             }
                   9006:                         }
                   9007:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9008:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9009:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   9010:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
                   9011:                                 $allow = 1;
                   9012:                             }
                   9013:                         }
                   9014:                     }
                   9015:                 }
                   9016:             }
                   9017:         }
                   9018:     }
                   9019:     return if ($allow);
                   9020:     return 1;
                   9021: }
                   9022: 
1.1282    raeburn  9023: # -------------------------------- Deversion and split uri into path an filename   
                   9024: 
1.1133    foxr     9025: #
1.1282    raeburn  9026: #   Removes the version from a URI and
1.1133    foxr     9027: #   splits it in to its filename and path to the filename.
                   9028: #   Seems like File::Basename could have done this more clearly.
                   9029: #   Parameters:
                   9030: #      $uri   - input URI
                   9031: #   Returns:
                   9032: #     Two element list consisting of 
                   9033: #     $pathname  - the URI up to and excluding the trailing /
                   9034: #     $filename  - The part of the URI following the last /
                   9035: #  NOTE:
                   9036: #    Another realization of this is simply:
                   9037: #    use File::Basename;
                   9038: #    ...
                   9039: #    $uri = shift;
                   9040: #    $filename = basename($uri);
                   9041: #    $path     = dirname($uri);
                   9042: #    return ($filename, $path);
                   9043: #
                   9044: #     The implementation below is probably faster however.
                   9045: #
1.710     albertel 9046: sub split_uri_for_cond {
                   9047:     my $uri=&deversion(&declutter(shift));
                   9048:     my @uriparts=split(/\//,$uri);
                   9049:     my $filename=pop(@uriparts);
                   9050:     my $pathname=join('/',@uriparts);
                   9051:     return ($pathname,$filename);
                   9052: }
1.232     www      9053: # --------------------------------------------------- Is a resource on the map?
                   9054: 
                   9055: sub is_on_map {
1.710     albertel 9056:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9057:     #Trying to find the conditional for the file
1.620     albertel 9058:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9059: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9060:     if ($match) {
1.289     bowersj2 9061: 	return (1,$1);
                   9062:     } else {
1.434     www      9063: 	return (0,0);
1.289     bowersj2 9064:     }
1.12      www      9065: }
                   9066: 
1.427     www      9067: # --------------------------------------------------------- Get symb from alias
                   9068: 
                   9069: sub get_symb_from_alias {
                   9070:     my $symb=shift;
                   9071:     my ($map,$resid,$url)=&decode_symb($symb);
                   9072: # Already is a symb
                   9073:     if ($url) { return $symb; }
                   9074: # Must be an alias
                   9075:     my $aliassymb='';
                   9076:     my %bighash;
1.620     albertel 9077:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9078:                             &GDBM_READER(),0640)) {
                   9079:         my $rid=$bighash{'mapalias_'.$symb};
                   9080: 	if ($rid) {
                   9081: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9082: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9083: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9084: 	}
                   9085:         untie %bighash;
                   9086:     }
                   9087:     return $aliassymb;
                   9088: }
                   9089: 
1.12      www      9090: # ----------------------------------------------------------------- Define Role
                   9091: 
                   9092: sub definerole {
                   9093:   if (allowed('mcr','/')) {
1.1326    raeburn  9094:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9095:     foreach my $role (split(':',$sysrole)) {
                   9096: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9097:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9098:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9099: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9100:                return "refused:s:$crole&$cqual"; 
                   9101:             }
                   9102:         }
1.191     harris41 9103:     }
1.800     albertel 9104:     foreach my $role (split(':',$domrole)) {
                   9105: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9106:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9107:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9108: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9109:                return "refused:d:$crole&$cqual"; 
                   9110:             }
                   9111:         }
1.191     harris41 9112:     }
1.800     albertel 9113:     foreach my $role (split(':',$courole)) {
                   9114: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9115:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9116:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9117: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9118:                return "refused:c:$crole&$cqual"; 
                   9119:             }
                   9120:         }
1.191     harris41 9121:     }
1.1326    raeburn  9122:     my $uhome;
                   9123:     if (($uname ne '') && ($udom ne '')) {
                   9124:         $uhome = &homeserver($uname,$udom);
                   9125:         return $uhome if ($uhome eq 'no_host');
                   9126:     } else {
                   9127:         $uname = $env{'user.name'};
                   9128:         $udom = $env{'user.domain'};
                   9129:         $uhome = $env{'user.home'};
                   9130:     }
1.620     albertel 9131:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9132:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9133:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9134:     return reply($command,$uhome);
1.12      www      9135:   } else {
                   9136:     return 'refused';
                   9137:   }
1.105     harris41 9138: }
                   9139: 
                   9140: # ---------------- Make a metadata query against the network of library servers
                   9141: 
                   9142: sub metadata_query {
1.1237    raeburn  9143:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9144:     my %rhash;
1.845     albertel 9145:     my %libserv = &all_library();
1.244     matthew  9146:     my @server_list = (defined($server_array) ? @$server_array
                   9147:                                               : keys(%libserv) );
                   9148:     for my $server (@server_list) {
1.1237    raeburn  9149:         my $domains = ''; 
                   9150:         if (ref($domains_hash) eq 'HASH') {
                   9151:             $domains = $domains_hash->{$server}; 
                   9152:         }
1.118     harris41 9153: 	unless ($custom or $customshow) {
1.1237    raeburn  9154: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9155: 	    $rhash{$server}=$reply;
                   9156: 	}
                   9157: 	else {
                   9158: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9159: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9160: 			     $server);
                   9161: 	    $rhash{$server}=$reply;
                   9162: 	}
1.112     harris41 9163:     }
1.118     harris41 9164:     return \%rhash;
1.240     www      9165: }
                   9166: 
                   9167: # ----------------------------------------- Send log queries and wait for reply
                   9168: 
                   9169: sub log_query {
                   9170:     my ($uname,$udom,$query,%filters)=@_;
                   9171:     my $uhome=&homeserver($uname,$udom);
                   9172:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9173:     my $uhost=&hostname($uhome);
1.800     albertel 9174:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9175:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9176:                        $uhome);
1.479     albertel 9177:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9178:     return get_query_reply($queryid);
                   9179: }
                   9180: 
1.818     raeburn  9181: # -------------------------- Update MySQL table for portfolio file
                   9182: 
                   9183: sub update_portfolio_table {
1.821     raeburn  9184:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9185:     if ($group ne '') {
                   9186:         $file_name =~s /^\Q$group\E//;
                   9187:     }
1.818     raeburn  9188:     my $homeserver = &homeserver($uname,$udom);
                   9189:     my $queryid=
1.821     raeburn  9190:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9191:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9192:     my $reply = &get_query_reply($queryid);
                   9193:     return $reply;
                   9194: }
                   9195: 
1.899     raeburn  9196: # -------------------------- Update MySQL allusers table
                   9197: 
                   9198: sub update_allusers_table {
                   9199:     my ($uname,$udom,$names) = @_;
                   9200:     my $homeserver = &homeserver($uname,$udom);
                   9201:     my $queryid=
                   9202:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9203:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9204:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9205:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9206:                'generation='.&escape($names->{'generation'}).'%%'.
                   9207:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9208:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9209:     return;
1.899     raeburn  9210: }
                   9211: 
1.508     raeburn  9212: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9213: 
                   9214: sub fetch_enrollment_query {
1.511     raeburn  9215:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9216:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9217:     my $maxtries = 1;
1.508     raeburn  9218:     if ($context eq 'automated') {
                   9219:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9220:         $sleep = 2;
                   9221:         $loopmax = 100;
1.547     raeburn  9222:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9223:     } else {
                   9224:         $homeserver = &homeserver($cnum,$dom);
                   9225:     }
1.838     albertel 9226:     my $host=&hostname($homeserver);
1.506     raeburn  9227:     my $cmd = '';
1.1000    raeburn  9228:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9229:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9230:     }
                   9231:     $cmd =~ s/%%$//;
                   9232:     $cmd = &escape($cmd);
                   9233:     my $query = 'fetchenrollment';
1.620     albertel 9234:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9235:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9236:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9237:         return 'error: '.$queryid;
                   9238:     }
1.1317    raeburn  9239:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9240:     my $tries = 1;
                   9241:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9242:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9243:         $tries ++;
                   9244:     }
1.526     raeburn  9245:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9246:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9247:     } else {
1.901     albertel 9248:         my @responses = split(/:/,$reply);
1.1322    raeburn  9249:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9250:             foreach my $line (@responses) {
                   9251:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9252:                 $$replyref{$key} = $value;
                   9253:             }
                   9254:         } else {
1.1117    foxr     9255:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9256:             foreach my $line (@responses) {
                   9257:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9258:                 $$replyref{$key} = $value;
                   9259:                 if ($value > 0) {
1.800     albertel 9260:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9261:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9262:                         my $destname = $pathname.'/'.$filename;
                   9263:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9264:                         if ($xml_classlist =~ /^error/) {
                   9265:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9266:                         } else {
1.1359    raeburn  9267:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9268:                                 print FILE &unescape($xml_classlist);
                   9269:                                 close(FILE);
1.526     raeburn  9270:                             } else {
                   9271:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9272:                             }
                   9273:                         }
                   9274:                     }
                   9275:                 }
                   9276:             }
                   9277:         }
                   9278:         return 'ok';
                   9279:     }
                   9280:     return 'error';
                   9281: }
                   9282: 
1.242     www      9283: sub get_query_reply {
1.1317    raeburn  9284:     my ($queryid,$sleep,$loopmax) = @_;;
                   9285:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9286:         $sleep = 0.2;
                   9287:     }
                   9288:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9289:         $loopmax = 100;
                   9290:     }
1.1117    foxr     9291:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9292:     my $reply='';
1.1317    raeburn  9293:     for (1..$loopmax) {
                   9294: 	sleep($sleep);
1.240     www      9295:         if (-e $replyfile.'.end') {
1.1359    raeburn  9296: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9297: 		$reply = join('',<$fh>);
                   9298: 		close($fh);
1.240     www      9299: 	   } else { return 'error: reply_file_error'; }
1.242     www      9300:            return &unescape($reply);
                   9301: 	}
1.240     www      9302:     }
1.242     www      9303:     return 'timeout:'.$queryid;
1.240     www      9304: }
                   9305: 
                   9306: sub courselog_query {
1.241     www      9307: #
                   9308: # possible filters:
                   9309: # url: url or symb
                   9310: # username
                   9311: # domain
                   9312: # action: view, submit, grade
                   9313: # start: timestamp
                   9314: # end: timestamp
                   9315: #
1.240     www      9316:     my (%filters)=@_;
1.620     albertel 9317:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9318:     if ($filters{'url'}) {
                   9319: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9320:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9321:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9322:     }
1.620     albertel 9323:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9324:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9325:     return &log_query($cname,$cdom,'courselog',%filters);
                   9326: }
                   9327: 
                   9328: sub userlog_query {
1.858     raeburn  9329: #
                   9330: # possible filters:
                   9331: # action: log check role
                   9332: # start: timestamp
                   9333: # end: timestamp
                   9334: #
1.240     www      9335:     my ($uname,$udom,%filters)=@_;
                   9336:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9337: }
                   9338: 
1.506     raeburn  9339: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9340: 
                   9341: sub auto_run {
1.508     raeburn  9342:     my ($cnum,$cdom) = @_;
1.876     raeburn  9343:     my $response = 0;
                   9344:     my $settings;
                   9345:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9346:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9347:         $settings = $domconfig{'autoenroll'};
                   9348:         if ($settings->{'run'} eq '1') {
                   9349:             $response = 1;
                   9350:         }
                   9351:     } else {
1.934     raeburn  9352:         my $homeserver;
                   9353:         if (&is_course($cdom,$cnum)) {
                   9354:             $homeserver = &homeserver($cnum,$cdom);
                   9355:         } else {
                   9356:             $homeserver = &domain($cdom,'primary');
                   9357:         }
                   9358:         if ($homeserver ne 'no_host') {
                   9359:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9360:         }
1.876     raeburn  9361:     }
1.506     raeburn  9362:     return $response;
                   9363: }
1.776     albertel 9364: 
1.506     raeburn  9365: sub auto_get_sections {
1.508     raeburn  9366:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9367:     my $homeserver;
                   9368:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9369:         $homeserver = &homeserver($cnum,$cdom);
                   9370:     }
                   9371:     if (!defined($homeserver)) { 
                   9372:         if ($cdom =~ /^$match_domain$/) {
                   9373:             $homeserver = &domain($cdom,'primary');
                   9374:         }
                   9375:     }
                   9376:     my @secs;
                   9377:     if (defined($homeserver)) {
                   9378:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9379:         unless ($response eq 'refused') {
                   9380:             @secs = split(/:/,$response);
                   9381:         }
1.506     raeburn  9382:     }
                   9383:     return @secs;
                   9384: }
1.776     albertel 9385: 
1.506     raeburn  9386: sub auto_new_course {
1.1099    raeburn  9387:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9388:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9389:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9390:     return $response;
                   9391: }
1.776     albertel 9392: 
1.506     raeburn  9393: sub auto_validate_courseID {
1.508     raeburn  9394:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9395:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9396:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9397:     return $response;
                   9398: }
1.776     albertel 9399: 
1.1007    raeburn  9400: sub auto_validate_instcode {
1.1020    raeburn  9401:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9402:     my ($homeserver,$response);
                   9403:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9404:         $homeserver = &homeserver($cnum,$cdom);
                   9405:     }
                   9406:     if (!defined($homeserver)) {
                   9407:         if ($cdom =~ /^$match_domain$/) {
                   9408:             $homeserver = &domain($cdom,'primary');
                   9409:         }
                   9410:     }
1.1065    raeburn  9411:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9412:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9413:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9414:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9415: }
                   9416: 
1.506     raeburn  9417: sub auto_create_password {
1.873     raeburn  9418:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9419:     my ($homeserver,$response);
1.506     raeburn  9420:     my $create_passwd = 0;
                   9421:     my $authchk = '';
1.873     raeburn  9422:     if ($udom =~ /^$match_domain$/) {
                   9423:         $homeserver = &domain($udom,'primary');
                   9424:     }
                   9425:     if ($homeserver eq '') {
                   9426:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9427:             $homeserver = &homeserver($cnum,$cdom);
                   9428:         }
                   9429:     }
                   9430:     if ($homeserver eq '') {
                   9431:         $authchk = 'nodomain';
1.506     raeburn  9432:     } else {
1.873     raeburn  9433:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9434:         if ($response eq 'refused') {
                   9435:             $authchk = 'refused';
                   9436:         } else {
1.901     albertel 9437:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9438:         }
1.506     raeburn  9439:     }
                   9440:     return ($authparam,$create_passwd,$authchk);
                   9441: }
                   9442: 
1.706     raeburn  9443: sub auto_photo_permission {
                   9444:     my ($cnum,$cdom,$students) = @_;
                   9445:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9446:     my ($outcome,$perm_reqd,$conditions) = 
                   9447: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9448:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9449: 	return (undef,undef);
                   9450:     }
1.706     raeburn  9451:     return ($outcome,$perm_reqd,$conditions);
                   9452: }
                   9453: 
                   9454: sub auto_checkphotos {
                   9455:     my ($uname,$udom,$pid) = @_;
                   9456:     my $homeserver = &homeserver($uname,$udom);
                   9457:     my ($result,$resulttype);
                   9458:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9459: 				   &escape($uname).':'.&escape($pid),
                   9460: 				   $homeserver));
1.709     albertel 9461:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9462: 	return (undef,undef);
                   9463:     }
1.706     raeburn  9464:     if ($outcome) {
                   9465:         ($result,$resulttype) = split(/:/,$outcome);
                   9466:     } 
                   9467:     return ($result,$resulttype);
                   9468: }
                   9469: 
                   9470: sub auto_photochoice {
                   9471:     my ($cnum,$cdom) = @_;
                   9472:     my $homeserver = &homeserver($cnum,$cdom);
                   9473:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9474: 						       &escape($cdom),
                   9475: 						       $homeserver)));
1.709     albertel 9476:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9477: 	return (undef,undef);
                   9478:     }
1.706     raeburn  9479:     return ($update,$comment);
                   9480: }
                   9481: 
                   9482: sub auto_photoupdate {
                   9483:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9484:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9485:     my $host=&hostname($homeserver);
1.706     raeburn  9486:     my $cmd = '';
                   9487:     my $maxtries = 1;
1.800     albertel 9488:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9489:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9490:     }
                   9491:     $cmd =~ s/%%$//;
                   9492:     $cmd = &escape($cmd);
                   9493:     my $query = 'institutionalphotos';
                   9494:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9495:     unless ($queryid=~/^\Q$host\E\_/) {
                   9496:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9497:         return 'error: '.$queryid;
                   9498:     }
                   9499:     my $reply = &get_query_reply($queryid);
                   9500:     my $tries = 1;
                   9501:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9502:         $reply = &get_query_reply($queryid);
                   9503:         $tries ++;
                   9504:     }
                   9505:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9506:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9507:     } else {
                   9508:         my @responses = split(/:/,$reply);
                   9509:         my $outcome = shift(@responses); 
                   9510:         foreach my $item (@responses) {
                   9511:             my ($key,$value) = split(/=/,$item);
                   9512:             $$photo{$key} = $value;
                   9513:         }
                   9514:         return $outcome;
                   9515:     }
                   9516:     return 'error';
                   9517: }
                   9518: 
1.521     raeburn  9519: sub auto_instcode_format {
1.793     albertel 9520:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9521: 	$cat_order) = @_;
1.521     raeburn  9522:     my $courses = '';
1.772     raeburn  9523:     my @homeservers;
1.521     raeburn  9524:     if ($caller eq 'global') {
1.841     albertel 9525: 	my %servers = &get_servers($codedom,'library');
                   9526: 	foreach my $tryserver (keys(%servers)) {
                   9527: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9528: 		push(@homeservers,$tryserver);
                   9529: 	    }
1.584     raeburn  9530:         }
1.1022    raeburn  9531:     } elsif ($caller eq 'requests') {
                   9532:         if ($codedom =~ /^$match_domain$/) {
                   9533:             my $chome = &domain($codedom,'primary');
                   9534:             unless ($chome eq 'no_host') {
                   9535:                 push(@homeservers,$chome);
                   9536:             }
                   9537:         }
1.521     raeburn  9538:     } else {
1.772     raeburn  9539:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9540:     }
1.793     albertel 9541:     foreach my $code (keys(%{$instcodes})) {
                   9542:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9543:     }
                   9544:     chop($courses);
1.772     raeburn  9545:     my $ok_response = 0;
                   9546:     my $response;
                   9547:     while (@homeservers > 0 && $ok_response == 0) {
                   9548:         my $server = shift(@homeservers); 
                   9549:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9550:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9551:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9552: 		split(/:/,$response);
1.772     raeburn  9553:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9554:             push(@{$codetitles},&str2array($codetitles_str));
                   9555:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9556:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9557:             $ok_response = 1;
                   9558:         }
                   9559:     }
                   9560:     if ($ok_response) {
1.521     raeburn  9561:         return 'ok';
1.772     raeburn  9562:     } else {
                   9563:         return $response;
1.521     raeburn  9564:     }
                   9565: }
                   9566: 
1.792     raeburn  9567: sub auto_instcode_defaults {
                   9568:     my ($domain,$returnhash,$code_order) = @_;
                   9569:     my @homeservers;
1.841     albertel 9570: 
                   9571:     my %servers = &get_servers($domain,'library');
                   9572:     foreach my $tryserver (keys(%servers)) {
                   9573: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9574: 	    push(@homeservers,$tryserver);
                   9575: 	}
1.792     raeburn  9576:     }
1.841     albertel 9577: 
1.792     raeburn  9578:     my $response;
1.841     albertel 9579:     foreach my $server (@homeservers) {
1.792     raeburn  9580:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9581:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9582: 	
                   9583: 	foreach my $pair (split(/\&/,$response)) {
                   9584: 	    my ($name,$value)=split(/\=/,$pair);
                   9585: 	    if ($name eq 'code_order') {
                   9586: 		@{$code_order} = split(/\&/,&unescape($value));
                   9587: 	    } else {
                   9588: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9589: 	    }
                   9590: 	}
                   9591: 	return 'ok';
1.792     raeburn  9592:     }
1.841     albertel 9593: 
                   9594:     return $response;
1.1003    raeburn  9595: }
                   9596: 
                   9597: sub auto_possible_instcodes {
1.1007    raeburn  9598:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9599:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9600:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9601:         return;
                   9602:     }
1.1003    raeburn  9603:     my (@homeservers,$uhome);
                   9604:     if (defined(&domain($domain,'primary'))) {
                   9605:         $uhome=&domain($domain,'primary');
                   9606:         push(@homeservers,&domain($domain,'primary'));
                   9607:     } else {
                   9608:         my %servers = &get_servers($domain,'library');
                   9609:         foreach my $tryserver (keys(%servers)) {
                   9610:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9611:                 push(@homeservers,$tryserver);
                   9612:             }
                   9613:         }
                   9614:     }
                   9615:     my $response;
                   9616:     foreach my $server (@homeservers) {
                   9617:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9618:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9619:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9620:             split(':',$response);
                   9621:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9622:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9623:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9624:             my ($name,$value)=split('=',$item);
                   9625:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9626:         }
                   9627:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9628:             my ($name,$value)=split('=',$item);
                   9629:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9630:         }
                   9631:         return 'ok';
                   9632:     }
                   9633:     return $response;
                   9634: }
1.792     raeburn  9635: 
1.1010    raeburn  9636: sub auto_courserequest_checks {
                   9637:     my ($dom) = @_;
1.1020    raeburn  9638:     my ($homeserver,%validations);
                   9639:     if ($dom =~ /^$match_domain$/) {
                   9640:         $homeserver = &domain($dom,'primary');
                   9641:     }
                   9642:     unless ($homeserver eq 'no_host') {
                   9643:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9644:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9645:             my @items = split(/&/,$response);
                   9646:             foreach my $item (@items) {
                   9647:                 my ($key,$value) = split('=',$item);
                   9648:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9649:             }
                   9650:         }
                   9651:     }
1.1010    raeburn  9652:     return %validations; 
                   9653: }
                   9654: 
1.1020    raeburn  9655: sub auto_courserequest_validation {
1.1255    raeburn  9656:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9657:     my ($homeserver,$response);
                   9658:     if ($dom =~ /^$match_domain$/) {
                   9659:         $homeserver = &domain($dom,'primary');
                   9660:     }
1.1255    raeburn  9661:     unless ($homeserver eq 'no_host') {
                   9662:         my $customdata;
                   9663:         if (ref($custominfo) eq 'HASH') {
                   9664:             $customdata = &freeze_escape($custominfo);
                   9665:         }
1.1020    raeburn  9666:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9667:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9668:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9669:                                     $customdata,$homeserver));
1.1020    raeburn  9670:     }
                   9671:     return $response;
                   9672: }
                   9673: 
1.777     albertel 9674: sub auto_validate_class_sec {
1.918     raeburn  9675:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9676:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9677:     my $ownerlist;
                   9678:     if (ref($owners) eq 'ARRAY') {
                   9679:         $ownerlist = join(',',@{$owners});
                   9680:     } else {
                   9681:         $ownerlist = $owners;
                   9682:     }
1.773     raeburn  9683:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9684:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9685:     return $response;
                   9686: }
                   9687: 
1.1367    raeburn  9688: sub auto_validate_instclasses {
                   9689:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9690:     my ($homeserver,%validations);
                   9691:     $homeserver = &homeserver($cnum,$cdom);
                   9692:     unless ($homeserver eq 'no_host') {
                   9693:         my $ownerlist;
                   9694:         if (ref($owners) eq 'ARRAY') {
                   9695:             $ownerlist = join(',',@{$owners});
                   9696:         } else {
                   9697:             $ownerlist = $owners;
                   9698:         }
                   9699:         if (ref($classesref) eq 'HASH') {
                   9700:             my $classes = &freeze_escape($classesref);
                   9701:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9702:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9703:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9704:                 my @items = split(/&/,$response);
                   9705:                 foreach my $item (@items) {
                   9706:                     my ($key,$value) = split('=',$item);
                   9707:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9708:                 }
                   9709:             }
                   9710:         }
                   9711:     }
                   9712:     return %validations;
                   9713: }
                   9714: 
1.1248    raeburn  9715: sub auto_crsreq_update {
                   9716:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9717:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9718:     my ($homeserver,%crsreqresponse);
                   9719:     if ($cdom =~ /^$match_domain$/) {
                   9720:         $homeserver = &domain($cdom,'primary');
                   9721:     }
                   9722:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9723:         my $info;
                   9724:         if (ref($inbound) eq 'HASH') {
                   9725:             $info = &freeze_escape($inbound);
                   9726:         }
                   9727:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9728:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9729:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9730:                             &escape($title).':'.&escape($code).':'.
                   9731:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9732:                             $homeserver);
1.1248    raeburn  9733:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9734:             my @items = split(/&/,$response);
                   9735:             foreach my $item (@items) {
                   9736:                 my ($key,$value) = split('=',$item);
                   9737:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9738:             }
                   9739:         }
                   9740:     }
                   9741:     return \%crsreqresponse;
                   9742: }
                   9743: 
1.1305    raeburn  9744: sub auto_export_grades {
1.1309    raeburn  9745:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9746:     my ($homeserver,%exportresponse);
                   9747:     if ($cdom =~ /^$match_domain$/) {
                   9748:         $homeserver = &domain($cdom,'primary');
                   9749:     }
                   9750:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9751:         my $info;
                   9752:         if (ref($inforef) eq 'HASH') {
                   9753:             $info = &freeze_escape($inforef);
                   9754:         }
                   9755:         if (ref($gradesref) eq 'HASH') {
                   9756:             my $grades = &freeze_escape($gradesref);
                   9757:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9758:                                 $info.':'.$grades,$homeserver);
                   9759:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9760:                 my @items = split(/&/,$response);
                   9761:                 foreach my $item (@items) {
                   9762:                     my ($key,$value) = split('=',$item);
                   9763:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9764:                 }
                   9765:             }
                   9766:         }
                   9767:     }
                   9768:     return \%exportresponse;
1.1305    raeburn  9769: }
                   9770: 
1.1287    raeburn  9771: sub check_instcode_cloning {
                   9772:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9773:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9774:         return;
                   9775:     }
                   9776:     my $canclone;
                   9777:     if (@{$code_order} > 0) {
                   9778:         my $instcoderegexp ='^';
                   9779:         my @clonecodes = split(/\&/,$cloner);
                   9780:         foreach my $item (@{$code_order}) {
                   9781:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9782:                 foreach my $pair (@clonecodes) {
                   9783:                     my ($key,$val) = split(/\=/,$pair,2);
                   9784:                     $val = &unescape($val);
                   9785:                     if ($key eq $item) {
                   9786:                         $instcoderegexp .= '('.$val.')';
                   9787:                         last;
                   9788:                     }
                   9789:                 }
                   9790:             } else {
                   9791:                 $instcoderegexp .= $codedefaults->{$item};
                   9792:             }
                   9793:         }
                   9794:         $instcoderegexp .= '$';
                   9795:         my (@from,@to);
                   9796:         eval {
                   9797:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9798:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9799:         };
                   9800:         if ((@from > 0) && (@to > 0)) {
                   9801:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9802:             if (!@diffs) {
                   9803:                 $canclone = 1;
                   9804:             }
                   9805:         }
                   9806:     }
                   9807:     return $canclone;
                   9808: }
                   9809: 
                   9810: sub default_instcode_cloning {
                   9811:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9812:     my (%codedefaults,@code_order,$canclone);
                   9813:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9814:         %codedefaults = %{$codedefaultsref};
                   9815:         @code_order = @{$codeorderref};
                   9816:     } elsif ($clonedom) {
                   9817:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9818:     }
                   9819:     if (($domdefclone) && (@code_order)) {
                   9820:         my @clonecodes = split(/\+/,$domdefclone);
                   9821:         my $instcoderegexp ='^';
                   9822:         foreach my $item (@code_order) {
                   9823:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9824:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9825:             } else {
                   9826:                 $instcoderegexp .= $codedefaults{$item};
                   9827:             }
                   9828:         }
                   9829:         $instcoderegexp .= '$';
                   9830:         my (@from,@to);
                   9831:         eval {
                   9832:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9833:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9834:         };
                   9835:         if ((@from > 0) && (@to > 0)) {
                   9836:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9837:             if (!@diffs) {
                   9838:                 $canclone = 1;
                   9839:             }
                   9840:         }
                   9841:     }
                   9842:     return $canclone;
                   9843: }
                   9844: 
1.679     raeburn  9845: # ------------------------------------------------------- Course Group routines
                   9846: 
                   9847: sub get_coursegroups {
1.809     raeburn  9848:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9849:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9850: }
                   9851: 
1.679     raeburn  9852: sub modify_coursegroup {
                   9853:     my ($cdom,$cnum,$groupsettings) = @_;
                   9854:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9855: }
                   9856: 
1.809     raeburn  9857: sub toggle_coursegroup_status {
                   9858:     my ($cdom,$cnum,$group,$action) = @_;
                   9859:     my ($from_namespace,$to_namespace);
                   9860:     if ($action eq 'delete') {
                   9861:         $from_namespace = 'coursegroups';
                   9862:         $to_namespace = 'deleted_groups';
                   9863:     } else {
                   9864:         $from_namespace = 'deleted_groups';
                   9865:         $to_namespace = 'coursegroups';
                   9866:     }
                   9867:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9868:     if (my $tmp = &error(%curr_group)) {
                   9869:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9870:         return ('read error',$tmp);
                   9871:     } else {
                   9872:         my %savedsettings = %curr_group; 
1.809     raeburn  9873:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9874:         my $deloutcome;
                   9875:         if ($result eq 'ok') {
1.809     raeburn  9876:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9877:         } else {
                   9878:             return ('write error',$result);
                   9879:         }
                   9880:         if ($deloutcome eq 'ok') {
                   9881:             return 'ok';
                   9882:         } else {
                   9883:             return ('delete error',$deloutcome);
                   9884:         }
                   9885:     }
                   9886: }
                   9887: 
1.679     raeburn  9888: sub modify_group_roles {
1.957     raeburn  9889:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9890:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9891:     my $role = 'gr/'.&escape($userprivs);
                   9892:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9893:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9894:     if ($result eq 'ok') {
                   9895:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9896:     }
1.679     raeburn  9897:     return $result;
                   9898: }
                   9899: 
                   9900: sub modify_coursegroup_membership {
                   9901:     my ($cdom,$cnum,$membership) = @_;
                   9902:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9903:     return $result;
                   9904: }
                   9905: 
1.682     raeburn  9906: sub get_active_groups {
                   9907:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9908:     my $now = time;
                   9909:     my %groups = ();
                   9910:     foreach my $key (keys(%env)) {
1.811     albertel 9911:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9912:             my ($start,$end) = split(/\./,$env{$key});
                   9913:             if (($end!=0) && ($end<$now)) { next; }
                   9914:             if (($start!=0) && ($start>$now)) { next; }
                   9915:             if ($1 eq $cdom && $2 eq $cnum) {
                   9916:                 $groups{$3} = $env{$key} ;
                   9917:             }
                   9918:         }
                   9919:     }
                   9920:     return %groups;
                   9921: }
                   9922: 
1.683     raeburn  9923: sub get_group_membership {
                   9924:     my ($cdom,$cnum,$group) = @_;
                   9925:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9926: }
                   9927: 
                   9928: sub get_users_groups {
                   9929:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9930:     my @usersgroups;
1.683     raeburn  9931:     my $cachetime=1800;
                   9932: 
                   9933:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9934:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9935:     if (defined($cached)) {
1.734     albertel 9936:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9937:     } else {  
                   9938:         $grouplist = '';
1.816     raeburn  9939:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9940:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9941:         my $access_end = $env{'course.'.$courseid.
                   9942:                               '.default_enrollment_end_date'};
                   9943:         my $now = time;
                   9944:         foreach my $key (keys(%roleshash)) {
                   9945:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9946:                 my $group = $1;
                   9947:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9948:                     my $start = $2;
                   9949:                     my $end = $1;
                   9950:                     if ($start == -1) { next; } # deleted from group
                   9951:                     if (($start!=0) && ($start>$now)) { next; }
                   9952:                     if (($end!=0) && ($end<$now)) {
                   9953:                         if ($access_end && $access_end < $now) {
                   9954:                             if ($access_end - $end < 86400) {
                   9955:                                 push(@usersgroups,$group);
1.733     raeburn  9956:                             }
                   9957:                         }
1.817     raeburn  9958:                         next;
1.733     raeburn  9959:                     }
1.817     raeburn  9960:                     push(@usersgroups,$group);
1.683     raeburn  9961:                 }
                   9962:             }
                   9963:         }
1.817     raeburn  9964:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9965:         $grouplist = join(':',@usersgroups);
                   9966:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9967:     }
1.733     raeburn  9968:     return @usersgroups;
1.683     raeburn  9969: }
                   9970: 
                   9971: sub devalidate_getgroups_cache {
                   9972:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9973:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9974: 
1.683     raeburn  9975:     my $hashid="$udom:$uname:$courseid";
                   9976:     &devalidate_cache_new('getgroups',$hashid);
                   9977: }
                   9978: 
1.12      www      9979: # ------------------------------------------------------------------ Plain Text
                   9980: 
                   9981: sub plaintext {
1.988     raeburn  9982:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9983:     if ($short =~ m{^cr/}) {
1.758     albertel 9984: 	return (split('/',$short))[-1];
                   9985:     }
1.742     raeburn  9986:     if (!defined($cid)) {
                   9987:         $cid = $env{'request.course.id'};
                   9988:     }
                   9989:     my %rolenames = (
1.1008    raeburn  9990:                       Course    => 'std',
                   9991:                       Community => 'alt1',
1.1305    raeburn  9992:                       Placement => 'std',
1.742     raeburn  9993:                     );
1.1037    raeburn  9994:     if ($cid ne '') {
                   9995:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9996:             unless ($forcedefault) {
                   9997:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9998:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9999:                 return &Apache::lonlocal::mt($roletext);
                   10000:             }
                   10001:         }
                   10002:     }
                   10003:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10004:         (defined($rolenames{$type})) && 
                   10005:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10006:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10007:     } elsif ($cid ne '') {
                   10008:         my $crstype = $env{'course.'.$cid.'.type'};
                   10009:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10010:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10011:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10012:         }
1.742     raeburn  10013:     }
1.1037    raeburn  10014:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10015: }
                   10016: 
                   10017: # ----------------------------------------------------------------- Assign Role
                   10018: 
                   10019: sub assignrole {
1.957     raeburn  10020:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10021:         $context)=@_;
1.21      www      10022:     my $mrole;
                   10023:     if ($role =~ /^cr\//) {
1.393     www      10024:         my $cwosec=$url;
1.811     albertel 10025:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10026: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10027:            my $refused = 1;
                   10028:            if ($context eq 'requestcourses') {
                   10029:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10030:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10031:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10032:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10033:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10034:                            if ($crsenv{'internal.courseowner'} eq
                   10035:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10036:                                $refused = '';
                   10037:                            }
                   10038:                        }
                   10039:                    }
                   10040:                }
                   10041:            }
                   10042:            if ($refused) {
                   10043:                &logthis('Refused custom assignrole: '.
                   10044:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10045:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10046:                return 'refused';
                   10047:            }
1.104     www      10048:         }
1.21      www      10049:         $mrole='cr';
1.678     raeburn  10050:     } elsif ($role =~ /^gr\//) {
                   10051:         my $cwogrp=$url;
1.811     albertel 10052:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10053:         unless (&allowed('mdg',$cwogrp)) {
                   10054:             &logthis('Refused group assignrole: '.
                   10055:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10056:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10057:             return 'refused';
                   10058:         }
                   10059:         $mrole='gr';
1.21      www      10060:     } else {
1.82      www      10061:         my $cwosec=$url;
1.811     albertel 10062:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10063:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10064:             my $refused;
                   10065:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10066:                 if (!(&allowed('c'.$role,$url))) {
                   10067:                     $refused = 1;
                   10068:                 }
                   10069:             } else {
                   10070:                 $refused = 1;
                   10071:             }
1.947     raeburn  10072:             if ($refused) {
1.1045    raeburn  10073:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  10074:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10075:                     my %crsenv;
                   10076:                     if ($role eq 'cc' || $role eq 'co') {
                   10077:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10078:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10079:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10080:                                 if ($crsenv{'internal.courseowner'} eq 
                   10081:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10082:                                     $refused = '';
                   10083:                                 }
                   10084:                             }
                   10085:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10086:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10087:                                 if ($crsenv{'internal.courseowner'} eq 
                   10088:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10089:                                     $refused = '';
                   10090:                                 }
                   10091:                             }
                   10092:                         }
                   10093:                     }
1.1368    raeburn  10094:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10095:                     if ($role eq 'st') {
                   10096:                         $refused = '';
1.1377    raeburn  10097:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10098:                         $refused = '';
                   10099:                     }
1.1017    raeburn  10100:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10101:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10102:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10103:                         my $wrongcc;
                   10104:                         if ($cnum =~ /^$match_community$/) {
                   10105:                             $wrongcc = 1 if ($role eq 'cc');
                   10106:                         } else {
                   10107:                             $wrongcc = 1 if ($role eq 'co');
                   10108:                         }
                   10109:                         unless ($wrongcc) {
                   10110:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10111:                             if ($crsenv{'internal.courseowner'} eq 
                   10112:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10113:                                 $refused = '';
                   10114:                             }
1.1017    raeburn  10115:                         }
                   10116:                     }
1.1183    raeburn  10117:                 } elsif ($context eq 'requestauthor') {
                   10118:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10119:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10120:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10121:                             $refused = '';
                   10122:                         } else {
                   10123:                             my %domdefaults = &get_domain_defaults($udom);
                   10124:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10125:                                 my $checkbystatus;
                   10126:                                 if ($env{'user.adv'}) { 
                   10127:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10128:                                     if ($disposition eq 'automatic') {
                   10129:                                         $refused = '';
                   10130:                                     } elsif ($disposition eq '') {
                   10131:                                         $checkbystatus = 1;
                   10132:                                     } 
                   10133:                                 } else {
                   10134:                                     $checkbystatus = 1;
                   10135:                                 }
                   10136:                                 if ($checkbystatus) {
                   10137:                                     if ($env{'environment.inststatus'}) {
                   10138:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10139:                                         foreach my $type (@inststatuses) {
                   10140:                                             if (($type ne '') &&
                   10141:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10142:                                                 $refused = '';
                   10143:                                             }
                   10144:                                         }
                   10145:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10146:                                         $refused = '';
                   10147:                                     }
                   10148:                                 }
                   10149:                             }
                   10150:                         }
                   10151:                     }
1.1017    raeburn  10152:                 }
                   10153:                 if ($refused) {
1.947     raeburn  10154:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10155:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10156: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10157:                     return 'refused';
                   10158:                 }
1.932     raeburn  10159:             }
1.1131    raeburn  10160:         } elsif ($role eq 'au') {
                   10161:             if ($url ne '/'.$udom.'/') {
                   10162:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10163:                          ' to assign author role for '.$uname.':'.$udom.
                   10164:                          ' in domain: '.$url.' refused (wrong domain).');
                   10165:                 return 'refused';
                   10166:             }
1.104     www      10167:         }
1.21      www      10168:         $mrole=$role;
                   10169:     }
1.620     albertel 10170:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10171:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10172:     if ($end) { $command.='_'.$end; }
1.21      www      10173:     if ($start) {
                   10174: 	if ($end) { 
1.81      www      10175:            $command.='_'.$start; 
1.21      www      10176:         } else {
1.81      www      10177:            $command.='_0_'.$start;
1.21      www      10178:         }
                   10179:     }
1.739     raeburn  10180:     my $origstart = $start;
                   10181:     my $origend = $end;
1.957     raeburn  10182:     my $delflag;
1.357     www      10183: # actually delete
                   10184:     if ($deleteflag) {
1.373     www      10185: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10186: # modify command to delete the role
1.620     albertel 10187:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10188:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10189: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10190: # set start and finish to negative values for userrolelog
                   10191:            $start=-1;
                   10192:            $end=-1;
1.957     raeburn  10193:            $delflag = 1;
1.357     www      10194:         }
                   10195:     }
                   10196: # send command
1.349     www      10197:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10198: # log new user role if status is ok
1.349     www      10199:     if ($answer eq 'ok') {
1.663     raeburn  10200: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10201:         if (($role eq 'cc') || ($role eq 'in') ||
                   10202:             ($role eq 'ep') || ($role eq 'ad') ||
                   10203:             ($role eq 'ta') || ($role eq 'st') ||
                   10204:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10205:             ($role eq 'co')) {
1.1200    raeburn  10206: # for course roles, perform group memberships changes triggered by role change.
                   10207:             unless ($role =~ /^gr/) {
                   10208:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10209:                                                  $origstart,$selfenroll,$context);
                   10210:             }
1.1184    raeburn  10211:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10212:                            $selfenroll,$context);
                   10213:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10214:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10215:                  ($role eq 'da')) {
1.1184    raeburn  10216:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10217:                            $context);
                   10218:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10219:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10220:                              $context); 
                   10221:         }
1.1053    raeburn  10222:         if ($role eq 'cc') {
                   10223:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10224:         }
1.349     www      10225:     }
                   10226:     return $answer;
1.169     harris41 10227: }
                   10228: 
1.1053    raeburn  10229: sub autoupdate_coowners {
                   10230:     my ($url,$end,$start,$uname,$udom) = @_;
                   10231:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10232:     if (($cdom ne '') && ($cnum ne '')) {
                   10233:         my $now = time;
                   10234:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10235:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10236:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10237:             my $instcode = $coursehash{'internal.coursecode'};
                   10238:             if ($instcode ne '') {
1.1056    raeburn  10239:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10240:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10241:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10242:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   10243:                         if ($result eq 'valid') {
                   10244:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10245:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10246:                                     push(@newcoowners,$coowner);
                   10247:                                 }
                   10248:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10249:                                     push(@newcoowners,$uname.':'.$udom);
                   10250:                                 }
                   10251:                                 @newcoowners = sort(@newcoowners);
                   10252:                             } else {
                   10253:                                 push(@newcoowners,$uname.':'.$udom);
                   10254:                             }
                   10255:                         } else {
                   10256:                             if ($coursehash{'internal.co-owners'}) {
                   10257:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10258:                                     unless ($coowner eq $uname.':'.$udom) {
                   10259:                                         push(@newcoowners,$coowner);
                   10260:                                     }
                   10261:                                 }
                   10262:                                 unless (@newcoowners > 0) {
                   10263:                                     $delcoowners = 1;
                   10264:                                     $coowners = '';
                   10265:                                 }
                   10266:                             }
                   10267:                         }
                   10268:                         if (@newcoowners || $delcoowners) {
                   10269:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10270:                                             $delcoowners,@newcoowners);
                   10271:                         }
                   10272:                     }
                   10273:                 }
                   10274:             }
                   10275:         }
                   10276:     }
                   10277: }
                   10278: 
                   10279: sub store_coowners {
                   10280:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10281:     my $cid = $cdom.'_'.$cnum;
                   10282:     my ($coowners,$delresult,$putresult);
                   10283:     if (@newcoowners) {
                   10284:         $coowners = join(',',@newcoowners);
                   10285:         my %coownershash = (
                   10286:                             'internal.co-owners' => $coowners,
                   10287:                            );
                   10288:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10289:         if ($putresult eq 'ok') {
                   10290:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10291:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10292:             }
                   10293:         }
                   10294:     }
                   10295:     if ($delcoowners) {
                   10296:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10297:         if ($delresult eq 'ok') {
                   10298:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10299:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10300:             }
                   10301:         }
                   10302:     }
                   10303:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10304:         my %crsinfo =
                   10305:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10306:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10307:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10308:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10309:         }
                   10310:     }
                   10311: }
                   10312: 
1.169     harris41 10313: # -------------------------------------------------- Modify user authentication
1.197     www      10314: # Overrides without validation
                   10315: 
1.169     harris41 10316: sub modifyuserauth {
                   10317:     my ($udom,$uname,$umode,$upass)=@_;
                   10318:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10319:     my $allowed;
                   10320:     if (&allowed('mau',$udom)) {
                   10321:         $allowed = 1;
                   10322:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10323:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10324:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10325:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10326:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10327:         if (($cdom ne '') && ($cnum ne '')) {
                   10328:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10329:             if ($is_owner) {
                   10330:                 $allowed = 1;
                   10331:             }
                   10332:         }
                   10333:     }
                   10334:     unless ($allowed) { return 'refused'; }
1.197     www      10335:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10336:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10337:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10338:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10339: 		     &escape($upass),$uhome);
1.1434    raeburn  10340:     my $ip = &get_requestor_ip();
1.620     albertel 10341:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10342:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  10343:          '(Remote '.$ip.'): '.$reply);
1.197     www      10344:     &log($udom,,$uname,$uhome,
1.620     albertel 10345:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10346:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  10347:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10348:     unless ($reply eq 'ok') {
1.197     www      10349:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10350: 	return 'error: '.$reply;
                   10351:     }   
1.170     harris41 10352:     return 'ok';
1.80      www      10353: }
                   10354: 
1.81      www      10355: # --------------------------------------------------------------- Modify a user
1.80      www      10356: 
1.81      www      10357: sub modifyuser {
1.206     matthew  10358:     my ($udom,    $uname, $uid,
                   10359:         $umode,   $upass, $first,
                   10360:         $middle,  $last,  $gene,
1.1058    raeburn  10361:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10362:     $udom= &LONCAPA::clean_domain($udom);
                   10363:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10364:     my $showcandelete = 'none';
                   10365:     if (ref($candelete) eq 'ARRAY') {
                   10366:         if (@{$candelete} > 0) {
                   10367:             $showcandelete = join(', ',@{$candelete});
                   10368:         }
                   10369:     }
1.81      www      10370:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10371:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10372: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10373:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10374:                                      ' desiredhome not specified'). 
1.620     albertel 10375:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10376:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10377:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10378:     my $newuser;
                   10379:     if ($uhome eq 'no_host') {
                   10380:         $newuser = 1;
1.1368    raeburn  10381:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10382:                 ($umode eq 'lti')) {
                   10383:             return 'error: more information needed to create new user';
                   10384:         }
1.1075    raeburn  10385:     }
1.80      www      10386: # ----------------------------------------------------------------- Create User
1.406     albertel 10387:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10388: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10389:         my $unhome='';
1.844     albertel 10390:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10391:             $unhome = $desiredhome;
1.620     albertel 10392: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10393: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10394:         } else { # load balancing routine for determining $unhome
1.81      www      10395:             my $loadm=10000000;
1.841     albertel 10396: 	    my %servers = &get_servers($udom,'library');
                   10397: 	    foreach my $tryserver (keys(%servers)) {
                   10398: 		my $answer=reply('load',$tryserver);
                   10399: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10400: 		    $loadm=$answer;
                   10401: 		    $unhome=$tryserver;
                   10402: 		}
1.80      www      10403: 	    }
                   10404:         }
                   10405:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10406: 	    return 'error: unable to find a home server for '.$uname.
                   10407:                    ' in domain '.$udom;
1.80      www      10408:         }
                   10409:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10410:                          &escape($upass),$unhome);
                   10411: 	unless ($reply eq 'ok') {
                   10412:             return 'error: '.$reply;
                   10413:         }   
1.230     stredwic 10414:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10415:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10416: 	    return 'error: unable verify users home machine.';
1.80      www      10417:         }
1.209     matthew  10418:     }   # End of creation of new user
1.80      www      10419: # ---------------------------------------------------------------------- Add ID
                   10420:     if ($uid) {
                   10421:        $uid=~tr/A-Z/a-z/;
                   10422:        my %uidhash=&idrget($udom,$uname);
1.196     www      10423:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10424:          && (!$forceid)) {
1.80      www      10425: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10426: 	      return 'error: user id "'.$uid.'" does not match '.
                   10427:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10428:           }
                   10429:        } else {
1.1300    raeburn  10430: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10431:        }
                   10432:     }
                   10433: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10434:     my @tmp=&get('environment',
1.899     raeburn  10435: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10436:                     'permanentemail','inststatus'],
1.134     albertel 10437: 		   $udom,$uname);
1.1075    raeburn  10438:     my (%names,%oldnames);
1.313     matthew  10439:     if ($tmp[0] =~ m/^error:.*/) { 
                   10440:         %names=(); 
                   10441:     } else {
                   10442:         %names = @tmp;
1.1075    raeburn  10443:         %oldnames = %names;
1.313     matthew  10444:     }
1.388     www      10445: #
1.1058    raeburn  10446: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10447: # of users did not contain them), do not overwrite existing values
                   10448: # unless field is in $candelete array ref.  
                   10449: #
                   10450: 
                   10451:     my @fields = ('firstname','middlename','lastname','generation',
                   10452:                   'permanentemail','id');
                   10453:     my %newvalues;
                   10454:     if (ref($candelete) eq 'ARRAY') {
                   10455:         foreach my $field (@fields) {
                   10456:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10457:                 if ($field eq 'firstname') {
                   10458:                     $names{$field} = $first;
                   10459:                 } elsif ($field eq 'middlename') {
                   10460:                     $names{$field} = $middle;
                   10461:                 } elsif ($field eq 'lastname') {
                   10462:                     $names{$field} = $last;
                   10463:                 } elsif ($field eq 'generation') { 
                   10464:                     $names{$field} = $gene;
                   10465:                 } elsif ($field eq 'permanentemail') {
                   10466:                     $names{$field} = $email;
                   10467:                 } elsif ($field eq 'id') {
                   10468:                     $names{$field}  = $uid;
                   10469:                 }
                   10470:             }
                   10471:         }
                   10472:     }
1.388     www      10473:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10474:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10475:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10476:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10477:     if ($email) {
                   10478:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10479:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10480:     }
1.899     raeburn  10481:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10482:     if (defined($inststatus)) {
                   10483:         $names{'inststatus'} = '';
                   10484:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10485:         if (ref($usertypes) eq 'HASH') {
                   10486:             my @okstatuses; 
                   10487:             foreach my $item (split(/:/,$inststatus)) {
                   10488:                 if (defined($usertypes->{$item})) {
                   10489:                     push(@okstatuses,$item);  
                   10490:                 }
                   10491:             }
                   10492:             if (@okstatuses) {
                   10493:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10494:             }
                   10495:         }
                   10496:     }
1.1075    raeburn  10497:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10498:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10499:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10500:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10501:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10502:     } else {
                   10503:         $logmsg .= ' during self creation';
                   10504:     }
1.1075    raeburn  10505:     my $changed;
                   10506:     if ($newuser) {
                   10507:         $changed = 1;
                   10508:     } else {
                   10509:         foreach my $field (@fields) {
                   10510:             if ($names{$field} ne $oldnames{$field}) {
                   10511:                 $changed = 1;
                   10512:                 last;
                   10513:             }
                   10514:         }
                   10515:     }
                   10516:     unless ($changed) {
                   10517:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10518:         &logthis($logmsg);
                   10519:         return 'ok';
                   10520:     }
                   10521:     my $reply = &put('environment', \%names, $udom,$uname);
                   10522:     if ($reply ne 'ok') { 
                   10523:         return 'error: '.$reply;
                   10524:     }
1.1087    raeburn  10525:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10526:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10527:     }
1.1075    raeburn  10528:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10529:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10530:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10531:     &logthis($logmsg);
1.134     albertel 10532:     return 'ok';
1.80      www      10533: }
                   10534: 
1.81      www      10535: # -------------------------------------------------------------- Modify student
1.80      www      10536: 
1.81      www      10537: sub modifystudent {
                   10538:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10539:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10540:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10541:     if (!$cid) {
1.620     albertel 10542: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10543: 	    return 'not_in_class';
                   10544: 	}
1.80      www      10545:     }
                   10546: # --------------------------------------------------------------- Make the user
1.81      www      10547:     my $reply=&modifyuser
1.209     matthew  10548: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10549:          $desiredhome,$email,$inststatus);
1.80      www      10550:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10551:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10552:     # student's environment
1.297     matthew  10553:     $uid = undef if (!$forceid);
1.455     albertel 10554:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10555:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10556:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10557:     return $reply;
                   10558: }
                   10559: 
                   10560: sub modify_student_enrollment {
1.1216    raeburn  10561:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10562:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10563:     my ($cdom,$cnum,$chome);
                   10564:     if (!$cid) {
1.620     albertel 10565: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10566: 	    return 'not_in_class';
                   10567: 	}
1.620     albertel 10568: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10569: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10570:     } else {
                   10571: 	($cdom,$cnum)=split(/_/,$cid);
                   10572:     }
1.620     albertel 10573:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10574:     if (!$chome) {
1.457     raeburn  10575: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10576:     }
1.455     albertel 10577:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10578:     # Make sure the user exists
1.81      www      10579:     my $uhome=&homeserver($uname,$udom);
                   10580:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10581: 	return 'error: no such user';
                   10582:     }
1.297     matthew  10583:     # Get student data if we were not given enough information
                   10584:     if (!defined($first)  || $first  eq '' || 
                   10585:         !defined($last)   || $last   eq '' || 
                   10586:         !defined($uid)    || $uid    eq '' || 
                   10587:         !defined($middle) || $middle eq '' || 
                   10588:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10589:         # They did not supply us with enough data to enroll the student, so
                   10590:         # we need to pick up more information.
1.297     matthew  10591:         my %tmp = &get('environment',
1.294     matthew  10592:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10593:                        ,$udom,$uname);
                   10594: 
1.800     albertel 10595:         #foreach my $key (keys(%tmp)) {
                   10596:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10597:         #}
1.294     matthew  10598:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10599:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10600:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10601:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10602:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10603:     }
1.556     albertel 10604:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10605:     my $user = "$uname:$udom";
                   10606:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10607:     my $reply=cput('classlist',
1.1148    raeburn  10608: 		   {$user => 
1.1314    raeburn  10609: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10610: 		   $cdom,$cnum);
1.1148    raeburn  10611:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10612:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10613:     } else { 
1.81      www      10614: 	return 'error: '.$reply;
                   10615:     }
1.297     matthew  10616:     # Add student role to user
1.83      www      10617:     my $uurl='/'.$cid;
1.81      www      10618:     $uurl=~s/\_/\//g;
                   10619:     if ($usec) {
                   10620: 	$uurl.='/'.$usec;
                   10621:     }
1.1148    raeburn  10622:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10623:                              $selfenroll,$context);
                   10624:     if ($result ne 'ok') {
                   10625:         if ($old_entry{$user} ne '') {
                   10626:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10627:         } else {
                   10628:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10629:         }
                   10630:     }
                   10631:     return $result; 
1.21      www      10632: }
                   10633: 
1.556     albertel 10634: sub format_name {
                   10635:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10636:     my $name;
                   10637:     if ($first ne 'lastname') {
                   10638: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10639:     } else {
                   10640: 	if ($lastname=~/\S/) {
                   10641: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10642: 	    $name=~s/\s+,/,/;
                   10643: 	} else {
                   10644: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10645: 	}
                   10646:     }
                   10647:     $name=~s/^\s+//;
                   10648:     $name=~s/\s+$//;
                   10649:     $name=~s/\s+/ /g;
                   10650:     return $name;
                   10651: }
                   10652: 
1.84      www      10653: # ------------------------------------------------- Write to course preferences
                   10654: 
                   10655: sub writecoursepref {
                   10656:     my ($courseid,%prefs)=@_;
                   10657:     $courseid=~s/^\///;
                   10658:     $courseid=~s/\_/\//g;
                   10659:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10660:     my $chome=homeserver($cnum,$cdomain);
                   10661:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10662: 	return 'error: no such course';
                   10663:     }
                   10664:     my $cstring='';
1.800     albertel 10665:     foreach my $pref (keys(%prefs)) {
                   10666: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10667:     }
1.84      www      10668:     $cstring=~s/\&$//;
                   10669:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10670: }
                   10671: 
                   10672: # ---------------------------------------------------------- Make/modify course
                   10673: 
                   10674: sub createcourse {
1.741     raeburn  10675:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  10676:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10677:     $url=&declutter($url);
                   10678:     my $cid='';
1.1028    raeburn  10679:     if ($context eq 'requestcourses') {
                   10680:         my $can_create = 0;
                   10681:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10682:         if ($udom eq $ownerdom) {
1.1423    raeburn  10683:             my $reload;
                   10684:             if (($callercontext eq 'auto') &&
                   10685:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10686:                 $reload = 'reload';
                   10687:             }
                   10688:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10689:                                   $context)) {
                   10690:                 $can_create = 1;
                   10691:             }
                   10692:         } else {
                   10693:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10694:                                            $category);
                   10695:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10696:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10697:                 if (@curr > 0) {
                   10698:                     my @options = qw(approval validate autolimit);
                   10699:                     my $optregex = join('|',@options);
                   10700:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10701:                         $can_create = 1;
                   10702:                     }
                   10703:                 }
                   10704:             }
                   10705:         }
                   10706:         if ($can_create) {
                   10707:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10708:                 unless (&allowed('ccc',$udom)) {
                   10709:                     return 'refused'; 
                   10710:                 }
1.1017    raeburn  10711:             }
                   10712:         } else {
                   10713:             return 'refused';
                   10714:         }
1.1028    raeburn  10715:     } elsif (!&allowed('ccc',$udom)) {
                   10716:         return 'refused';
1.84      www      10717:     }
1.1011    raeburn  10718: # --------------------------------------------------------------- Get Unique ID
                   10719:     my $uname;
                   10720:     if ($cnum =~ /^$match_courseid$/) {
                   10721:         my $chome=&homeserver($cnum,$udom,'true');
                   10722:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10723:             $uname = $cnum;
                   10724:         } else {
1.1038    raeburn  10725:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10726:         }
                   10727:     } else {
1.1038    raeburn  10728:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10729:     }
                   10730:     return $uname if ($uname =~ /^error/);
                   10731: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10732:     if (!defined($course_server)) {
                   10733:         if (defined(&domain($udom,'primary'))) {
                   10734:             $course_server = &domain($udom,'primary');
                   10735:         } else {
                   10736:             $course_server = $env{'user.home'}; 
                   10737:         }
                   10738:     }
                   10739:     my %host_servers =
                   10740:         &Apache::lonnet::get_servers($udom,'library');
                   10741:     unless ($host_servers{$course_server}) {
                   10742:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10743:     }
1.84      www      10744: # ------------------------------------------------------------- Make the course
                   10745:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10746:                       $course_server);
1.84      www      10747:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10748:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10749:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10750: 	return 'error: no such course';
                   10751:     }
1.271     www      10752: # ----------------------------------------------------------------- Course made
1.516     raeburn  10753: # log existence
1.1029    raeburn  10754:     my $now = time;
1.918     raeburn  10755:     my $newcourse = {
                   10756:                     $udom.'_'.$uname => {
1.921     raeburn  10757:                                      description => $description,
                   10758:                                      inst_code   => $inst_code,
                   10759:                                      owner       => $course_owner,
                   10760:                                      type        => $crstype,
1.1029    raeburn  10761:                                      creator     => $env{'user.name'}.':'.
                   10762:                                                     $env{'user.domain'},
                   10763:                                      created     => $now,
                   10764:                                      context     => $context,
1.918     raeburn  10765:                                                 },
                   10766:                     };
1.921     raeburn  10767:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10768: # set toplevel url
1.271     www      10769:     my $topurl=$url;
                   10770:     unless ($nonstandard) {
                   10771: # ------------------------------------------ For standard courses, make top url
                   10772:         my $mapurl=&clutter($url);
1.278     www      10773:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10774:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10775: <map>
                   10776: <resource id="1" type="start"></resource>
                   10777: <resource id="2" src="$mapurl"></resource>
                   10778: <resource id="3" type="finish"></resource>
                   10779: <link index="1" from="1" to="2"></link>
                   10780: <link index="2" from="2" to="3"></link>
                   10781: </map>
                   10782: ENDINITMAP
                   10783:         $topurl=&declutter(
1.638     albertel 10784:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10785:                           );
                   10786:     }
                   10787: # ----------------------------------------------------------- Write preferences
1.84      www      10788:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10789:                      ('description'              => $description,
                   10790:                       'url'                      => $topurl,
                   10791:                       'internal.creator'         => $env{'user.name'}.':'.
                   10792:                                                     $env{'user.domain'},
                   10793:                       'internal.created'         => $now,
                   10794:                       'internal.creationcontext' => $context)
                   10795:                     );
1.84      www      10796:     return '/'.$udom.'/'.$uname;
                   10797: }
                   10798: 
1.1011    raeburn  10799: # ------------------------------------------------------------------- Create ID
                   10800: sub generate_coursenum {
1.1038    raeburn  10801:     my ($udom,$crstype) = @_;
1.1011    raeburn  10802:     my $domdesc = &domain($udom);
                   10803:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10804:     my $first;
                   10805:     if ($crstype eq 'Community') {
                   10806:         $first = '0';
                   10807:     } else {
                   10808:         $first = int(1+rand(9)); 
                   10809:     } 
                   10810:     my $uname=$first.
1.1011    raeburn  10811:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10812:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10813:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10814: # ----------------------------------------------- Make sure that does not exist
                   10815:     my $uhome=&homeserver($uname,$udom,'true');
                   10816:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10817:         if ($crstype eq 'Community') {
                   10818:             $first = '0';
                   10819:         } else {
                   10820:             $first = int(1+rand(9));
                   10821:         }
                   10822:         $uname=$first.
1.1011    raeburn  10823:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10824:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10825:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10826:         $uhome=&homeserver($uname,$udom,'true');
                   10827:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10828:             return 'error: unable to generate unique course-ID';
                   10829:         }
                   10830:     }
                   10831:     return $uname;
                   10832: }
                   10833: 
1.813     albertel 10834: sub is_course {
1.1167    droeschl 10835:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10836:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10837: 
1.1381    raeburn  10838:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10839:     my $uhome=&homeserver($cnum,$cdom);
                   10840:     my $iscourse;
                   10841:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10842:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10843:     } else {
                   10844:         my $hashid = $cdom.':'.$cnum;
                   10845:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10846:         unless (defined($cached)) {
                   10847:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10848:                                         $cnum,undef,undef,'.');
                   10849:             $iscourse = 0;
                   10850:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10851:                 $iscourse = 1;
                   10852:             }
                   10853:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10854:         }
                   10855:     }
                   10856:     return unless ($iscourse);
1.1167    droeschl 10857:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10858: }
                   10859: 
1.1015    raeburn  10860: sub store_userdata {
                   10861:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10862:     my $result;
1.1016    raeburn  10863:     if ($datakey ne '') {
1.1013    raeburn  10864:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10865:             if ($udom eq '' || $uname eq '') {
                   10866:                 $udom = $env{'user.domain'};
                   10867:                 $uname = $env{'user.name'};
                   10868:             }
                   10869:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10870:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10871:                 $result = 'error: no_host';
                   10872:             } else {
1.1434    raeburn  10873:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10874:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10875: 
                   10876:                 my $namevalue='';
                   10877:                 foreach my $key (keys(%{$storehash})) {
                   10878:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10879:                 }
                   10880:                 $namevalue=~s/\&$//;
1.1224    raeburn  10881:                 unless ($namespace eq 'courserequests') {
                   10882:                     $datakey = &escape($datakey);
                   10883:                 }
1.1105    raeburn  10884:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10885:                                   $namevalue,$uhome);
1.1013    raeburn  10886:             }
                   10887:         } else {
                   10888:             $result = 'error: data to store was not a hash reference'; 
                   10889:         }
                   10890:     } else {
                   10891:         $result= 'error: invalid requestkey'; 
                   10892:     }
                   10893:     return $result;
                   10894: }
                   10895: 
1.21      www      10896: # ---------------------------------------------------------- Assign Custom Role
                   10897: 
                   10898: sub assigncustomrole {
1.957     raeburn  10899:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10900:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10901:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10902: }
                   10903: 
                   10904: # ----------------------------------------------------------------- Revoke Role
                   10905: 
                   10906: sub revokerole {
1.957     raeburn  10907:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10908:     my $now=time;
1.965     raeburn  10909:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10910: }
                   10911: 
                   10912: # ---------------------------------------------------------- Revoke Custom Role
                   10913: 
                   10914: sub revokecustomrole {
1.957     raeburn  10915:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10916:     my $now=time;
1.357     www      10917:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10918:            $deleteflag,$selfenroll,$context);
1.17      www      10919: }
                   10920: 
1.533     banghart 10921: # ------------------------------------------------------------ Disk usage
1.535     albertel 10922: sub diskusage {
1.955     raeburn  10923:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10924:     $directorypath =~ s/\/$//;
                   10925:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10926:                        .&escape($getpropath).':'.&escape($uname).':'
                   10927:                        .&escape($udom),homeserver($uname,$udom));
                   10928:     if ($listing eq 'unknown_cmd') {
                   10929:         if ($getpropath) {
                   10930:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10931:         }
                   10932:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10933:     }
1.514     albertel 10934:     return $listing;
1.512     banghart 10935: }
                   10936: 
1.566     banghart 10937: sub is_locked {
1.1096    raeburn  10938:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10939:     my @check;
                   10940:     my $is_locked;
1.1093    raeburn  10941:     push (@check,$file_name);
1.613     albertel 10942:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10943: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10944:     my ($tmp)=keys(%locked);
                   10945:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10946:     
1.566     banghart 10947:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10948:         $is_locked = 'false';
                   10949:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10950:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10951:                $is_locked = 'true';
1.1096    raeburn  10952:                if (ref($which) eq 'ARRAY') {
                   10953:                    push(@{$which},$entry);
                   10954:                } else {
                   10955:                    last;
                   10956:                }
1.745     raeburn  10957:            }
                   10958:        }
1.566     banghart 10959:     } else {
                   10960:         $is_locked = 'false';
                   10961:     }
1.1093    raeburn  10962:     return $is_locked;
1.566     banghart 10963: }
                   10964: 
1.759     albertel 10965: sub declutter_portfile {
                   10966:     my ($file) = @_;
1.833     albertel 10967:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10968:     return $file;
                   10969: }
                   10970: 
1.559     banghart 10971: # ------------------------------------------------------------- Mark as Read Only
                   10972: 
                   10973: sub mark_as_readonly {
                   10974:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10975:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10976:     my ($tmp)=keys(%current_permissions);
                   10977:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10978:     foreach my $file (@{$files}) {
1.759     albertel 10979: 	$file = &declutter_portfile($file);
1.561     banghart 10980:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10981:     }
1.613     albertel 10982:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10983:     return;
                   10984: }
                   10985: 
1.572     banghart 10986: # ------------------------------------------------------------Save Selected Files
                   10987: 
                   10988: sub save_selected_files {
                   10989:     my ($user, $path, @files) = @_;
                   10990:     my $filename = $user."savedfiles";
1.573     banghart 10991:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10992:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10993:     foreach my $file (@files) {
1.620     albertel 10994:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10995:     }
                   10996:     foreach my $file (@other_files) {
1.574     banghart 10997:         print (OUT $file."\n");
1.572     banghart 10998:     }
1.574     banghart 10999:     close (OUT);
1.572     banghart 11000:     return 'ok';
                   11001: }
                   11002: 
1.574     banghart 11003: sub clear_selected_files {
                   11004:     my ($user) = @_;
                   11005:     my $filename = $user."savedfiles";
1.1359    raeburn  11006:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11007:     print (OUT undef);
                   11008:     close (OUT);
                   11009:     return ("ok");    
                   11010: }
                   11011: 
1.572     banghart 11012: sub files_in_path {
                   11013:     my ($user, $path) = @_;
                   11014:     my $filename = $user."savedfiles";
                   11015:     my %return_files;
1.1359    raeburn  11016:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11017:     while (my $line_in = <IN>) {
1.574     banghart 11018:         chomp ($line_in);
                   11019:         my @paths_and_file = split (m!/!, $line_in);
                   11020:         my $file_part = pop (@paths_and_file);
                   11021:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11022:         $path_part.='/';
                   11023:         my $path_and_file = $path_part.$file_part;
                   11024:         if ($path_part eq $path) {
                   11025:             $return_files{$file_part}= 'selected';
                   11026:         }
                   11027:     }
1.574     banghart 11028:     close (IN);
                   11029:     return (\%return_files);
1.572     banghart 11030: }
                   11031: 
                   11032: # called in portfolio select mode, to show files selected NOT in current directory
                   11033: sub files_not_in_path {
                   11034:     my ($user, $path) = @_;
                   11035:     my $filename = $user."savedfiles";
                   11036:     my @return_files;
                   11037:     my $path_part;
1.1359    raeburn  11038:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11039:     while (my $line = <IN>) {
1.572     banghart 11040:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11041:         my @paths_and_file = split(m|/|, $line);
                   11042:         my $file_part = pop(@paths_and_file);
                   11043:         chomp($file_part);
                   11044:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11045:         $path_part .= '/';
                   11046:         my $path_and_file = $path_part.$file_part;
                   11047:         if ($path_part ne $path) {
1.800     albertel 11048:             push(@return_files, ($path_and_file));
1.572     banghart 11049:         }
                   11050:     }
1.800     albertel 11051:     close(OUT);
1.574     banghart 11052:     return (@return_files);
1.572     banghart 11053: }
                   11054: 
1.1273    raeburn  11055: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11056:  
                   11057: sub portfiles_versioning {
                   11058:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11059:     my $portfolio_root = '/userfiles/portfolio';
                   11060:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11061:     foreach my $file (@{$portfiles}) {
                   11062:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11063:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11064:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11065:         my $getpropath = 1;
                   11066:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11067:                                              $stu_name,$getpropath);
                   11068:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11069:         my $new_answer = 
                   11070:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11071:         if ($new_answer ne 'problem getting file') {
                   11072:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11073:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11074:                               [$symb,$env{'request.course.id'},'graded']);
                   11075:         }
                   11076:     }
                   11077: }
                   11078: 
                   11079: sub get_next_version {
                   11080:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11081:     my $version;
                   11082:     if (ref($dir_list) eq 'ARRAY') {
                   11083:         foreach my $row (@{$dir_list}) {
                   11084:             my ($file) = split(/\&/,$row,2);
                   11085:             my ($file_name,$file_version,$file_ext) =
                   11086:                 &file_name_version_ext($file);
                   11087:             if (($file_name eq $answer_name) &&
                   11088:                 ($file_ext eq $answer_ext)) {
                   11089:                      # gets here if filename and extension match,
                   11090:                      # regardless of version
                   11091:                 if ($file_version ne '') {
                   11092:                     # a versioned file is found  so save it for later
                   11093:                     if ($file_version > $version) {
                   11094:                         $version = $file_version;
                   11095:                     }
                   11096:                 }
                   11097:             }
                   11098:         }
                   11099:     }
                   11100:     $version ++;
                   11101:     return($version);
                   11102: }
                   11103: 
                   11104: sub version_selected_portfile {
                   11105:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11106:     my ($answer_name,$answer_ver,$answer_ext) =
                   11107:         &file_name_version_ext($file_name);
                   11108:     my $new_answer;
                   11109:     $env{'form.copy'} =
                   11110:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11111:     if($env{'form.copy'} eq '-1') {
                   11112:         $new_answer = 'problem getting file';
                   11113:     } else {
                   11114:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11115:         my $copy_result = 
                   11116:             &finishuserfileupload($stu_name,$domain,'copy',
                   11117:                                   '/portfolio'.$directory.$new_answer);
                   11118:     }
                   11119:     undef($env{'form.copy'});
                   11120:     return ($new_answer);
                   11121: }
                   11122: 
                   11123: sub file_name_version_ext {
                   11124:     my ($file)=@_;
                   11125:     my @file_parts = split(/\./, $file);
                   11126:     my ($name,$version,$ext);
                   11127:     if (@file_parts > 1) {
                   11128:         $ext=pop(@file_parts);
                   11129:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11130:             $version=pop(@file_parts);
                   11131:         }
                   11132:         $name=join('.',@file_parts);
                   11133:     } else {
                   11134:         $name=join('.',@file_parts);
                   11135:     }
                   11136:     return($name,$version,$ext);
                   11137: }
                   11138: 
1.745     raeburn  11139: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11140: 
1.745     raeburn  11141: sub get_portfile_permissions {
                   11142:     my ($domain,$user) = @_;
1.613     albertel 11143:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11144:     my ($tmp)=keys(%current_permissions);
                   11145:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11146:     return \%current_permissions;
                   11147: }
                   11148: 
                   11149: #---------------------------------------------Get portfolio file access controls
                   11150: 
1.749     raeburn  11151: sub get_access_controls {
1.745     raeburn  11152:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11153:     my %access;
                   11154:     my $real_file = $file;
                   11155:     $file =~ s/\.meta$//;
1.745     raeburn  11156:     if (defined($file)) {
1.749     raeburn  11157:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11158:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11159:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11160:             }
                   11161:         }
1.745     raeburn  11162:     } else {
1.749     raeburn  11163:         foreach my $key (keys(%{$current_permissions})) {
                   11164:             if ($key =~ /\0accesscontrol$/) {
                   11165:                 if (defined($group)) {
                   11166:                     if ($key !~ m-^\Q$group\E/-) {
                   11167:                         next;
                   11168:                     }
                   11169:                 }
                   11170:                 my ($fullpath) = split(/\0/,$key);
                   11171:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11172:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11173:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11174:                     }
                   11175:                 }
                   11176:             }
                   11177:         }
                   11178:     }
                   11179:     return %access;
                   11180: }
                   11181: 
                   11182: sub modify_access_controls {
                   11183:     my ($file_name,$changes,$domain,$user)=@_;
                   11184:     my ($outcome,$deloutcome);
                   11185:     my %store_permissions;
                   11186:     my %new_values;
                   11187:     my %new_control;
                   11188:     my %translation;
                   11189:     my @deletions = ();
                   11190:     my $now = time;
                   11191:     if (exists($$changes{'activate'})) {
                   11192:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11193:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11194:             my $numnew = scalar(@newitems);
                   11195:             for (my $i=0; $i<$numnew; $i++) {
                   11196:                 my $newkey = $newitems[$i];
                   11197:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11198:                 if ($newkey =~ /^\d+:/) { 
                   11199:                     $newkey =~ s/^(\d+)/$newid/;
                   11200:                     $translation{$1} = $newid;
                   11201:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11202:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11203:                     $translation{$1} = $newid;
                   11204:                 }
1.749     raeburn  11205:                 $new_values{$file_name."\0".$newkey} = 
                   11206:                                           $$changes{'activate'}{$newitems[$i]};
                   11207:                 $new_control{$newkey} = $now;
                   11208:             }
                   11209:         }
                   11210:     }
                   11211:     my %todelete;
                   11212:     my %changed_items;
                   11213:     foreach my $action ('delete','update') {
                   11214:         if (exists($$changes{$action})) {
                   11215:             if (ref($$changes{$action}) eq 'HASH') {
                   11216:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11217:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11218:                     if ($action eq 'delete') { 
                   11219:                         $todelete{$itemnum} = 1;
                   11220:                     } else {
                   11221:                         $changed_items{$itemnum} = $key;
                   11222:                     }
                   11223:                 }
1.745     raeburn  11224:             }
                   11225:         }
1.749     raeburn  11226:     }
                   11227:     # get lock on access controls for file.
                   11228:     my $lockhash = {
                   11229:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11230:                                                        ':'.$env{'user.domain'},
                   11231:                    }; 
                   11232:     my $tries = 0;
                   11233:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11234:    
1.1288    damieng  11235:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11236:         $tries ++;
1.1289    damieng  11237:         sleep(0.1);
1.749     raeburn  11238:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11239:     }
                   11240:     if ($gotlock eq 'ok') {
                   11241:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11242:         my ($tmp)=keys(%curr_permissions);
                   11243:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11244:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11245:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11246:             if (ref($curr_controls) eq 'HASH') {
                   11247:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11248:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11249:                     if (defined($todelete{$itemnum})) {
                   11250:                         push(@deletions,$file_name."\0".$control_item);
                   11251:                     } else {
                   11252:                         if (defined($changed_items{$itemnum})) {
                   11253:                             $new_control{$changed_items{$itemnum}} = $now;
                   11254:                             push(@deletions,$file_name."\0".$control_item);
                   11255:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11256:                         } else {
                   11257:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11258:                         }
                   11259:                     }
1.745     raeburn  11260:                 }
                   11261:             }
                   11262:         }
1.970     raeburn  11263:         my ($group);
                   11264:         if (&is_course($domain,$user)) {
                   11265:             ($group,my $file) = split(/\//,$file_name,2);
                   11266:         }
1.749     raeburn  11267:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11268:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11269:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11270:         #  remove lock
                   11271:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11272:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11273:         my $sqlresult =
1.970     raeburn  11274:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11275:                                     $group);
1.749     raeburn  11276:     } else {
                   11277:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11278:     }
1.749     raeburn  11279:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11280: }
                   11281: 
1.827     raeburn  11282: sub make_public_indefinitely {
1.1271    raeburn  11283:     my (@requrl) = @_;
                   11284:     return &automated_portfile_access('public',\@requrl);
                   11285: }
                   11286: 
                   11287: sub automated_portfile_access {
                   11288:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11289:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11290:         return 'invalid';
                   11291:     }
1.1271    raeburn  11292:     my %urls;
                   11293:     if (ref($addsref) eq 'ARRAY') {
                   11294:         foreach my $requrl (@{$addsref}) {
                   11295:             if (&is_portfolio_url($requrl)) {
                   11296:                 unless (exists($urls{$requrl})) {
                   11297:                     $urls{$requrl} = 'add';
                   11298:                 }
                   11299:             }
                   11300:         }
                   11301:     }
                   11302:     if (ref($delsref) eq 'ARRAY') {
                   11303:         foreach my $requrl (@{$delsref}) { 
                   11304:             if (&is_portfolio_url($requrl)) {
                   11305:                 unless (exists($urls{$requrl})) {
                   11306:                     $urls{$requrl} = 'delete'; 
                   11307:                 }
                   11308:             }
                   11309:         }
                   11310:     }
                   11311:     unless (keys(%urls)) {
                   11312:         return 'invalid';
                   11313:     }
                   11314:     my $ip;
                   11315:     if ($accesstype eq 'ip') {
                   11316:         if (ref($info) eq 'HASH') {
                   11317:             if ($info->{'ip'} ne '') {
                   11318:                 $ip = $info->{'ip'};
                   11319:             }
                   11320:         }
                   11321:         if ($ip eq '') {
                   11322:             return 'invalid';
                   11323:         }
                   11324:     }
                   11325:     my $errors;
1.827     raeburn  11326:     my $now = time;
1.1271    raeburn  11327:     my %current_perms;
                   11328:     foreach my $requrl (sort(keys(%urls))) {
                   11329:         my $action;
                   11330:         if ($urls{$requrl} eq 'add') {
                   11331:             $action = 'activate';
                   11332:         } else {
                   11333:             $action = 'none';
                   11334:         }
                   11335:         my $aclnum = 0;
1.827     raeburn  11336:         my (undef,$udom,$unum,$file_name,$group) =
                   11337:             &parse_portfolio_url($requrl);
1.1271    raeburn  11338:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11339:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11340:         }
                   11341:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11342:                                                    $group,$file_name);
                   11343:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11344:             my ($num,$scope,$end,$start) = 
                   11345:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11346:             if ($scope eq $accesstype) {
                   11347:                 if (($start <= $now) && ($end == 0)) {
                   11348:                     if ($accesstype eq 'ip') {
                   11349:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11350:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11351:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11352:                                     if ($urls{$requrl} eq 'add') {
                   11353:                                         $action = 'none';
                   11354:                                         last;
                   11355:                                     } else {
                   11356:                                         $action = 'delete';
                   11357:                                         $aclnum = $num;
                   11358:                                         last;
                   11359:                                     }
                   11360:                                 }
                   11361:                             }
                   11362:                         }
                   11363:                     } elsif ($accesstype eq 'public') {
                   11364:                         if ($urls{$requrl} eq 'add') {
                   11365:                             $action = 'none';
                   11366:                             last;
                   11367:                         } else {
                   11368:                             $action = 'delete';
                   11369:                             $aclnum = $num;
                   11370:                             last;
                   11371:                         }
                   11372:                     }
                   11373:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11374:                     $action = 'update';
                   11375:                     $aclnum = $num;
1.1271    raeburn  11376:                     last;
1.827     raeburn  11377:                 }
                   11378:             }
                   11379:         }
                   11380:         if ($action eq 'none') {
1.1271    raeburn  11381:             next;
1.827     raeburn  11382:         } else {
                   11383:             my %changes;
                   11384:             my $newend = 0;
                   11385:             my $newstart = $now;
1.1271    raeburn  11386:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11387:             $changes{$action}{$newkey} = {
1.1271    raeburn  11388:                 type => $accesstype,
1.827     raeburn  11389:                 time => {
                   11390:                     start => $newstart,
                   11391:                     end   => $newend,
                   11392:                 },
                   11393:             };
1.1271    raeburn  11394:             if ($accesstype eq 'ip') {
                   11395:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11396:             }
1.827     raeburn  11397:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11398:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11399:             unless ($outcome eq 'ok') {
                   11400:                 $errors .= $outcome.' ';
                   11401:             }
1.827     raeburn  11402:         }
1.1271    raeburn  11403:     }
                   11404:     if ($errors) {
                   11405:         $errors =~ s/\s$//;
                   11406:         return $errors;
1.827     raeburn  11407:     } else {
1.1271    raeburn  11408:         return 'ok';
1.827     raeburn  11409:     }
                   11410: }
                   11411: 
1.745     raeburn  11412: #------------------------------------------------------Get Marked as Read Only
                   11413: 
                   11414: sub get_marked_as_readonly {
                   11415:     my ($domain,$user,$what,$group) = @_;
                   11416:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11417:     my @readonly_files;
1.629     banghart 11418:     my $cmp1=$what;
                   11419:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11420:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11421:         if (defined($group)) {
                   11422:             if ($file_name !~ m-^\Q$group\E/-) {
                   11423:                 next;
                   11424:             }
                   11425:         }
1.561     banghart 11426:         if (ref($value) eq "ARRAY"){
                   11427:             foreach my $stored_what (@{$value}) {
1.629     banghart 11428:                 my $cmp2=$stored_what;
1.759     albertel 11429:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11430:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11431:                 }
1.629     banghart 11432:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11433:                     push(@readonly_files, $file_name);
1.745     raeburn  11434:                     last;
1.563     banghart 11435:                 } elsif (!defined($what)) {
                   11436:                     push(@readonly_files, $file_name);
1.745     raeburn  11437:                     last;
1.561     banghart 11438:                 }
                   11439:             }
1.745     raeburn  11440:         }
1.561     banghart 11441:     }
                   11442:     return @readonly_files;
                   11443: }
1.577     banghart 11444: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11445: 
1.577     banghart 11446: sub get_marked_as_readonly_hash {
1.745     raeburn  11447:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11448:     my %readonly_files;
1.745     raeburn  11449:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11450:         if (defined($group)) {
                   11451:             if ($file_name !~ m-^\Q$group\E/-) {
                   11452:                 next;
                   11453:             }
                   11454:         }
1.577     banghart 11455:         if (ref($value) eq "ARRAY"){
                   11456:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11457:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11458:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11459:                         if ($lock_descriptor eq 'graded') {
                   11460:                             $readonly_files{$file_name} = 'graded';
                   11461:                         } elsif ($lock_descriptor eq 'handback') {
                   11462:                             $readonly_files{$file_name} = 'handback';
                   11463:                         } else {
                   11464:                             if (!exists($readonly_files{$file_name})) {
                   11465:                                 $readonly_files{$file_name} = 'locked';
                   11466:                             }
                   11467:                         }
1.745     raeburn  11468:                     }
1.750     banghart 11469:                 } 
1.577     banghart 11470:             }
                   11471:         } 
                   11472:     }
                   11473:     return %readonly_files;
                   11474: }
1.559     banghart 11475: # ------------------------------------------------------------ Unmark as Read Only
                   11476: 
                   11477: sub unmark_as_readonly {
1.629     banghart 11478:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11479:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11480:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11481:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11482:     my $symb_crs = $what;
                   11483:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11484:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11485:     my ($tmp)=keys(%current_permissions);
                   11486:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11487:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11488:     foreach my $file (@readonly_files) {
1.759     albertel 11489: 	my $clean_file = &declutter_portfile($file);
                   11490: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11491: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11492:         my @new_locks;
                   11493:         my @del_keys;
                   11494:         if (ref($current_locks) eq "ARRAY"){
                   11495:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11496:                 my $compare=$locker;
1.749     raeburn  11497:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11498:                     $compare=join('',@{$locker});
1.746     raeburn  11499:                     if ($compare ne $symb_crs) {
                   11500:                         push(@new_locks, $locker);
                   11501:                     }
1.563     banghart 11502:                 }
                   11503:             }
1.650     albertel 11504:             if (scalar(@new_locks) > 0) {
1.563     banghart 11505:                 $current_permissions{$file} = \@new_locks;
                   11506:             } else {
                   11507:                 push(@del_keys, $file);
1.613     albertel 11508:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11509:                 delete($current_permissions{$file});
1.563     banghart 11510:             }
                   11511:         }
1.561     banghart 11512:     }
1.613     albertel 11513:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11514:     return;
                   11515: }
1.512     banghart 11516: 
1.17      www      11517: # ------------------------------------------------------------ Directory lister
                   11518: 
                   11519: sub dirlist {
1.955     raeburn  11520:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11521:     $uri=~s/^\///;
                   11522:     $uri=~s/\/$//;
1.253     stredwic 11523:     my ($udom, $uname);
1.955     raeburn  11524:     if ($getuserdir) {
1.253     stredwic 11525:         $udom = $userdomain;
                   11526:         $uname = $username;
1.955     raeburn  11527:     } else {
                   11528:         (undef,$udom,$uname)=split(/\//,$uri);
                   11529:         if(defined($userdomain)) {
                   11530:             $udom = $userdomain;
                   11531:         }
                   11532:         if(defined($username)) {
                   11533:             $uname = $username;
                   11534:         }
1.253     stredwic 11535:     }
1.955     raeburn  11536:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11537: 
1.955     raeburn  11538:     $dirRoot = $perlvar{'lonDocRoot'};
                   11539:     if (defined($getpropath)) {
                   11540:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11541:         $dirRoot =~ s/\/$//;
1.955     raeburn  11542:     } elsif (defined($getuserdir)) {
                   11543:         my $subdir=$uname.'__';
                   11544:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11545:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11546:                    ."/$udom/$subdir/$uname";
                   11547:     } elsif (defined($alternateRoot)) {
                   11548:         $dirRoot = $alternateRoot;
1.751     banghart 11549:     }
1.253     stredwic 11550: 
                   11551:     if($udom) {
                   11552:         if($uname) {
1.1135    raeburn  11553:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11554:             if ($uhome eq 'no_host') {
                   11555:                 return ([],'no_host');
                   11556:             }
1.955     raeburn  11557:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11558:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11559:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11560:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11561:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11562:             } else {
                   11563:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11564:             }
1.605     matthew  11565:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11566:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11567:                 @listing_results = split(/:/,$listing);
                   11568:             } else {
                   11569:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11570:             }
1.1135    raeburn  11571:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11572:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11573:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11574:                 return ([],$listing);
                   11575:             } else {
                   11576:                 return (\@listing_results);
1.1135    raeburn  11577:             }
1.955     raeburn  11578:         } elsif(!$alternateRoot) {
1.1136    raeburn  11579:             my (%allusers,%listerror);
1.841     albertel 11580: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11581:  	    foreach my $tryserver (keys(%servers)) {
                   11582:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11583:                                   &escape($udom),$tryserver);
                   11584:                 if ($listing eq 'unknown_cmd') {
                   11585: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11586: 				      $udom, $tryserver);
                   11587:                 } else {
                   11588:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11589:                 }
1.841     albertel 11590: 		if ($listing eq 'unknown_cmd') {
                   11591: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11592: 				      $udom, $tryserver);
                   11593: 		    @listing_results = split(/:/,$listing);
                   11594: 		} else {
                   11595: 		    @listing_results =
                   11596: 			map { &unescape($_); } split(/:/,$listing);
                   11597: 		}
1.1136    raeburn  11598:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11599:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11600:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11601:                     $listerror{$tryserver} = $listing;
                   11602:                 } else {
1.841     albertel 11603: 		    foreach my $line (@listing_results) {
                   11604: 			my ($entry) = split(/&/,$line,2);
                   11605: 			$allusers{$entry} = 1;
                   11606: 		    }
                   11607: 		}
1.253     stredwic 11608:             }
1.1136    raeburn  11609:             my @alluserslist=();
1.800     albertel 11610:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11611:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11612:             }
1.1318    droeschl 11613: 
                   11614:             if (!%listerror) {
                   11615:                 # no errors
                   11616:                 return (\@alluserslist);
                   11617:             } elsif (scalar(keys(%servers)) == 1) {
                   11618:                 # one library server, one error 
                   11619:                 my ($key) = keys(%listerror);
                   11620:                 return (\@alluserslist, $listerror{$key});
                   11621:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11622:                 # con_lost indicates that we might miss data from at least one
                   11623:                 # library server
                   11624:                 return (\@alluserslist, 'con_lost');
                   11625:             } else {
                   11626:                 # multiple library servers and no con_lost -> data should be
                   11627:                 # complete. 
                   11628:                 return (\@alluserslist);
                   11629:             }
                   11630: 
1.253     stredwic 11631:         } else {
1.1136    raeburn  11632:             return ([],'missing username');
1.253     stredwic 11633:         }
1.955     raeburn  11634:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11635:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11636:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11637:         return (\@all_domains);
1.955     raeburn  11638:     } else {
1.1136    raeburn  11639:         return ([],'missing domain');
1.275     stredwic 11640:     }
                   11641: }
                   11642: 
                   11643: # --------------------------------------------- GetFileTimestamp
                   11644: # This function utilizes dirlist and returns the date stamp for
                   11645: # when it was last modified.  It will also return an error of -1
                   11646: # if an error occurs
                   11647: 
                   11648: sub GetFileTimestamp {
1.955     raeburn  11649:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11650:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11651:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11652:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11653:                                     undef,$getuserdir);
                   11654:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11655:         return -1;
                   11656:     }
                   11657:     if (ref($fileref) eq 'ARRAY') {
                   11658:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11659:         # @stats contains first the filename, then the stat output
                   11660:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11661:     } else {
                   11662:         return -1;
1.253     stredwic 11663:     }
1.26      www      11664: }
                   11665: 
1.712     albertel 11666: sub stat_file {
                   11667:     my ($uri) = @_;
1.787     albertel 11668:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11669: 
1.955     raeburn  11670:     my ($udom,$uname,$file);
1.712     albertel 11671:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11672: 	($udom,$uname,$file) =
1.811     albertel 11673: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11674: 	$file = 'userfiles/'.$file;
                   11675:     }
                   11676:     if ($uri =~ m-^/res/-) {
                   11677: 	($udom,$uname) = 
1.807     albertel 11678: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11679: 	$file = $uri;
                   11680:     }
                   11681: 
                   11682:     if (!$udom || !$uname || !$file) {
                   11683: 	# unable to handle the uri
                   11684: 	return ();
                   11685:     }
1.956     raeburn  11686:     my $getpropath;
                   11687:     if ($file =~ /^userfiles\//) {
                   11688:         $getpropath = 1;
                   11689:     }
1.1136    raeburn  11690:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11691:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11692:         return ();
                   11693:     } else {
                   11694:         if (ref($listref) eq 'ARRAY') {
                   11695:             my @stats = split('&',$listref->[0]);
                   11696: 	    shift(@stats); #filename is first
                   11697: 	    return @stats;
                   11698:         }
1.712     albertel 11699:     }
                   11700:     return ();
                   11701: }
                   11702: 
1.1313    raeburn  11703: # --------------------------------------------------------- recursedirs
                   11704: # Recursive function to traverse either a specific user's Authoring Space
                   11705: # or corresponding Published Resource Space, and populate the hash ref:
                   11706: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11707: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11708: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11709: # files in Authoring Space.
                   11710: #
                   11711: # Inputs:
                   11712: #
                   11713: # $is_home - true if current server is home server for user's space
                   11714: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11715: # $docroot - Document root (i.e., /home/httpd/html
                   11716: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11717: # $relpath - Current path (relative to top level).
                   11718: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11719: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11720: #
                   11721: # Returns: nothing
                   11722: #
                   11723: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11724: #
                   11725: # Currently used by interface/londocs.pm to create linked select boxes for
                   11726: # directory and filename to import a Course "Author" resource into a course, and
                   11727: # also to create linked select boxes for Authoring Space and Directory to choose
                   11728: # save location for creation of a new "standard" problem from the Course Editor.
                   11729: #
                   11730: 
                   11731: sub recursedirs {
                   11732:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11733:     return unless (ref($dirhashref) eq 'HASH');
                   11734:     my $currpath = $docroot.$toppath;
                   11735:     if ($relpath) {
                   11736:         $currpath .= "/$relpath";
                   11737:     }
                   11738:     my $savefile;
                   11739:     if (ref($filehashref)) {
                   11740:         $savefile = 1;
                   11741:     }
                   11742:     if ($is_home) {
                   11743:         if (opendir(my $dirh,$currpath)) {
                   11744:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11745:                 next if ($item eq '');
                   11746:                 if (-d "$currpath/$item") {
                   11747:                     my $newpath;
                   11748:                     if ($relpath) {
                   11749:                         $newpath = "$relpath/$item";
                   11750:                     } else {
                   11751:                         $newpath = $item;
                   11752:                     }
                   11753:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11754:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11755:                 } elsif ($savefile) {
                   11756:                     if ($context eq 'priv') {
                   11757:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11758:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11759:                         }
                   11760:                     } else {
                   11761:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11762:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11763:                         }
                   11764:                     }
                   11765:                 }
                   11766:             }
                   11767:             closedir($dirh);
                   11768:         }
                   11769:     } else {
                   11770:         my ($dirlistref,$listerror) =
                   11771:             &dirlist($toppath.$relpath);
                   11772:         my @dir_lines;
                   11773:         my $dirptr=16384;
                   11774:         if (ref($dirlistref) eq 'ARRAY') {
                   11775:             foreach my $dir_line (sort
                   11776:                               {
                   11777:                                   my ($afile)=split('&',$a,2);
                   11778:                                   my ($bfile)=split('&',$b,2);
                   11779:                                   return (lc($afile) cmp lc($bfile));
                   11780:                               } (@{$dirlistref})) {
                   11781:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11782:                     split(/\&/,$dir_line,16);
                   11783:                 $item =~ s/\s+$//;
                   11784:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11785:                 if ($dirptr&$testdir) {
                   11786:                     my $newpath;
                   11787:                     if ($relpath) {
                   11788:                         $newpath = "$relpath/$item";
                   11789:                     } else {
                   11790:                         $relpath = '/';
                   11791:                         $newpath = $item;
                   11792:                     }
                   11793:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11794:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11795:                 } elsif ($savefile) {
                   11796:                     if ($context eq 'priv') {
                   11797:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11798:                             $filehashref->{$relpath}{$item} = 1;
                   11799:                         }
                   11800:                     } else {
                   11801:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11802:                             $filehashref->{$relpath}{$item} = 1;
                   11803:                         }
                   11804:                     }
                   11805:                 }
                   11806:             }
                   11807:         }
                   11808:     }
                   11809:     return;
                   11810: }
                   11811: 
1.26      www      11812: # -------------------------------------------------------- Value of a Condition
                   11813: 
1.713     albertel 11814: # gets the value of a specific preevaluated condition
                   11815: #    stored in the string  $env{user.state.<cid>}
                   11816: # or looks up a condition reference in the bighash and if if hasn't
                   11817: # already been evaluated recurses into docondval to get the value of
                   11818: # the condition, then memoizing it to 
                   11819: #   $env{user.state.<cid>.<condition>}
1.40      www      11820: sub directcondval {
                   11821:     my $number=shift;
1.620     albertel 11822:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11823: 	&Apache::lonuserstate::evalstate();
                   11824:     }
1.713     albertel 11825:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11826: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11827:     } elsif ($number =~ /^_/) {
                   11828: 	my $sub_condition;
                   11829: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11830: 		&GDBM_READER(),0640)) {
                   11831: 	    $sub_condition=$bighash{'conditions'.$number};
                   11832: 	    untie(%bighash);
                   11833: 	}
                   11834: 	my $value = &docondval($sub_condition);
1.949     raeburn  11835: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11836: 	return $value;
                   11837:     }
1.620     albertel 11838:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11839:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11840:     } else {
                   11841:        return 2;
                   11842:     }
                   11843: }
                   11844: 
1.713     albertel 11845: # get the collection of conditions for this resource
1.26      www      11846: sub condval {
                   11847:     my $condidx=shift;
1.54      www      11848:     my $allpathcond='';
1.713     albertel 11849:     foreach my $cond (split(/\|/,$condidx)) {
                   11850: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11851: 	    $allpathcond.=
                   11852: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11853: 	}
1.191     harris41 11854:     }
1.54      www      11855:     $allpathcond=~s/\|$//;
1.713     albertel 11856:     return &docondval($allpathcond);
                   11857: }
                   11858: 
                   11859: #evaluates an expression of conditions
                   11860: sub docondval {
                   11861:     my ($allpathcond) = @_;
                   11862:     my $result=0;
                   11863:     if ($env{'request.course.id'}
                   11864: 	&& defined($allpathcond)) {
                   11865: 	my $operand='|';
                   11866: 	my @stack;
                   11867: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11868: 	    if ($chunk eq '(') {
                   11869: 		push @stack,($operand,$result);
                   11870: 	    } elsif ($chunk eq ')') {
                   11871: 		my $before=pop @stack;
                   11872: 		if (pop @stack eq '&') {
                   11873: 		    $result=$result>$before?$before:$result;
                   11874: 		} else {
                   11875: 		    $result=$result>$before?$result:$before;
                   11876: 		}
                   11877: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11878: 		$operand=$chunk;
                   11879: 	    } else {
                   11880: 		my $new=directcondval($chunk);
                   11881: 		if ($operand eq '&') {
                   11882: 		    $result=$result>$new?$new:$result;
                   11883: 		} else {
                   11884: 		    $result=$result>$new?$result:$new;
                   11885: 		}
                   11886: 	    }
                   11887: 	}
1.26      www      11888:     }
                   11889:     return $result;
1.421     albertel 11890: }
                   11891: 
                   11892: # ---------------------------------------------------- Devalidate courseresdata
                   11893: 
                   11894: sub devalidatecourseresdata {
                   11895:     my ($coursenum,$coursedomain)=@_;
                   11896:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11897:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11898: }
                   11899: 
1.763     www      11900: 
1.200     www      11901: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11902: #
                   11903: #  Parameters:
                   11904: #      $coursenum    - Number of the course.
                   11905: #      $coursedomain - Domain at which the course was created.
                   11906: #  Returns:
                   11907: #     A hash of the course parameters along (I think) with timestamps
                   11908: #     and version info.
1.877     foxr     11909: 
1.624     albertel 11910: sub get_courseresdata {
                   11911:     my ($coursenum,$coursedomain)=@_;
1.200     www      11912:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11913:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11914:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11915:     my %dumpreply;
1.417     albertel 11916:     unless (defined($cached)) {
1.624     albertel 11917: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11918: 	$result=\%dumpreply;
1.251     albertel 11919: 	my ($tmp) = keys(%dumpreply);
                   11920: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11921: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11922: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11923: 	    return $tmp;
1.416     albertel 11924: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11925: 	    $result=undef;
1.599     albertel 11926: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11927: 	}
                   11928:     }
1.624     albertel 11929:     return $result;
                   11930: }
                   11931: 
1.633     albertel 11932: sub devalidateuserresdata {
                   11933:     my ($uname,$udom)=@_;
                   11934:     my $hashid="$udom:$uname";
                   11935:     &devalidate_cache_new('userres',$hashid);
                   11936: }
                   11937: 
1.624     albertel 11938: sub get_userresdata {
                   11939:     my ($uname,$udom)=@_;
                   11940:     #most student don\'t have any data set, check if there is some data
                   11941:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11942: 
                   11943:     my $hashid="$udom:$uname";
                   11944:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11945:     if (!defined($cached)) {
                   11946: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11947: 	$result=\%resourcedata;
                   11948: 	&do_cache_new('userres',$hashid,$result,600);
                   11949:     }
                   11950:     my ($tmp)=keys(%$result);
                   11951:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11952: 	return $result;
                   11953:     }
                   11954:     #error 2 occurs when the .db doesn't exist
                   11955:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11956:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11957: 	    &logthis("<font color=\"blue\">WARNING:".
                   11958: 		     " Trying to get resource data for ".
                   11959: 		     $uname." at ".$udom.": ".
                   11960: 		     $tmp."</font>");
                   11961:         }
1.624     albertel 11962:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11963: 	#&EXT_cache_set($udom,$uname);
                   11964: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11965: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11966:     }
                   11967:     return $tmp;
                   11968: }
1.879     foxr     11969: #----------------------------------------------- resdata - return resource data
                   11970: #  Purpose:
                   11971: #    Return resource data for either users or for a course.
                   11972: #  Parameters:
                   11973: #     $name      - Course/user name.
                   11974: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11975: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11976: #     $mapp      - decluttered URL of enclosing map  
                   11977: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11978: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11979: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11980: #     $courseid  - CourseID (first part of param identifier).
                   11981: #     $modifier  - Middle part of param identifier.
                   11982: #     $what      - Last part of param identifier.
1.879     foxr     11983: #     @which     - Array of names of resources desired.
                   11984: #  Returns:
                   11985: #     The value of the first reasource in @which that is found in the
                   11986: #     resource hash.
                   11987: #  Exceptional Conditions:
                   11988: #     If the $type passed in is not valid (not the string 'course' or 
                   11989: #     'user', an undefined  reference is returned.
                   11990: #     If none of the resources are found, an undef is returned
1.624     albertel 11991: sub resdata {
1.1301    raeburn  11992:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11993:         $modifier,$what,@which)=@_;
1.624     albertel 11994:     my $result;
                   11995:     if ($type eq 'course') {
                   11996: 	$result=&get_courseresdata($name,$domain);
                   11997:     } elsif ($type eq 'user') {
                   11998: 	$result=&get_userresdata($name,$domain);
                   11999:     }
                   12000:     if (!ref($result)) { return $result; }    
1.251     albertel 12001:     foreach my $item (@which) {
1.1301    raeburn  12002:         if ($item->[1] eq 'course') {
                   12003:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12004:                 unless ($$recursed) {
1.1302    raeburn  12005:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12006:                     $$recursed = 1;
                   12007:                 }
                   12008:                 foreach my $item (@${recurseup}) {
                   12009:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12010:                     last if (defined($result->{$norecursechk}));
                   12011:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12012:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12013:                 }
                   12014:             }
                   12015:         }
                   12016:         if (defined($result->{$item->[0]})) {
1.927     albertel 12017: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12018: 	}
1.250     albertel 12019:     }
1.291     albertel 12020:     return undef;
1.200     www      12021: }
                   12022: 
1.1360    raeburn  12023: sub get_domain_lti {
                   12024:     my ($cdom,$context) = @_;
                   12025:     my ($name,%lti);
                   12026:     if ($context eq 'consumer') {
                   12027:         $name = 'ltitools';
                   12028:     } elsif ($context eq 'provider') {
                   12029:         $name = 'lti';
                   12030:     } else {
                   12031:         return %lti;
                   12032:     }
                   12033:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  12034:     if (defined($cached)) {
                   12035:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12036:             %lti = %{$result};
1.1298    raeburn  12037:         }
                   12038:     } else {
1.1360    raeburn  12039:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12040:         if (ref($domconfig{$name}) eq 'HASH') {
                   12041:             %lti = %{$domconfig{$name}};
                   12042:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   12043:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   12044:                 foreach my $id (keys(%lti)) {
                   12045:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  12046:                         foreach my $item ('key','secret') {
1.1360    raeburn  12047:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  12048:                         }
                   12049:                     }
                   12050:                 }
                   12051:             }
1.1298    raeburn  12052:         }
                   12053:         my $cachetime = 24*60*60;
1.1360    raeburn  12054:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  12055:     }
1.1360    raeburn  12056:     return %lti;
1.1298    raeburn  12057: }
                   12058: 
1.1236    raeburn  12059: sub get_numsuppfiles {
                   12060:     my ($cnum,$cdom,$ignorecache)=@_;
                   12061:     my $hashid=$cnum.':'.$cdom;
                   12062:     my ($suppcount,$cached);
                   12063:     unless ($ignorecache) {
                   12064:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   12065:     }
                   12066:     unless (defined($cached)) {
                   12067:         my $chome=&homeserver($cnum,$cdom);
                   12068:         unless ($chome eq 'no_host') {
1.1366    raeburn  12069:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  12070:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  12071:             ($suppcount,$supptools,$errors) =
                   12072:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   12073:                                                          $supptools,$errors);
1.1236    raeburn  12074:         }
                   12075:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   12076:     }
                   12077:     return $suppcount;
                   12078: }
                   12079: 
1.379     matthew  12080: #
                   12081: # EXT resource caching routines
                   12082: #
                   12083: 
1.1302    raeburn  12084: {
                   12085: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12086: #
                   12087: # The course for which we cache
                   12088: my $cachedmapkey='';
                   12089: # The cached recursive maps for this course
                   12090: my %cachedmaps=();
                   12091: # When this was last done
                   12092: my $cachedmaptime='';
                   12093: 
1.379     matthew  12094: sub clear_EXT_cache_status {
1.383     albertel 12095:     &delenv('cache.EXT.');
1.379     matthew  12096: }
                   12097: 
                   12098: sub EXT_cache_status {
                   12099:     my ($target_domain,$target_user) = @_;
1.383     albertel 12100:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12101:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12102:         # We know already the user has no data
                   12103:         return 1;
                   12104:     } else {
                   12105:         return 0;
                   12106:     }
                   12107: }
                   12108: 
                   12109: sub EXT_cache_set {
                   12110:     my ($target_domain,$target_user) = @_;
1.383     albertel 12111:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12112:     #&appenv({$cachename => time});
1.379     matthew  12113: }
                   12114: 
1.28      www      12115: # --------------------------------------------------------- Value of a Variable
1.58      www      12116: sub EXT {
1.715     albertel 12117: 
1.1228    raeburn  12118:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12119:     unless ($varname) { return ''; }
1.218     albertel 12120:     #get real user name/domain, courseid and symb
                   12121:     my $courseid;
1.359     albertel 12122:     my $publicuser;
1.427     www      12123:     if ($symbparm) {
                   12124: 	$symbparm=&get_symb_from_alias($symbparm);
                   12125:     }
1.218     albertel 12126:     if (!($uname && $udom)) {
1.790     albertel 12127:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12128:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12129:     } else {
1.620     albertel 12130: 	$courseid=$env{'request.course.id'};
1.218     albertel 12131:     }
1.48      www      12132:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12133:     my $rest;
1.320     albertel 12134:     if (defined($therest[0])) {
1.48      www      12135:        $rest=join('.',@therest);
                   12136:     } else {
                   12137:        $rest='';
                   12138:     }
1.320     albertel 12139: 
1.57      www      12140:     my $qualifierrest=$qualifier;
                   12141:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12142:     my $spacequalifierrest=$space;
                   12143:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12144:     if ($realm eq 'user') {
1.48      www      12145: # --------------------------------------------------------------- user.resource
                   12146: 	if ($space eq 'resource') {
1.651     albertel 12147: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12148: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12149: 		 &&
1.744     albertel 12150: 		 ($symbparm eq &symbread()) ) {	
                   12151: 		# if we are in the middle of processing the resource the
                   12152: 		# get the value we are planning on committing
                   12153:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12154:                     return $Apache::lonhomework::results{$qualifierrest};
                   12155:                 } else {
                   12156:                     return $Apache::lonhomework::history{$qualifierrest};
                   12157:                 }
1.335     albertel 12158: 	    } else {
1.359     albertel 12159: 		my %restored;
1.620     albertel 12160: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12161: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12162: 		} else {
                   12163: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12164: 		}
1.335     albertel 12165: 		return $restored{$qualifierrest};
                   12166: 	    }
1.48      www      12167: # ----------------------------------------------------------------- user.access
                   12168:         } elsif ($space eq 'access') {
1.218     albertel 12169: 	    # FIXME - not supporting calls for a specific user
1.48      www      12170:             return &allowed($qualifier,$rest);
                   12171: # ------------------------------------------ user.preferences, user.environment
                   12172:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12173: 	    if (($uname eq $env{'user.name'}) &&
                   12174: 		($udom eq $env{'user.domain'})) {
                   12175: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12176: 	    } else {
1.359     albertel 12177: 		my %returnhash;
                   12178: 		if (!$publicuser) {
                   12179: 		    %returnhash=&userenvironment($udom,$uname,
                   12180: 						 $qualifierrest);
                   12181: 		}
1.218     albertel 12182: 		return $returnhash{$qualifierrest};
                   12183: 	    }
1.48      www      12184: # ----------------------------------------------------------------- user.course
                   12185:         } elsif ($space eq 'course') {
1.218     albertel 12186: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12187:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12188: # ------------------------------------------------------------------- user.role
                   12189:         } elsif ($space eq 'role') {
1.218     albertel 12190: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12191:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12192:             if ($qualifier eq 'value') {
                   12193: 		return $role;
                   12194:             } elsif ($qualifier eq 'extent') {
                   12195:                 return $where;
                   12196:             }
                   12197: # ----------------------------------------------------------------- user.domain
                   12198:         } elsif ($space eq 'domain') {
1.218     albertel 12199:             return $udom;
1.48      www      12200: # ------------------------------------------------------------------- user.name
                   12201:         } elsif ($space eq 'name') {
1.218     albertel 12202:             return $uname;
1.48      www      12203: # ---------------------------------------------------- Any other user namespace
1.29      www      12204:         } else {
1.359     albertel 12205: 	    my %reply;
                   12206: 	    if (!$publicuser) {
                   12207: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12208: 	    }
                   12209: 	    return $reply{$qualifierrest};
1.48      www      12210:         }
1.236     www      12211:     } elsif ($realm eq 'query') {
                   12212: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12213:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12214: 						[$spacequalifierrest]);
1.620     albertel 12215: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12216:    } elsif ($realm eq 'request') {
1.48      www      12217: # ------------------------------------------------------------- request.browser
                   12218:         if ($space eq 'browser') {
1.1145    bisitz   12219:             return $env{'browser.'.$qualifier};
1.57      www      12220: # ------------------------------------------------------------ request.filename
                   12221:         } else {
1.620     albertel 12222:             return $env{'request.'.$spacequalifierrest};
1.29      www      12223:         }
1.28      www      12224:     } elsif ($realm eq 'course') {
1.48      www      12225: # ---------------------------------------------------------- course.description
1.620     albertel 12226:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12227:     } elsif ($realm eq 'resource') {
1.165     www      12228: 
1.620     albertel 12229: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12230: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12231: 	}
1.693     albertel 12232: 
1.1232    raeburn  12233:         if ($qualifier eq '') {
                   12234: 	    if ($space eq 'title') {
                   12235: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12236: 	        return &gettitle($symbparm);
                   12237: 	    }
1.693     albertel 12238: 	
1.1232    raeburn  12239: 	    if ($space eq 'map') {
                   12240: 	        my ($map) = &decode_symb($symbparm);
                   12241: 	        return &symbread($map);
                   12242: 	    }
                   12243:             if ($space eq 'maptitle') {
                   12244:                 my ($map) = &decode_symb($symbparm);
                   12245:                 return &gettitle($map);
                   12246:             }
                   12247: 	    if ($space eq 'filename') {
                   12248: 	        if ($symbparm) {
                   12249: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12250: 	        }
                   12251: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12252: 	    }
1.1232    raeburn  12253: 
1.1233    raeburn  12254:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12255:                 if ($space eq 'visibleparts') {
                   12256:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12257:                     my $item;
                   12258:                     if (ref($navmap)) {
                   12259:                         my $res = $navmap->getBySymb($symbparm);
                   12260:                         my $parts = $res->parts();
                   12261:                         if (ref($parts) eq 'ARRAY') {
                   12262:                             $item = join(',',@{$parts});
                   12263:                         }
                   12264:                         undef($navmap);
1.1232    raeburn  12265:                     }
1.1233    raeburn  12266:                     return $item;
1.1232    raeburn  12267:                 }
                   12268:             }
                   12269:         }
1.693     albertel 12270: 
1.1301    raeburn  12271: 	my ($section, $group, @groups, @recurseup, $recursed);
                   12272: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12273:         if (($courseid eq '') && ($cid)) {
                   12274:             $courseid = $cid;
                   12275:         }
                   12276: 	if (($symbparm && $courseid) && 
                   12277: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12278: 
1.218     albertel 12279: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12280: 
1.60      www      12281: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12282: 	    my $symbp=$symbparm;
1.1301    raeburn  12283: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12284: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12285:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12286: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12287: 	    if (($env{'user.name'} eq $uname) &&
                   12288: 		($env{'user.domain'} eq $udom)) {
                   12289: 		$section=$env{'request.course.sec'};
1.733     raeburn  12290:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12291:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12292: 	    } else {
1.539     albertel 12293: 		if (! defined($usection)) {
1.551     albertel 12294: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12295: 		} else {
                   12296: 		    $section = $usection;
                   12297: 		}
1.733     raeburn  12298:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12299: 	    }
                   12300: 
                   12301: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12302: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12303:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12304: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12305: 
1.593     albertel 12306: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12307: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12308:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12309: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12310: 
1.60      www      12311: # ----------------------------------------------------------- first, check user
1.624     albertel 12312: 
1.1301    raeburn  12313: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12314:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12315: 				       ([$courselevelr,'resource'],
                   12316: 					[$courselevelm,'map'     ],
1.1301    raeburn  12317:                                         [$courseleveli,'map'     ],
1.927     albertel 12318: 					[$courselevel, 'course'  ]));
1.931     albertel 12319: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12320: 
1.594     albertel 12321: # ------------------------------------------------ second, check some of course
1.684     raeburn  12322:             my $coursereply;
1.691     raeburn  12323:             if (@groups > 0) {
                   12324:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12325:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12326:                                        $mapp,\$recursed,\@recurseup);
                   12327:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12328:             }
1.96      www      12329: 
1.684     raeburn  12330: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12331: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12332: 				  'course',$mapp,\$recursed,\@recurseup,
                   12333:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12334: 				  ([$seclevelr,   'resource'],
                   12335: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12336:                                    [$secleveli,   'map'     ],
1.927     albertel 12337: 				   [$seclevel,    'course'  ],
                   12338: 				   [$courselevelr,'resource']));
                   12339: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12340: 
1.60      www      12341: # ------------------------------------------------------ third, check map parms
1.218     albertel 12342: 	    my %parmhash=();
                   12343: 	    my $thisparm='';
                   12344: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12345: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12346: 		    &GDBM_READER(),0640)) {
1.218     albertel 12347: 		$thisparm=$parmhash{$symbparm};
                   12348: 		untie(%parmhash);
                   12349: 	    }
1.927     albertel 12350: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12351: 	}
1.594     albertel 12352: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12353:  
                   12354:         my $what = $spacequalifierrest;
                   12355: 	$what=~s/\./\_/;
1.282     albertel 12356: 	my $filename;
                   12357: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12358: 	if ($symbparm) {
1.409     www      12359: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12360: 	} else {
1.620     albertel 12361: 	    $filename=$env{'request.filename'};
1.282     albertel 12362: 	}
1.1362    raeburn  12363:         my $toolsymb;
                   12364:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12365:             $toolsymb = $symbparm;
                   12366:         }
                   12367: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12368: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12369: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12370: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12371: 
1.1301    raeburn  12372: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12373: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12374: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12375: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12376: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12377: 				     'course',$mapp,\$recursed,\@recurseup,
                   12378:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12379: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12380:                                       [$courseleveli,'map'   ],
1.927     albertel 12381: 				      [$courselevel, 'course']));
                   12382: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12383: 	}
1.145     www      12384: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12385: 	unless ($space eq '0') {
1.336     albertel 12386: 	    my @parts=split(/_/,$space);
                   12387: 	    my $id=pop(@parts);
                   12388: 	    my $part=join('_',@parts);
                   12389: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12390: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12391: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12392: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12393: 	}
1.395     albertel 12394: 	if ($recurse) { return undef; }
1.1362    raeburn  12395: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12396: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12397: # ---------------------------------------------------- Any other user namespace
                   12398:     } elsif ($realm eq 'environment') {
                   12399: # ----------------------------------------------------------------- environment
1.620     albertel 12400: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12401: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12402: 	} else {
1.770     albertel 12403: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12404: 		return '';
                   12405: 	    }
1.219     albertel 12406: 	    my %returnhash=&userenvironment($udom,$uname,
                   12407: 					    $spacequalifierrest);
                   12408: 	    return $returnhash{$spacequalifierrest};
                   12409: 	}
1.28      www      12410:     } elsif ($realm eq 'system') {
1.48      www      12411: # ----------------------------------------------------------------- system.time
                   12412: 	if ($space eq 'time') {
                   12413: 	    return time;
                   12414:         }
1.696     albertel 12415:     } elsif ($realm eq 'server') {
                   12416: # ----------------------------------------------------------------- system.time
                   12417: 	if ($space eq 'name') {
                   12418: 	    return $ENV{'SERVER_NAME'};
                   12419:         }
1.1415    raeburn  12420:     } elsif ($realm eq 'client') {
                   12421:         if ($space eq 'remote_addr') {
                   12422:             return $ENV{'REMOTE_ADDR'};
                   12423:         }
1.28      www      12424:     }
1.48      www      12425:     return '';
1.61      www      12426: }
                   12427: 
1.927     albertel 12428: sub get_reply {
                   12429:     my ($reply_value) = @_;
1.940     raeburn  12430:     if (ref($reply_value) eq 'ARRAY') {
                   12431:         if (wantarray) {
                   12432: 	    return @$reply_value;
                   12433:         }
                   12434:         return $reply_value->[0];
                   12435:     } else {
                   12436:         return $reply_value;
1.927     albertel 12437:     }
                   12438: }
                   12439: 
1.691     raeburn  12440: sub check_group_parms {
1.1301    raeburn  12441:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12442:         $recursed,$recurseupref) = @_;
                   12443:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12444:                   [$what,'course']);
                   12445:     my $coursereply;
1.691     raeburn  12446:     foreach my $group (@{$groups}) {
1.1301    raeburn  12447:         my @groupitems = ();
1.691     raeburn  12448:         foreach my $level (@levels) {
1.927     albertel 12449:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12450:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12451:         }
1.1301    raeburn  12452:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12453:                                    $env{'course.'.$courseid.'.domain'},
                   12454:                                    'course',$mapp,$recursed,$recurseupref,
                   12455:                                    $courseid,'.['.$group.'].',$what,
                   12456:                                    @groupitems);
                   12457:         last if (defined($coursereply));
1.691     raeburn  12458:     }
                   12459:     return $coursereply;
                   12460: }
                   12461: 
1.1301    raeburn  12462: sub get_map_hierarchy {
1.1302    raeburn  12463:     my ($mapname,$courseid) = @_;
                   12464:     my @recurseup = ();
1.1301    raeburn  12465:     if ($mapname) {
1.1302    raeburn  12466:         if (($cachedmapkey eq $courseid) &&
                   12467:             (abs($cachedmaptime-time)<5)) {
                   12468:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12469:                 return @{$cachedmaps{$mapname}};
                   12470:             }
                   12471:         }
1.1301    raeburn  12472:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12473:         if (ref($navmap)) {
                   12474:             @recurseup = $navmap->recurseup_maps($mapname);
                   12475:             undef($navmap);
1.1302    raeburn  12476:             $cachedmaps{$mapname} = \@recurseup;
                   12477:             $cachedmaptime=time;
                   12478:             $cachedmapkey=$courseid;
1.1301    raeburn  12479:         }
                   12480:     }
                   12481:     return @recurseup;
                   12482: }
                   12483: 
1.1302    raeburn  12484: }
                   12485: 
1.691     raeburn  12486: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12487:     my ($courseid,@groups) = @_;
                   12488:     @groups = sort(@groups);
1.691     raeburn  12489:     return @groups;
                   12490: }
                   12491: 
1.395     albertel 12492: sub packages_tab_default {
1.1362    raeburn  12493:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12494:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12495: 
                   12496:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12497:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12498: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12499: 	if ($pack_type eq 'default') {
                   12500: 	    $do_default=1;
                   12501: 	} elsif ($pack_type eq 'extension') {
                   12502: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12503: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12504: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12505: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12506: 	}
                   12507:     }
                   12508:     # first look for a package that matches the requested part id
                   12509:     foreach my $package (@specifics) {
                   12510: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12511: 	next if ($pack_part ne $part);
                   12512: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12513: 	    return $packagetab{"$pack_type&$name&default"};
                   12514: 	}
                   12515:     }
                   12516:     # look for any possible matching non extension_ package
                   12517:     foreach my $package (@specifics) {
                   12518: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12519: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12520: 	    return $packagetab{"$pack_type&$name&default"};
                   12521: 	}
1.585     albertel 12522: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12523: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12524: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12525: 	}
                   12526:     }
1.738     albertel 12527:     # look for any posible extension_ match
                   12528:     foreach my $package (@extension) {
                   12529: 	my ($package,$pack_type)=@{$package};
                   12530: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12531: 	    return $packagetab{"$pack_type&$name&default"};
                   12532: 	}
                   12533: 	if (defined($packagetab{$package."&$name&default"})) {
                   12534: 	    return $packagetab{$package."&$name&default"};
                   12535: 	}
                   12536:     }
                   12537:     # look for a global default setting
                   12538:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12539: 	return $packagetab{"default&$name&default"};
                   12540:     }
1.395     albertel 12541:     return undef;
                   12542: }
                   12543: 
1.334     albertel 12544: sub add_prefix_and_part {
                   12545:     my ($prefix,$part)=@_;
                   12546:     my $keyroot;
                   12547:     if (defined($prefix) && $prefix !~ /^__/) {
                   12548: 	# prefix that has a part already
                   12549: 	$keyroot=$prefix;
                   12550:     } elsif (defined($prefix)) {
                   12551: 	# prefix that is missing a part
                   12552: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12553:     } else {
                   12554: 	# no prefix at all
                   12555: 	if (defined($part)) { $keyroot='_'.$part; }
                   12556:     }
                   12557:     return $keyroot;
                   12558: }
                   12559: 
1.71      www      12560: # ---------------------------------------------------------------- Get metadata
                   12561: 
1.599     albertel 12562: my %metaentry;
1.1070    www      12563: my %importedpartids;
1.1369    raeburn  12564: my %importedrespids;
1.71      www      12565: sub metadata {
1.1362    raeburn  12566:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12567:     $uri=&declutter($uri);
1.288     albertel 12568:     # if it is a non metadata possible uri return quickly
1.529     albertel 12569:     if (($uri eq '') || 
                   12570: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12571: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12572:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12573: 	return undef;
                   12574:     }
1.1261    raeburn  12575:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12576: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12577: 	return undef;
1.288     albertel 12578:     }
1.73      www      12579:     my $filename=$uri;
                   12580:     $uri=~s/\.meta$//;
1.172     www      12581: #
                   12582: # Is the metadata already cached?
1.177     www      12583: # Look at timestamp of caching
1.172     www      12584: # Everything is cached by the main uri, libraries are never directly cached
                   12585: #
1.428     albertel 12586:     if (!defined($liburi)) {
1.599     albertel 12587: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12588: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12589:     }
1.1362    raeburn  12590: 
                   12591: #
                   12592: # If the uri is for an external tool the file from
                   12593: # which metadata should be retrieved depends on whether
                   12594: # the tool had been configured to be gradable (set in the Course
                   12595: # Editor or Resource Editor).
                   12596: #
                   12597: # If a valid symb has been included as the third arg in the call
                   12598: # to &metadata() that can be used to retrieve the value of
                   12599: # parameter_0_gradable set for the resource, and included in the
                   12600: # uploaded map containing the tool. The value is retrieved via
                   12601: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12602: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12603: # is retrieved via &get().
                   12604: #
                   12605: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12606: # hiddenresource and encrypturl (during course initialization)
                   12607: # the map-level parameter for resource.0.gradable included in the 
                   12608: # uploaded map containing the tool will not yet have been stored
                   12609: # in the user_course_parms.db file for the user's session, so in 
                   12610: # this case fall back to retrieving gradable status from the
                   12611: # exttool_$marker.db file.
1.1362    raeburn  12612: #
                   12613: # In order to avoid an infinite loop, &metadata() will return
                   12614: # before a call to &EXT(), if the uri is for an external tool
                   12615: # and the $what for which metadata is being requested is
                   12616: # parameter_0_gradable or 0_gradable.
                   12617: #
                   12618: 
                   12619:     if ($uri =~ /ext\.tool$/) {
                   12620:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12621:             return;
                   12622:         } else {
                   12623:             my ($checked,$use_passback);
                   12624:             if ($toolsymb ne '') {
                   12625:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12626:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12627:                     $checked = 1;
                   12628:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12629:                         $use_passback = 1;
                   12630:                     }
                   12631:                 }
                   12632:             }
                   12633:             unless ($checked) {
                   12634:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12635:                 $marker=~s/\D//g;
1.1363    raeburn  12636:                 if ($marker) {
1.1362    raeburn  12637:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12638:                     $use_passback = $toolsettings{'gradable'};
                   12639:                 }
                   12640:             }
                   12641:             if ($use_passback) {
                   12642:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12643:             } else {
                   12644:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12645:             }
                   12646:         }
                   12647:     }
                   12648: 
1.428     albertel 12649:     {
1.1069    www      12650: # Imported parts would go here
1.1369    raeburn  12651:         my @origfiletagids=();
1.1069    www      12652:         my $importedparts=0;
1.1369    raeburn  12653: 
                   12654: # Imported responseids would go here
                   12655:         my $importedresponses=0;
1.172     www      12656: #
                   12657: # Is this a recursive call for a library?
                   12658: #
1.599     albertel 12659: #	if (! exists($metacache{$uri})) {
                   12660: #	    $metacache{$uri}={};
                   12661: #	}
1.924     albertel 12662: 	my $cachetime = 60*60;
1.171     www      12663:         if ($liburi) {
                   12664: 	    $liburi=&declutter($liburi);
                   12665:             $filename=$liburi;
1.401     bowersj2 12666:         } else {
1.599     albertel 12667: 	    &devalidate_cache_new('meta',$uri);
                   12668: 	    undef(%metaentry);
1.401     bowersj2 12669: 	}
1.140     www      12670:         my %metathesekeys=();
1.73      www      12671:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12672: 	my $metastring;
1.1140    www      12673: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12674: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12675: 	    $metastring = 
1.929     albertel 12676: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12677: 					  ('grade_target' => 'meta'));
                   12678: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12679: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12680:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12681: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12682: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12683: 	    $metastring=&getfile($file);
1.489     albertel 12684: 	}
1.208     albertel 12685:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12686:         my $token;
1.140     www      12687:         undef %metathesekeys;
1.71      www      12688:         while ($token=$parser->get_token) {
1.339     albertel 12689: 	    if ($token->[0] eq 'S') {
                   12690: 		if (defined($token->[2]->{'package'})) {
1.172     www      12691: #
                   12692: # This is a package - get package info
                   12693: #
1.339     albertel 12694: 		    my $package=$token->[2]->{'package'};
                   12695: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12696: 		    if (defined($token->[2]->{'id'})) { 
                   12697: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12698: 		    }
1.599     albertel 12699: 		    if ($metaentry{':packages'}) {
                   12700: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12701: 		    } else {
1.599     albertel 12702: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12703: 		    }
1.736     albertel 12704: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12705: 			my $part=$keyroot;
                   12706: 			$part=~s/^\_//;
1.736     albertel 12707: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12708: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12709: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12710: 			    # ignore package.tab specified default values
                   12711:                             # here &package_tab_default() will fetch those
                   12712: 			    if ($subp eq 'default') { next; }
1.736     albertel 12713: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12714: 			    my $unikey;
                   12715: 			    if ($pack =~ /_0$/) {
                   12716: 				$unikey='parameter_0_'.$name;
                   12717: 				$part=0;
                   12718: 			    } else {
                   12719: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12720: 			    }
1.339     albertel 12721: 			    if ($subp eq 'display') {
                   12722: 				$value.=' [Part: '.$part.']';
                   12723: 			    }
1.599     albertel 12724: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12725: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12726: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12727: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12728: 			    }
1.599     albertel 12729: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12730: 				$metaentry{':'.$unikey}=
                   12731: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12732: 			    }
1.339     albertel 12733: 			}
                   12734: 		    }
                   12735: 		} else {
1.172     www      12736: #
                   12737: # This is not a package - some other kind of start tag
1.339     albertel 12738: #
                   12739: 		    my $entry=$token->[1];
1.1068    www      12740: 		    my $unikey='';
1.175     www      12741: 
1.339     albertel 12742: 		    if ($entry eq 'import') {
1.175     www      12743: #
                   12744: # Importing a library here
1.339     albertel 12745: #
1.1067    www      12746:                         my $location=$parser->get_text('/import');
                   12747:                         my $dir=$filename;
                   12748:                         $dir=~s|[^/]*$||;
                   12749:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12750: 
                   12751:                         my $importid=$token->[2]->{'id'};
1.1068    www      12752:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12753: #
                   12754: # Check metadata for imported file to
                   12755: # see if it contained response items
                   12756: #
1.1372    raeburn  12757:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12758:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12759:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12760:                                                            $depthcount+1));
                   12761:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12762:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12763:                                                              undef,$depthcount+1);
                   12764:                             if ($libresponseorder ne '') {
                   12765:                                 if ($#origfiletagids<0) {
                   12766:                                     undef(%importedrespids);
                   12767:                                     undef(%importedpartids);
                   12768:                                 }
1.1373    raeburn  12769:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12770:                                 if (@respids) {
                   12771:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12772:                                 }
                   12773:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12774:                                     $importedresponses = 1;
1.1369    raeburn  12775: # We need to get the original file and the imported file to get the response order correct
                   12776: # Load and inspect original file
1.1372    raeburn  12777:                                     if ($#origfiletagids<0) {
                   12778:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12779:                                         $origfile=&getfile($origfilelocation);
                   12780:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12781:                                     }
1.1369    raeburn  12782:                                 }
                   12783:                             }
                   12784:                         }
1.1370    raeburn  12785: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12786: # hash populated for imported library file
                   12787:                         %metaentry = %currmetaentry;
                   12788:                         undef(%currmetaentry);
1.1374    raeburn  12789:                         if ($importmode eq 'part') {
1.1068    www      12790: # Import as part(s)
1.1069    www      12791:                            $importedparts=1;
                   12792: # We need to get the original file and the imported file to get the part order correct
                   12793: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12794: # Load and inspect original file if we didn't do that already
                   12795:                            if ($#origfiletagids<0) {
                   12796:                                undef(%importedrespids);
                   12797:                                undef(%importedpartids);
                   12798:                                if ($origfile eq '') {
                   12799:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12800:                                    $origfile=&getfile($origfilelocation);
                   12801:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12802:                                }
1.1070    www      12803:                            }
1.1372    raeburn  12804:                            my @impfilepartids;
                   12805: # If <partorder> tag is included in metadata for the imported file
                   12806: # get the parts in the imported file from that.
                   12807:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12808:                                %currmetaentry = %metaentry;
                   12809:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12810:                                                             $depthcount+1);
                   12811:                                %metaentry = %currmetaentry;
                   12812:                                undef(%currmetaentry);
                   12813:                                if ($libpartorder ne '') {
                   12814:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12815:                                }
                   12816:                            } else {
                   12817: # If no <partorder> tag available, load and inspect imported file
                   12818:                                my $impfile=&getfile($location);
                   12819:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12820:                            }
1.1069    www      12821:                            if ($#impfilepartids>=0) {
                   12822: # This problem had parts
1.1070    www      12823:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12824:                            } else {
                   12825: # Importing by turning a single problem into a problem part
                   12826: # It gets the import-tags ID as part-ID
                   12827:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12828:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12829:                            }
1.1068    www      12830:                         } else {
1.1374    raeburn  12831: # Import as problem or as normal import
                   12832:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12833:                             unless ($importmode eq 'problem') {
1.1068    www      12834: # Normal import
1.1374    raeburn  12835:                                 if (defined($token->[2]->{'id'})) {
                   12836:                                     $unikey.='_'.$token->[2]->{'id'};
                   12837:                                 }
                   12838:                             }
                   12839: # Check metadata for imported file to
                   12840: # see if it contained parts
                   12841:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12842:                                 %currmetaentry = %metaentry;
                   12843:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12844:                                                              $depthcount+1);
                   12845:                                 %metaentry = %currmetaentry;
                   12846:                                 undef(%currmetaentry);
                   12847:                                 if ($libpartorder ne '') {
                   12848:                                     $importedparts = 1;
                   12849:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12850:                                 }
                   12851:                             }
1.1067    www      12852:                         }
1.339     albertel 12853: 			if ($depthcount<20) {
1.736     albertel 12854: 			    my $metadata = 
1.1362    raeburn  12855: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12856: 					  $depthcount+1);
                   12857: 			    foreach my $meta (split(',',$metadata)) {
                   12858: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12859: 				$metathesekeys{$meta}=1;
1.339     albertel 12860: 			    }
1.1068    www      12861:                         }
1.1067    www      12862: 		    } else {
                   12863: #
                   12864: # Not importing, some other kind of non-package, non-library start tag
                   12865: # 
                   12866:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12867:                         if (defined($token->[2]->{'id'})) {
                   12868:                             $unikey.='_'.$token->[2]->{'id'};
                   12869:                         }
1.339     albertel 12870: 			if (defined($token->[2]->{'name'})) { 
                   12871: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12872: 			}
                   12873: 			$metathesekeys{$unikey}=1;
1.736     albertel 12874: 			foreach my $param (@{$token->[3]}) {
                   12875: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12876: 				$token->[2]->{$param};
1.339     albertel 12877: 			}
                   12878: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12879: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12880: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12881: 		 # only ws inside the tag, and not in default, so use default
                   12882: 		 # as value
1.599     albertel 12883: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12884: 			} elsif ( $internaltext =~ /\S/ ) {
                   12885: 		  # something interesting inside the tag
                   12886: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12887: 			} else {
1.908     albertel 12888: 		  # no interesting values, don't set a default
1.339     albertel 12889: 			}
1.172     www      12890: # end of not-a-package not-a-library import
1.339     albertel 12891: 		    }
1.172     www      12892: # end of not-a-package start tag
1.339     albertel 12893: 		}
1.172     www      12894: # the next is the end of "start tag"
1.339     albertel 12895: 	    }
                   12896: 	}
1.483     albertel 12897: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12898: 	$extension = lc($extension);
                   12899: 	if ($extension eq 'htm') { $extension='html'; }
                   12900: 
1.737     albertel 12901: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12902: 	    #no specific packages #how's our extension
                   12903: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12904: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12905: 					 \%metathesekeys);
                   12906: 	}
1.883     albertel 12907: 
                   12908: 	if (!exists($metaentry{':packages'})
                   12909: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12910: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12911: 		#no specific packages well let's get default then
                   12912: 		if ($key!~/^default&/) { next; }
1.488     albertel 12913: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12914: 					     \%metathesekeys);
                   12915: 	    }
                   12916: 	}
1.338     www      12917: # are there custom rights to evaluate
1.599     albertel 12918: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12919: 
1.338     www      12920:     #
                   12921:     # Importing a rights file here
1.339     albertel 12922:     #
                   12923: 	    unless ($depthcount) {
1.599     albertel 12924: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12925: 		my $dir=$filename;
                   12926: 		$dir=~s|[^/]*$||;
                   12927: 		$location=&filelocation($dir,$location);
1.736     albertel 12928: 		my $rights_metadata =
1.1362    raeburn  12929: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12930: 			      $depthcount+1);
                   12931: 		foreach my $rights (split(',',$rights_metadata)) {
                   12932: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12933: 		    $metathesekeys{$rights}=1;
1.339     albertel 12934: 		}
                   12935: 	    }
                   12936: 	}
1.737     albertel 12937: 	# uniqifiy package listing
                   12938: 	my %seen;
                   12939: 	my @uniq_packages =
                   12940: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12941: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12942: 
1.1369    raeburn  12943:         if (($importedresponses) || ($importedparts)) {
                   12944:             if ($importedparts) {
1.1070    www      12945: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12946:                 $metaentry{':partorder'}='';
                   12947:                 $metathesekeys{'partorder'}=1;
                   12948:             }
                   12949:             if ($importedresponses) {
                   12950: # We had imported responses and need to rebuil responseorder
                   12951:                 $metaentry{':responseorder'}='';
                   12952:                 $metathesekeys{'responseorder'}=1;
                   12953:             }
                   12954:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12955:                 my $origid = $origfiletagids[$index+1];
                   12956:                 if ($origfiletagids[$index] eq 'part') {
                   12957: # Original part, part of the problem
                   12958:                     if ($importedparts) {
                   12959:                         $metaentry{':partorder'}.=','.$origid;
                   12960:                     }
                   12961:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12962:                     if ($importedparts) {
                   12963: # We have imported parts at this position
1.1373    raeburn  12964:                         if ($importedpartids{$origid} ne '') {
                   12965:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12966:                         }
1.1369    raeburn  12967:                     }
                   12968:                     if ($importedresponses) {
                   12969: # We have imported responses at this position
1.1373    raeburn  12970:                         if ($importedrespids{$origid} ne '') {
                   12971:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12972:                         }
                   12973:                     }
                   12974:                 } else {
                   12975: # Original response item, part of the problem
                   12976:                     if ($importedresponses) {
                   12977:                         $metaentry{':responseorder'}.=','.$origid;
                   12978:                     }
                   12979:                 }
                   12980:             }
                   12981:             if ($importedparts) {
                   12982:                 $metaentry{':partorder'}=~s/^\,//;
                   12983:             }
                   12984:             if ($importedresponses) {
                   12985:                 $metaentry{':responseorder'}=~s/^\,//;
                   12986:             }
1.1070    www      12987:         }
1.737     albertel 12988: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12989: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12990: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12991:         unless ($liburi) {
                   12992: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12993:         }
1.177     www      12994: # this is the end of "was not already recently cached
1.71      www      12995:     }
1.599     albertel 12996:     return $metaentry{':'.$what};
1.261     albertel 12997: }
                   12998: 
1.488     albertel 12999: sub metadata_create_package_def {
1.483     albertel 13000:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13001:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13002:     if ($subp eq 'default') { next; }
                   13003:     
1.599     albertel 13004:     if (defined($metaentry{':packages'})) {
                   13005: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13006:     } else {
1.599     albertel 13007: 	$metaentry{':packages'}=$package;
1.483     albertel 13008:     }
                   13009:     my $value=$packagetab{$key};
                   13010:     my $unikey;
                   13011:     $unikey='parameter_0_'.$name;
1.599     albertel 13012:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13013:     $$metathesekeys{$unikey}=1;
1.599     albertel 13014:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13015: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13016:     }
1.599     albertel 13017:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13018: 	$metaentry{':'.$unikey}=
                   13019: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13020:     }
                   13021: }
                   13022: 
1.261     albertel 13023: sub metadata_generate_part0 {
                   13024:     my ($metadata,$metacache,$uri) = @_;
                   13025:     my %allnames;
1.737     albertel 13026:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13027: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13028: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13029: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13030: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13031: 	    $allnames{$name}=$part;
                   13032: 	  }
                   13033: 	}
                   13034:     }
                   13035:     foreach my $name (keys(%allnames)) {
                   13036:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13037:       my $key=":parameter_0_$name";
1.261     albertel 13038:       $$metacache{"$key.part"}='0';
                   13039:       $$metacache{"$key.name"}=$name;
1.428     albertel 13040:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13041: 					   $allnames{$name}.'_'.$name.
                   13042: 					   '.type'};
1.428     albertel 13043:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13044: 			     '.display'};
1.644     www      13045:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13046:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13047:       $$metacache{"$key.display"}=$olddis;
                   13048:     }
1.71      www      13049: }
                   13050: 
1.764     albertel 13051: # ------------------------------------------------------ Devalidate title cache
                   13052: 
                   13053: sub devalidate_title_cache {
                   13054:     my ($url)=@_;
                   13055:     if (!$env{'request.course.id'}) { return; }
                   13056:     my $symb=&symbread($url);
                   13057:     if (!$symb) { return; }
                   13058:     my $key=$env{'request.course.id'}."\0".$symb;
                   13059:     &devalidate_cache_new('title',$key);
                   13060: }
                   13061: 
1.1014    droeschl 13062: # ------------------------------------------------- Get the title of a course
                   13063: 
                   13064: sub current_course_title {
                   13065:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13066: }
1.301     www      13067: # ------------------------------------------------- Get the title of a resource
                   13068: 
                   13069: sub gettitle {
                   13070:     my $urlsymb=shift;
                   13071:     my $symb=&symbread($urlsymb);
1.534     albertel 13072:     if ($symb) {
1.620     albertel 13073: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13074: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13075: 	if (defined($cached)) { 
                   13076: 	    return $result;
                   13077: 	}
1.534     albertel 13078: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13079: 	my $title='';
1.907     albertel 13080: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13081: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13082: 	} else {
                   13083: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13084: 		    &GDBM_READER(),0640)) {
                   13085: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13086: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13087: 		untie(%bighash);
                   13088: 	    }
1.534     albertel 13089: 	}
                   13090: 	$title=~s/\&colon\;/\:/gs;
                   13091: 	if ($title) {
1.1159    www      13092: # Remember both $symb and $title for dynamic metadata
                   13093:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13094:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13095: # Cache this title and then return it
1.599     albertel 13096: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13097: 	}
                   13098: 	$urlsymb=$url;
                   13099:     }
                   13100:     my $title=&metadata($urlsymb,'title');
                   13101:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13102:     return $title;
1.301     www      13103: }
1.613     albertel 13104: 
1.614     albertel 13105: sub get_slot {
                   13106:     my ($which,$cnum,$cdom)=@_;
                   13107:     if (!$cnum || !$cdom) {
1.790     albertel 13108: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13109: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13110: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13111:     }
1.703     albertel 13112:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13113:     my %slotinfo;
                   13114:     if (exists($remembered{$key})) {
                   13115: 	$slotinfo{$which} = $remembered{$key};
                   13116:     } else {
                   13117: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13118: 	&Apache::lonhomework::showhash(%slotinfo);
                   13119: 	my ($tmp)=keys(%slotinfo);
                   13120: 	if ($tmp=~/^error:/) { return (); }
                   13121: 	$remembered{$key} = $slotinfo{$which};
                   13122:     }
1.616     albertel 13123:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13124: 	return %{$slotinfo{$which}};
                   13125:     }
                   13126:     return $slotinfo{$which};
1.614     albertel 13127: }
1.1150    raeburn  13128: 
                   13129: sub get_reservable_slots {
                   13130:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13131:     my $now = time;
                   13132:     my $reservable_info;
                   13133:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13134:     if (exists($remembered{$key})) {
                   13135:         $reservable_info = $remembered{$key};
                   13136:     } else {
                   13137:         my %resv;
                   13138:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13139:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13140:         $reservable_info = \%resv;
                   13141:         $remembered{$key} = $reservable_info;
                   13142:     }
                   13143:     return $reservable_info;
                   13144: }
                   13145: 
                   13146: sub get_course_slots {
                   13147:     my ($cnum,$cdom) = @_;
                   13148:     my $hashid=$cnum.':'.$cdom;
                   13149:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13150:     if (defined($cached)) {
                   13151:         if (ref($result) eq 'HASH') {
                   13152:             return %{$result};
                   13153:         }
                   13154:     } else {
                   13155:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13156:         my ($tmp) = keys(%slots);
                   13157:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13158:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13159:             return %slots;
                   13160:         }
                   13161:     }
                   13162:     return;
                   13163: }
                   13164: 
                   13165: sub devalidate_slots_cache {
                   13166:     my ($cnum,$cdom)=@_;
                   13167:     my $hashid=$cnum.':'.$cdom;
                   13168:     &devalidate_cache_new('allslots',$hashid);
                   13169: }
                   13170: 
1.1181    raeburn  13171: sub get_coursechange {
                   13172:     my ($cdom,$cnum) = @_;
                   13173:     if ($cdom eq '' || $cnum eq '') {
                   13174:         return unless ($env{'request.course.id'});
                   13175:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13176:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13177:     }
                   13178:     my $hashid=$cdom.'_'.$cnum;
                   13179:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13180:     if ((defined($cached)) && ($change ne '')) {
                   13181:         return $change;
                   13182:     } else {
                   13183:         my %crshash;
                   13184:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13185:         if ($crshash{'internal.contentchange'} eq '') {
                   13186:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13187:             if ($change eq '') {
                   13188:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13189:                 $change = $crshash{'internal.created'};
                   13190:             }
                   13191:         } else {
                   13192:             $change = $crshash{'internal.contentchange'};
                   13193:         }
                   13194:         my $cachetime = 600;
                   13195:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13196:     }
                   13197:     return $change;
                   13198: }
                   13199: 
                   13200: sub devalidate_coursechange_cache {
                   13201:     my ($cnum,$cdom)=@_;
                   13202:     my $hashid=$cnum.':'.$cdom;
                   13203:     &devalidate_cache_new('crschange',$hashid);
                   13204: }
                   13205: 
1.31      www      13206: # ------------------------------------------------- Update symbolic store links
                   13207: 
                   13208: sub symblist {
                   13209:     my ($mapname,%newhash)=@_;
1.438     www      13210:     $mapname=&deversion(&declutter($mapname));
1.31      www      13211:     my %hash;
1.620     albertel 13212:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13213:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13214:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13215: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13216: 		next if ($url eq 'last_known'
                   13217: 			 && $env{'form.no_update_last_known'});
                   13218: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13219: 						    $newhash{$url}->[1],
                   13220: 						    $newhash{$url}->[0]);
1.191     harris41 13221:             }
1.31      www      13222:             if (untie(%hash)) {
                   13223: 		return 'ok';
                   13224:             }
                   13225:         }
                   13226:     }
                   13227:     return 'error';
1.212     www      13228: }
                   13229: 
                   13230: # --------------------------------------------------------------- Verify a symb
                   13231: 
                   13232: sub symbverify {
1.1190    raeburn  13233:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13234:     my $thisfn=$thisurl;
1.439     www      13235:     $thisfn=&declutter($thisfn);
1.215     www      13236: # direct jump to resource in page or to a sequence - will construct own symbs
                   13237:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13238: # check URL part
1.409     www      13239:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13240: 
1.431     www      13241:     unless ($url eq $thisfn) { return 0; }
1.213     www      13242: 
1.216     www      13243:     $symb=&symbclean($symb);
1.510     www      13244:     $thisurl=&deversion($thisurl);
1.439     www      13245:     $thisfn=&deversion($thisfn);
1.213     www      13246: 
                   13247:     my %bighash;
                   13248:     my $okay=0;
1.431     www      13249: 
1.620     albertel 13250:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13251:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13252:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13253:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13254:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13255:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13256:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13257:             }
                   13258:         }
                   13259:         my $ids;
1.1419    raeburn  13260:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13261:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  13262:         } else {
                   13263:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13264:         }
1.1102    raeburn  13265:         unless ($ids) {
                   13266:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13267:             $ids=$bighash{$idkey};
1.216     www      13268:         }
                   13269:         if ($ids) {
                   13270: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13271:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13272:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13273:             }
1.800     albertel 13274: 	    foreach my $id (split(/\,/,$ids)) {
                   13275: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13276:                if (
                   13277:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13278:    eq $symb) {
                   13279:                    if (ref($encstate)) {
                   13280:                        $$encstate = $bighash{'encrypted_'.$id};
                   13281:                    }
1.620     albertel 13282: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13283: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13284:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13285: 		       $okay=1;
1.1202    raeburn  13286:                        last;
1.582     albertel 13287: 		   }
                   13288: 	       }
1.216     www      13289: 	   }
                   13290:         }
1.213     www      13291: 	untie(%bighash);
                   13292:     }
                   13293:     return $okay;
1.31      www      13294: }
                   13295: 
1.210     www      13296: # --------------------------------------------------------------- Clean-up symb
                   13297: 
                   13298: sub symbclean {
                   13299:     my $symb=shift;
1.568     albertel 13300:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13301: # remove version from map
                   13302:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13303: 
1.210     www      13304: # remove version from URL
                   13305:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13306: 
1.507     www      13307: # remove wrapper
                   13308: 
1.510     www      13309:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13310:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13311:     return $symb;
1.409     www      13312: }
                   13313: 
                   13314: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13315: 
                   13316: sub encode_symb {
                   13317:     my ($map,$resid,$url)=@_;
                   13318:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13319: }
1.409     www      13320: 
                   13321: sub decode_symb {
1.568     albertel 13322:     my $symb=shift;
                   13323:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13324:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13325:     return (&fixversion($map),$resid,&fixversion($url));
                   13326: }
                   13327: 
                   13328: sub fixversion {
                   13329:     my $fn=shift;
1.609     banghart 13330:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13331:     my %bighash;
                   13332:     my $uri=&clutter($fn);
1.620     albertel 13333:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13334: # is this cached?
1.599     albertel 13335:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13336:     if (defined($cached)) { return $result; }
                   13337: # unfortunately not cached, or expired
1.620     albertel 13338:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13339: 	    &GDBM_READER(),0640)) {
                   13340:  	if ($bighash{'version_'.$uri}) {
                   13341:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13342:  	    unless (($version eq 'mostrecent') || 
                   13343: 		    ($version==&getversion($uri))) {
1.440     www      13344:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13345:  	    }
                   13346:  	}
                   13347:  	untie %bighash;
1.413     www      13348:     }
1.599     albertel 13349:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13350: }
                   13351: 
                   13352: sub deversion {
                   13353:     my $url=shift;
                   13354:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13355:     return $url;
1.210     www      13356: }
                   13357: 
1.31      www      13358: # ------------------------------------------------------ Return symb list entry
                   13359: 
                   13360: sub symbread {
1.1424    raeburn  13361:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  13362:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  13363:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  13364:     if (defined($env{$cache_str})) {
1.1424    raeburn  13365:         unless (ref($possibles) eq 'HASH') {
                   13366:             if ($ignorecachednull) {
                   13367:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13368:             } else {
                   13369:                 return $env{$cache_str};
                   13370:             }
1.1282    raeburn  13371:         }
                   13372:     }
1.242     www      13373: # no filename provided? try from environment
1.1265    raeburn  13374:     unless ($thisfn) {
1.620     albertel 13375:         if ($env{'request.symb'}) {
1.1427    raeburn  13376:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13377: 	}
1.620     albertel 13378: 	$thisfn=$env{'request.filename'};
1.44      www      13379:     }
1.569     albertel 13380:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13381: # is that filename actually a symb? Verify, clean, and return
                   13382:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13383: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  13384: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13385: 	}
1.242     www      13386:     }
1.44      www      13387:     $thisfn=declutter($thisfn);
1.31      www      13388:     my %hash;
1.37      www      13389:     my %bighash;
                   13390:     my $syval='';
1.620     albertel 13391:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13392:         my $targetfn = $thisfn;
1.609     banghart 13393:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13394:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13395:         }
1.687     albertel 13396: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13397: 	    $targetfn=$1;
                   13398: 	}
1.1427    raeburn  13399:         unless ($ignoresymbdb) {
1.1424    raeburn  13400:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13401:                           &GDBM_READER(),0640)) {
                   13402: 	        $syval=$hash{$targetfn};
                   13403:                 untie(%hash);
                   13404:             }
1.1427    raeburn  13405:             if ($syval && $checkforblock) {
                   13406:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  13407:                 if (@blockers) {
                   13408:                     $syval='';
                   13409:                 }
                   13410:             }
1.37      www      13411:         }
                   13412: # ---------------------------------------------------------- There was an entry
                   13413:         if ($syval) {
1.601     albertel 13414: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13415: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13416: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13417: 		    #return $env{$cache_str}='';
1.601     albertel 13418: 		#}    
                   13419: 		#$syval.=$1;
                   13420: 	    #}
1.37      www      13421:         } else {
                   13422: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13423:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13424:                             &GDBM_READER(),0640)) {
1.37      www      13425: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13426:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13427:               unless ($ids) { 
                   13428:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13429:               }
                   13430:               unless ($ids) {
                   13431: # alias?
                   13432: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13433:               }
1.37      www      13434:               if ($ids) {
                   13435: # ------------------------------------------------------------------- Has ID(s)
                   13436:                  my @possibilities=split(/\,/,$ids);
1.39      www      13437:                  if ($#possibilities==0) {
                   13438: # ----------------------------------------------- There is only one possibility
1.37      www      13439: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13440: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13441: 						    $resid,$thisfn);
1.1282    raeburn  13442:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  13443:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13444:                              $possibles->{$syval} = 1;
                   13445:                          }
1.1282    raeburn  13446:                      }
                   13447:                      if ($checkforblock) {
1.1424    raeburn  13448:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  13449:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  13450:                              if (@blockers) {
                   13451:                                  $syval = '';
1.1425    raeburn  13452:                                  untie(%bighash);
                   13453:                                  return $env{$cache_str}='';
1.1424    raeburn  13454:                              }
1.1282    raeburn  13455:                          }
                   13456:                      }
                   13457:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13458: # ------------------------------------------ There is more than one possibility
                   13459:                      my $realpossible=0;
1.800     albertel 13460:                      foreach my $id (@possibilities) {
                   13461: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13462:                          my $canaccess;
                   13463:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13464:                              $canaccess = 1;
                   13465:                          } else { 
                   13466:                              $canaccess = &allowed('bre',$file);
                   13467:                          }
                   13468:                          if ($canaccess) {
                   13469:          		     my ($mapid,$resid)=split(/\./,$id);
                   13470:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13471:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13472: 						             $resid,$thisfn);
1.1424    raeburn  13473:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  13474:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  13475:                                  if ($checkforblock) {
1.1426    raeburn  13476:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  13477:                                      if (@blockers > 0) {
                   13478:                                          $syval = '';
                   13479:                                      } else {
1.1282    raeburn  13480:                                          $syval = $poss_syval;
                   13481:                                          $realpossible++;
                   13482:                                      }
                   13483:                                  } else {
                   13484:                                      $syval = $poss_syval;
                   13485:                                      $realpossible++;
                   13486:                                  }
1.1424    raeburn  13487:                                  if ($syval) {
                   13488:                                      if (ref($possibles) eq 'HASH') {
                   13489:                                          $possibles->{$syval} = 1;
                   13490:                                      }
                   13491:                                  }
1.1282    raeburn  13492:                              }
1.39      www      13493: 			 }
1.191     harris41 13494:                      }
1.39      www      13495: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13496:                  } else {
                   13497:                      $syval='';
1.37      www      13498:                  }
                   13499: 	      }
1.1282    raeburn  13500:               untie(%bighash);
1.481     raeburn  13501:            }
1.31      www      13502:         }
1.62      www      13503:         if ($syval) {
1.1427    raeburn  13504: 	    return $env{$cache_str}=$syval;
1.62      www      13505:         }
1.31      www      13506:     }
1.949     raeburn  13507:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13508:     return $env{$cache_str}='';
1.31      www      13509: }
                   13510: 
                   13511: # ---------------------------------------------------------- Return random seed
                   13512: 
1.32      www      13513: sub numval {
                   13514:     my $txt=shift;
                   13515:     $txt=~tr/A-J/0-9/;
                   13516:     $txt=~tr/a-j/0-9/;
                   13517:     $txt=~tr/K-T/0-9/;
                   13518:     $txt=~tr/k-t/0-9/;
                   13519:     $txt=~tr/U-Z/0-5/;
                   13520:     $txt=~tr/u-z/0-5/;
                   13521:     $txt=~s/\D//g;
1.564     albertel 13522:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13523:     return int($txt);
1.368     albertel 13524: }
                   13525: 
1.484     albertel 13526: sub numval2 {
                   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;
                   13535:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13536:     my $total;
                   13537:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13538:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13539:     return int($total);
                   13540: }
                   13541: 
1.575     albertel 13542: sub numval3 {
                   13543:     use integer;
                   13544:     my $txt=shift;
                   13545:     $txt=~tr/A-J/0-9/;
                   13546:     $txt=~tr/a-j/0-9/;
                   13547:     $txt=~tr/K-T/0-9/;
                   13548:     $txt=~tr/k-t/0-9/;
                   13549:     $txt=~tr/U-Z/0-5/;
                   13550:     $txt=~tr/u-z/0-5/;
                   13551:     $txt=~s/\D//g;
                   13552:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13553:     my $total;
                   13554:     foreach my $val (@txts) { $total+=$val; }
                   13555:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13556:     return $total;
                   13557: }
                   13558: 
1.675     albertel 13559: sub digest {
                   13560:     my ($data)=@_;
                   13561:     my $digest=&Digest::MD5::md5($data);
                   13562:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13563:     my ($e,$f);
                   13564:     {
                   13565:         use integer;
                   13566:         $e=($a+$b);
                   13567:         $f=($c+$d);
                   13568:         if ($_64bit) {
                   13569:             $e=(($e<<32)>>32);
                   13570:             $f=(($f<<32)>>32);
                   13571:         }
                   13572:     }
                   13573:     if (wantarray) {
                   13574: 	return ($e,$f);
                   13575:     } else {
                   13576: 	my $g;
                   13577: 	{
                   13578: 	    use integer;
                   13579: 	    $g=($e+$f);
                   13580: 	    if ($_64bit) {
                   13581: 		$g=(($g<<32)>>32);
                   13582: 	    }
                   13583: 	}
                   13584: 	return $g;
                   13585:     }
                   13586: }
                   13587: 
1.368     albertel 13588: sub latest_rnd_algorithm_id {
1.675     albertel 13589:     return '64bit5';
1.366     albertel 13590: }
1.32      www      13591: 
1.503     albertel 13592: sub get_rand_alg {
                   13593:     my ($courseid)=@_;
1.790     albertel 13594:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13595:     if ($courseid) {
1.620     albertel 13596: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13597:     }
                   13598:     return &latest_rnd_algorithm_id();
                   13599: }
                   13600: 
1.562     albertel 13601: sub validCODE {
                   13602:     my ($CODE)=@_;
                   13603:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13604:     return 0;
                   13605: }
                   13606: 
1.491     albertel 13607: sub getCODE {
1.620     albertel 13608:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13609:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13610: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13611: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13612: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13613:     }
                   13614:     return undef;
                   13615: }
1.1133    foxr     13616: #
                   13617: #  Determines the random seed for a specific context:
                   13618: #
                   13619: # parameters:
                   13620: #   symb      - in course context the symb for the seed.
                   13621: #   course_id - The course id of the form domain_coursenum.
                   13622: #   domain    - Domain for the user.
                   13623: #   course    - Course for the user.
                   13624: #   cenv      - environment of the course.
                   13625: #
                   13626: # NOTE:
                   13627: #   All parameters are picked out of the environment if missing
                   13628: #   or not defined.
                   13629: #   If a symb cannot be determined the current time is used instead.
                   13630: #
                   13631: #  For a given well defined symb, courside, domain, username,
                   13632: #  and course environment, the seed is reproducible.
                   13633: #
1.31      www      13634: sub rndseed {
1.1133    foxr     13635:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13636:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13637:     if (!defined($symb)) {
1.366     albertel 13638: 	unless ($symb=$wsymb) { return time; }
                   13639:     }
1.1146    foxr     13640:     if (!defined $courseid) { 
                   13641: 	$courseid=$wcourseid; 
                   13642:     }
                   13643:     if (!defined $domain) { $domain=$wdomain; }
                   13644:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13645: 
                   13646:     my $which;
                   13647:     if (defined($cenv->{'rndseed'})) {
                   13648: 	$which = $cenv->{'rndseed'};
                   13649:     } else {
                   13650: 	$which =&get_rand_alg($courseid);
                   13651:     }
1.491     albertel 13652:     if (defined(&getCODE())) {
1.1133    foxr     13653: 
1.675     albertel 13654: 	if ($which eq '64bit5') {
                   13655: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13656: 	} elsif ($which eq '64bit4') {
1.575     albertel 13657: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13658: 	} else {
                   13659: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13660: 	}
1.675     albertel 13661:     } elsif ($which eq '64bit5') {
                   13662: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13663:     } elsif ($which eq '64bit4') {
                   13664: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13665:     } elsif ($which eq '64bit3') {
                   13666: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13667:     } elsif ($which eq '64bit2') {
                   13668: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13669:     } elsif ($which eq '64bit') {
                   13670: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13671:     }
                   13672:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13673: }
                   13674: 
                   13675: sub rndseed_32bit {
                   13676:     my ($symb,$courseid,$domain,$username)=@_;
                   13677:     {
                   13678: 	use integer;
                   13679: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13680: 	my $symbseed=numval($symb) << 22;
                   13681: 	my $namechck=unpack("%32C*",$username) << 17;
                   13682: 	my $nameseed=numval($username) << 12;
                   13683: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13684: 	my $courseseed=unpack("%32C*",$courseid);
                   13685: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13686: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13687: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13688: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13689: 	return $num;
                   13690:     }
                   13691: }
                   13692: 
                   13693: sub rndseed_64bit {
                   13694:     my ($symb,$courseid,$domain,$username)=@_;
                   13695:     {
                   13696: 	use integer;
                   13697: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13698: 	my $symbseed=numval($symb) << 10;
                   13699: 	my $namechck=unpack("%32S*",$username);
                   13700: 	
                   13701: 	my $nameseed=numval($username) << 21;
                   13702: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13703: 	my $courseseed=unpack("%32S*",$courseid);
                   13704: 	
                   13705: 	my $num1=$symbchck+$symbseed+$namechck;
                   13706: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13707: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13708: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13709: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13710: 	return "$num1,$num2";
1.155     albertel 13711:     }
1.366     albertel 13712: }
                   13713: 
1.443     albertel 13714: sub rndseed_64bit2 {
                   13715:     my ($symb,$courseid,$domain,$username)=@_;
                   13716:     {
                   13717: 	use integer;
                   13718: 	# strings need to be an even # of cahracters long, it it is odd the
                   13719:         # last characters gets thrown away
                   13720: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13721: 	my $symbseed=numval($symb) << 10;
                   13722: 	my $namechck=unpack("%32S*",$username.' ');
                   13723: 	
                   13724: 	my $nameseed=numval($username) << 21;
1.501     albertel 13725: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13726: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13727: 	
                   13728: 	my $num1=$symbchck+$symbseed+$namechck;
                   13729: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13730: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13731: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13732: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13733: 	return "$num1,$num2";
                   13734:     }
                   13735: }
                   13736: 
                   13737: sub rndseed_64bit3 {
                   13738:     my ($symb,$courseid,$domain,$username)=@_;
                   13739:     {
                   13740: 	use integer;
                   13741: 	# strings need to be an even # of cahracters long, it it is odd the
                   13742:         # last characters gets thrown away
                   13743: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13744: 	my $symbseed=numval2($symb) << 10;
                   13745: 	my $namechck=unpack("%32S*",$username.' ');
                   13746: 	
                   13747: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13748: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13749: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13750: 	
                   13751: 	my $num1=$symbchck+$symbseed+$namechck;
                   13752: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13753: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13754: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13755: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13756: 	
1.503     albertel 13757: 	return "$num1:$num2";
1.443     albertel 13758:     }
                   13759: }
                   13760: 
1.575     albertel 13761: sub rndseed_64bit4 {
                   13762:     my ($symb,$courseid,$domain,$username)=@_;
                   13763:     {
                   13764: 	use integer;
                   13765: 	# strings need to be an even # of cahracters long, it it is odd the
                   13766:         # last characters gets thrown away
                   13767: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13768: 	my $symbseed=numval3($symb) << 10;
                   13769: 	my $namechck=unpack("%32S*",$username.' ');
                   13770: 	
                   13771: 	my $nameseed=numval3($username) << 21;
                   13772: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13773: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13774: 	
                   13775: 	my $num1=$symbchck+$symbseed+$namechck;
                   13776: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13777: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13778: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13779: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13780: 	
1.575     albertel 13781: 	return "$num1:$num2";
                   13782:     }
                   13783: }
                   13784: 
1.675     albertel 13785: sub rndseed_64bit5 {
                   13786:     my ($symb,$courseid,$domain,$username)=@_;
                   13787:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13788:     return "$num1:$num2";
                   13789: }
                   13790: 
1.366     albertel 13791: sub rndseed_CODE_64bit {
                   13792:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13793:     {
1.366     albertel 13794: 	use integer;
1.443     albertel 13795: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13796: 	my $symbseed=numval2($symb);
1.491     albertel 13797: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13798: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13799: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13800: 	my $num1=$symbseed+$CODEchck;
                   13801: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13802: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13803: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13804: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13805: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13806: 	return "$num1:$num2";
1.366     albertel 13807:     }
                   13808: }
                   13809: 
1.575     albertel 13810: sub rndseed_CODE_64bit4 {
                   13811:     my ($symb,$courseid,$domain,$username)=@_;
                   13812:     {
                   13813: 	use integer;
                   13814: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13815: 	my $symbseed=numval3($symb);
                   13816: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13817: 	my $CODEseed=numval3(&getCODE());
                   13818: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13819: 	my $num1=$symbseed+$CODEchck;
                   13820: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13821: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13822: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13823: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13824: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13825: 	return "$num1:$num2";
                   13826:     }
                   13827: }
                   13828: 
1.675     albertel 13829: sub rndseed_CODE_64bit5 {
                   13830:     my ($symb,$courseid,$domain,$username)=@_;
                   13831:     my $code = &getCODE();
                   13832:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13833:     return "$num1:$num2";
                   13834: }
                   13835: 
1.366     albertel 13836: sub setup_random_from_rndseed {
                   13837:     my ($rndseed)=@_;
1.503     albertel 13838:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13839:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13840:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13841:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13842:         } else {
                   13843:             &Math::Random::random_set_seed($num1,$num2);
                   13844:         }
1.366     albertel 13845:     } else {
                   13846: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13847:     }
1.36      albertel 13848: }
                   13849: 
1.474     albertel 13850: sub latest_receipt_algorithm_id {
1.835     albertel 13851:     return 'receipt3';
1.474     albertel 13852: }
                   13853: 
1.480     www      13854: sub recunique {
                   13855:     my $fucourseid=shift;
                   13856:     my $unique;
1.835     albertel 13857:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13858: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13859: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13860:     } else {
                   13861: 	$unique=$perlvar{'lonReceipt'};
                   13862:     }
                   13863:     return unpack("%32C*",$unique);
                   13864: }
                   13865: 
                   13866: sub recprefix {
                   13867:     my $fucourseid=shift;
                   13868:     my $prefix;
1.835     albertel 13869:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13870: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13871: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13872:     } else {
                   13873: 	$prefix=$perlvar{'lonHostID'};
                   13874:     }
                   13875:     return unpack("%32C*",$prefix);
                   13876: }
                   13877: 
1.76      www      13878: sub ireceipt {
1.474     albertel 13879:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13880: 
                   13881:     my $return =&recprefix($fucourseid).'-';
                   13882: 
                   13883:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13884: 	$env{'request.state'} eq 'construct') {
                   13885: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13886: 	return $return;
                   13887:     }
                   13888: 
1.76      www      13889:     my $cuname=unpack("%32C*",$funame);
                   13890:     my $cudom=unpack("%32C*",$fudom);
                   13891:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13892:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13893:     my $cunique=&recunique($fucourseid);
1.474     albertel 13894:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13895:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13896: 
1.790     albertel 13897: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13898: 			       
                   13899: 	$return.= ($cunique%$cuname+
                   13900: 		   $cunique%$cudom+
                   13901: 		   $cusymb%$cuname+
                   13902: 		   $cusymb%$cudom+
                   13903: 		   $cucourseid%$cuname+
                   13904: 		   $cucourseid%$cudom+
                   13905: 		   $cpart%$cuname+
                   13906: 		   $cpart%$cudom);
                   13907:     } else {
                   13908: 	$return.= ($cunique%$cuname+
                   13909: 		   $cunique%$cudom+
                   13910: 		   $cusymb%$cuname+
                   13911: 		   $cusymb%$cudom+
                   13912: 		   $cucourseid%$cuname+
                   13913: 		   $cucourseid%$cudom);
                   13914:     }
                   13915:     return $return;
1.76      www      13916: }
                   13917: 
                   13918: sub receipt {
1.474     albertel 13919:     my ($part)=@_;
1.790     albertel 13920:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13921:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13922: }
1.260     ng       13923: 
1.790     albertel 13924: sub whichuser {
                   13925:     my ($passedsymb)=@_;
                   13926:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13927:     if (defined($env{'form.grade_symb'})) {
                   13928: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13929: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13930: 	if (!$allowed &&
                   13931: 	    exists($env{'request.course.sec'}) &&
                   13932: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13933: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13934: 			      '/'.$env{'request.course.sec'});
                   13935: 	}
                   13936: 	if ($allowed) {
                   13937: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13938: 	    $courseid=$tmp_courseid;
                   13939: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13940: 	    ($name)=&get_env_multiple('form.grade_username');
                   13941: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13942: 	}
                   13943:     }
                   13944:     if (!$passedsymb) {
                   13945: 	$symb=&symbread();
                   13946:     } else {
                   13947: 	$symb=$passedsymb;
                   13948:     }
                   13949:     $courseid=$env{'request.course.id'};
                   13950:     $domain=$env{'user.domain'};
                   13951:     $name=$env{'user.name'};
                   13952:     if ($name eq 'public' && $domain eq 'public') {
                   13953: 	if (!defined($env{'form.username'})) {
                   13954: 	    $env{'form.username'}.=time.rand(10000000);
                   13955: 	}
                   13956: 	$name.=$env{'form.username'};
                   13957:     }
                   13958:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13959: 
                   13960: }
                   13961: 
1.36      albertel 13962: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13963: # returns either the contents of the file or 
                   13964: # -1 if the file doesn't exist
1.481     raeburn  13965: #
                   13966: # if the target is a file that was uploaded via DOCS, 
                   13967: # a check will be made to see if a current copy exists on the local server,
                   13968: # if it does this will be served, otherwise a copy will be retrieved from
                   13969: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13970: # the local server.   
1.472     albertel 13971: 
1.36      albertel 13972: sub getfile {
1.538     albertel 13973:     my ($file) = @_;
1.609     banghart 13974:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13975:     &repcopy($file);
                   13976:     return &readfile($file);
                   13977: }
                   13978: 
                   13979: sub repcopy_userfile {
                   13980:     my ($file)=@_;
1.1142    raeburn  13981:     my $londocroot = $perlvar{'lonDocRoot'};
                   13982:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13983:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13984:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13985: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13986:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13987:     if (-e "$file") {
1.828     www      13988: # we already have a local copy, check it out
1.538     albertel 13989: 	my @fileinfo = stat($file);
1.828     www      13990: 	my $rtncode;
                   13991: 	my $info;
1.538     albertel 13992: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13993: 	if ($lwpresp ne 'ok') {
1.828     www      13994: # there is no such file anymore, even though we had a local copy
1.482     albertel 13995: 	    if ($rtncode eq '404') {
1.538     albertel 13996: 		unlink($file);
1.482     albertel 13997: 	    }
                   13998: 	    return -1;
                   13999: 	}
                   14000: 	if ($info < $fileinfo[9]) {
1.828     www      14001: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14002: 	    return 'ok';
1.828     www      14003: 	} else {
                   14004: # the file is outdated, get rid of it
                   14005: 	    unlink($file);
1.482     albertel 14006: 	}
1.828     www      14007:     }
                   14008: # one way or the other, at this point, we don't have the file
                   14009: # construct the correct path for the file
                   14010:     my @parts = ($cdom,$cnum); 
                   14011:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14012: 	push @parts, split(/\//,$1);
                   14013:     }
                   14014:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14015:     foreach my $part (@parts) {
                   14016: 	$path .= '/'.$part;
                   14017: 	if (!-e $path) {
                   14018: 	    mkdir($path,0770);
1.482     albertel 14019: 	}
                   14020:     }
1.828     www      14021: # now the path exists for sure
                   14022: # get a user agent
                   14023:     my $transferfile=$file.'.in.transfer';
                   14024: # FIXME: this should flock
                   14025:     if (-e $transferfile) { return 'ok'; }
                   14026:     my $request;
                   14027:     $uri=~s/^\///;
1.980     raeburn  14028:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  14029:     my $hostname = &hostname($homeserver);
1.980     raeburn  14030:     my $protocol = $protocol{$homeserver};
                   14031:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14032:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  14033:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      14034: # did it work?
                   14035:     if ($response->is_error()) {
                   14036: 	unlink($transferfile);
                   14037: 	&logthis("Userfile repcopy failed for $uri");
                   14038: 	return -1;
                   14039:     }
                   14040: # worked, rename the transfer file
                   14041:     rename($transferfile,$file);
1.607     raeburn  14042:     return 'ok';
1.481     raeburn  14043: }
                   14044: 
1.517     albertel 14045: sub tokenwrapper {
                   14046:     my $uri=shift;
1.980     raeburn  14047:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14048:     $uri=~s|^/||;
1.620     albertel 14049:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14050:     my $token=$1;
1.552     albertel 14051:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14052:     if ($udom && $uname && $file) {
                   14053: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14054:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14055:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  14056:         my $hostname = &hostname($homeserver);
1.980     raeburn  14057:         my $protocol = $protocol{$homeserver};
                   14058:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14059:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14060:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14061:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14062:     } else {
                   14063:         return '/adm/notfound.html';
                   14064:     }
                   14065: }
                   14066: 
1.828     www      14067: # call with reqtype HEAD: get last modification time
                   14068: # call with reqtype GET: get the file contents
                   14069: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14070: #
1.481     raeburn  14071: sub getuploaded {
                   14072:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14073:     $uri=~s/^\///;
1.980     raeburn  14074:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  14075:     my $hostname = &hostname($homeserver);
1.980     raeburn  14076:     my $protocol = $protocol{$homeserver};
                   14077:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14078:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14079:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  14080:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  14081:     $$rtncode = $response->code;
1.482     albertel 14082:     if (! $response->is_success()) {
                   14083: 	return 'failed';
                   14084:     }      
                   14085:     if ($reqtype eq 'HEAD') {
1.486     www      14086: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14087:     } elsif ($reqtype eq 'GET') {
                   14088: 	$$info = $response->content;
1.472     albertel 14089:     }
1.482     albertel 14090:     return 'ok';
1.36      albertel 14091: }
                   14092: 
1.481     raeburn  14093: sub readfile {
                   14094:     my $file = shift;
                   14095:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14096:     my $fh;
1.1359    raeburn  14097:     open($fh,"<",$file);
1.481     raeburn  14098:     my $a='';
1.800     albertel 14099:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14100:     return $a;
                   14101: }
                   14102: 
1.36      albertel 14103: sub filelocation {
1.590     banghart 14104:     my ($dir,$file) = @_;
                   14105:     my $location;
                   14106:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14107: 
                   14108:     if ($file =~ m-^/adm/-) {
                   14109: 	$file=~s-^/adm/wrapper/-/-;
                   14110: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14111:     }
1.882     albertel 14112: 
1.1139    www      14113:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14114:         $location = $file;
1.609     banghart 14115:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14116:         my ($udom,$uname,$filename)=
1.811     albertel 14117:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14118:         my $home=&homeserver($uname,$udom);
                   14119:         my $is_me=0;
                   14120:         my @ids=&current_machine_ids();
                   14121:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14122:         if ($is_me) {
1.1117    foxr     14123:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14124:         } else {
                   14125:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14126:   	      $udom.'/'.$uname.'/'.$filename;
                   14127:         }
1.882     albertel 14128:     } elsif ($file =~ m-^/adm/-) {
                   14129: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14130:     } else {
                   14131:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14132:         $file=~s:^/(res|priv)/:/:;
                   14133:         my $space=$1;
1.590     banghart 14134:         if ( !( $file =~ m:^/:) ) {
                   14135:             $location = $dir. '/'.$file;
                   14136:         } else {
1.1142    raeburn  14137:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14138:         }
1.59      albertel 14139:     }
1.590     banghart 14140:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14141:     while ($location=~m{/\.\./}) {
                   14142: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14143: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14144: 	} else {
                   14145: 	    $location=~ s{/\.\./}{/}g;
                   14146: 	}
                   14147:     } #remove dir/..
1.590     banghart 14148:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14149:     return $location;
1.46      www      14150: }
1.36      albertel 14151: 
1.46      www      14152: sub hreflocation {
                   14153:     my ($dir,$file)=@_;
1.980     raeburn  14154:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14155: 	$file=filelocation($dir,$file);
1.700     albertel 14156:     } elsif ($file=~m-^/adm/-) {
                   14157: 	$file=~s-^/adm/wrapper/-/-;
                   14158: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14159:     }
                   14160:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14161: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14162:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14163: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14164: 	        {/uploaded/$1/$2/}x;
1.46      www      14165:     }
1.913     albertel 14166:     if ($file=~ m{^/userfiles/}) {
                   14167: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14168:     }
1.462     albertel 14169:     return $file;
1.465     albertel 14170: }
                   14171: 
1.1139    www      14172: 
                   14173: 
                   14174: 
                   14175: 
1.465     albertel 14176: sub current_machine_domains {
1.853     albertel 14177:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14178: }
                   14179: 
                   14180: sub machine_domains {
                   14181:     my ($hostname) = @_;
1.465     albertel 14182:     my @domains;
1.838     albertel 14183:     my %hostname = &all_hostnames();
1.465     albertel 14184:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14185: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14186: 	if ($hostname eq $name) {
1.844     albertel 14187: 	    push(@domains,&host_domain($id));
1.465     albertel 14188: 	}
                   14189:     }
                   14190:     return @domains;
                   14191: }
                   14192: 
                   14193: sub current_machine_ids {
1.853     albertel 14194:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14195: }
                   14196: 
                   14197: sub machine_ids {
                   14198:     my ($hostname) = @_;
                   14199:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14200:     my @ids;
1.888     albertel 14201:     my %name_to_host = &all_names();
1.889     albertel 14202:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14203: 	return @{ $name_to_host{$hostname} };
                   14204:     }
                   14205:     return;
1.31      www      14206: }
                   14207: 
1.824     raeburn  14208: sub additional_machine_domains {
                   14209:     my @domains;
1.1359    raeburn  14210:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  14211:     while( my $line = <$fh>) {
                   14212:         $line =~ s/\s//g;
                   14213:         push(@domains,$line);
                   14214:     }
                   14215:     return @domains;
                   14216: }
                   14217: 
                   14218: sub default_login_domain {
                   14219:     my $domain = $perlvar{'lonDefDomain'};
                   14220:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14221:     foreach my $posdom (&current_machine_domains(),
                   14222:                         &additional_machine_domains()) {
                   14223:         if (lc($posdom) eq lc($testdomain)) {
                   14224:             $domain=$posdom;
                   14225:             last;
                   14226:         }
                   14227:     }
                   14228:     return $domain;
                   14229: }
                   14230: 
1.1414    raeburn  14231: sub shared_institution {
1.1439  ! raeburn  14232:     my ($dom,$lonhost) = @_;
        !          14233:     if ($lonhost eq '') {
        !          14234:         $lonhost = $perlvar{'lonHostID'};
        !          14235:     }
1.1414    raeburn  14236:     my $same_intdom;
1.1439  ! raeburn  14237:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  14238:     if ($hostintdom ne '') {
                   14239:         my %iphost = &get_iphost();
                   14240:         my $primary_id = &domain($dom,'primary');
                   14241:         my $primary_ip = &get_host_ip($primary_id);
                   14242:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14243:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14244:                 my $intdom = &internet_dom($id);
                   14245:                 if ($intdom eq $hostintdom) {
                   14246:                     $same_intdom = 1;
                   14247:                     last;
                   14248:                 }
                   14249:             }
                   14250:         }
                   14251:     }
                   14252:     return $same_intdom;
                   14253: }
                   14254: 
1.1398    raeburn  14255: sub uses_sts {
                   14256:     my ($ignore_cache) = @_;
                   14257:     my $lonhost = $perlvar{'lonHostID'};
                   14258:     my $hostname = &hostname($lonhost);
                   14259:     my $sts_on;
                   14260:     if ($protocol{$lonhost} eq 'https') {
                   14261:         my $cachetime = 12*3600;
                   14262:         if (!$ignore_cache) {
                   14263:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14264:             if (defined($cached)) {
                   14265:                 return $sts_on;
                   14266:             }
                   14267:         }
                   14268:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14269:         my $request=new HTTP::Request('HEAD',$url);
                   14270:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14271:         if ($response->is_success) {
                   14272:             my $has_sts = $response->header('Strict-Transport-Security');
                   14273:             if ($has_sts eq '') {
                   14274:                 $sts_on = 0;
                   14275:             } else {
                   14276:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14277:                     my $maxage = $1;
                   14278:                     if ($maxage) {
                   14279:                         $sts_on = 1;
                   14280:                     } else {
                   14281:                         $sts_on = 0;
                   14282:                     }
                   14283:                 } else {
                   14284:                     $sts_on = 0;
                   14285:                 }
                   14286:             }
                   14287:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14288:         }
                   14289:     }
                   14290:     return;
                   14291: }
                   14292: 
1.1434    raeburn  14293: sub get_requestor_ip {
                   14294:     my ($r,$nolookup,$noproxy) = @_;
                   14295:     my $from_ip;
                   14296:     if (ref($r)) {
                   14297:         $from_ip = $r->get_remote_host($nolookup);
                   14298:     } else {
                   14299:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14300:     }
                   14301:     return $from_ip if ($noproxy); 
                   14302:     # Who controls proxy settings for server
                   14303:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14304:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14305:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  14306:         if ($proxyinfo->{'vpnint'}) {
                   14307:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  14308:                 return $from_ip;
                   14309:             }
                   14310:         }
                   14311:         if ($proxyinfo->{'trusted'}) {
                   14312:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14313:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14314:                 my ($ip,$xfor);
                   14315:                 if (ref($r)) {
                   14316:                     if ($ipheader) {
                   14317:                         $ip = $r->headers_in->{$ipheader};
                   14318:                     }
                   14319:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14320:                 } else {
                   14321:                     if ($ipheader) {
                   14322:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14323:                     }
                   14324:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14325:                 }
                   14326:                 if (($ip eq '') && ($xfor ne '')) {
                   14327:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14328:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14329:                             $ip = $poss_ip;
1.1435    raeburn  14330:                             last;
1.1434    raeburn  14331:                         }
                   14332:                     }
                   14333:                 }
                   14334:                 if ($ip ne '') {
                   14335:                     return $ip;
                   14336:                 }
                   14337:             }
                   14338:         }
                   14339:     }
                   14340:     return $from_ip;
                   14341: }
                   14342: 
                   14343: sub get_proxy_settings {
                   14344:     my ($dom_in_use) = @_;
                   14345:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14346:     my $proxyinfo = {
                   14347:                        ipheader => $domdefaults{'waf_ipheader'},
                   14348:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  14349:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  14350:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1434    raeburn  14351:                     };
                   14352:     return $proxyinfo;
                   14353: }
                   14354: 
                   14355: sub ip_match {
                   14356:     my ($ip,$pattern_str) = @_;
                   14357:     $ip=Net::CIDR::cidrvalidate($ip);
                   14358:     if ($ip) {
                   14359:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14360:     }
                   14361:     return;
                   14362: }
                   14363: 
                   14364: sub get_proxy_alias {
                   14365:     my $lonhost = $perlvar{'lonHostID'};
                   14366:     if ($lonhost ne '') {
                   14367:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonhost);
                   14368:         if ($cached) {
                   14369:             return $alias;
                   14370:         }
                   14371:         my $dom = &Apache::lonnet::host_domain($lonhost);
                   14372:         if ($dom ne '') {
                   14373:             my $cachetime = 60*60*24;
                   14374:             my %domconfig =
1.1437    raeburn  14375:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
1.1434    raeburn  14376:             my $alias;
1.1437    raeburn  14377:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14378:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14379:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonhost};
1.1434    raeburn  14380:                 }
                   14381:             }
                   14382:             return &do_cache_new('proxyalias',$lonhost,$alias,$cachetime);
                   14383:         }
                   14384:     }
                   14385:     return;
                   14386: }
                   14387: 
1.31      www      14388: # ------------------------------------------------------------- Declutters URLs
                   14389: 
                   14390: sub declutter {
                   14391:     my $thisfn=shift;
1.569     albertel 14392:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14393:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14394:         $thisfn=~s{^/home/httpd/html}{};
                   14395:     }
1.31      www      14396:     $thisfn=~s/^\///;
1.697     albertel 14397:     $thisfn=~s|^adm/wrapper/||;
                   14398:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14399:     $thisfn=~s/^res\///;
1.1172    bisitz   14400:     $thisfn=~s/^priv\///;
1.1032    raeburn  14401:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14402:         $thisfn=~s/\?.+$//;
                   14403:     }
1.268     www      14404:     return $thisfn;
                   14405: }
                   14406: 
                   14407: # ------------------------------------------------------------- Clutter up URLs
                   14408: 
                   14409: sub clutter {
                   14410:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14411:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14412: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14413:        $thisfn='/res'.$thisfn; 
                   14414:     }
1.1031    raeburn  14415:     if ($thisfn !~m|^/adm|) {
                   14416: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14417: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14418: 	} else {
                   14419: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14420: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14421: 	    if ($embstyle eq 'ssi'
                   14422: 		|| ($embstyle eq 'hdn')
                   14423: 		|| ($embstyle eq 'rat')
                   14424: 		|| ($embstyle eq 'prv')
                   14425: 		|| ($embstyle eq 'ign')) {
                   14426: 		#do nothing with these
                   14427: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14428: 		|| ($embstyle eq 'emb')
                   14429: 		|| ($embstyle eq 'wrp')) {
                   14430: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14431: 	    } elsif ($embstyle eq 'unk'
                   14432: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14433: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14434: 	    } else {
1.718     www      14435: #		&logthis("Got a blank emb style");
1.695     albertel 14436: 	    }
1.694     albertel 14437: 	}
1.1343    raeburn  14438:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14439:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14440:     }
1.31      www      14441:     return $thisfn;
1.12      www      14442: }
                   14443: 
1.787     albertel 14444: sub clutter_with_no_wrapper {
                   14445:     my $uri = &clutter(shift);
                   14446:     if ($uri =~ m-^/adm/-) {
                   14447: 	$uri =~ s-^/adm/wrapper/-/-;
                   14448: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14449:     }
                   14450:     return $uri;
                   14451: }
                   14452: 
1.557     albertel 14453: sub freeze_escape {
                   14454:     my ($value)=@_;
                   14455:     if (ref($value)) {
                   14456: 	$value=&nfreeze($value);
                   14457: 	return '__FROZEN__'.&escape($value);
                   14458:     }
                   14459:     return &escape($value);
                   14460: }
                   14461: 
1.11      www      14462: 
1.557     albertel 14463: sub thaw_unescape {
                   14464:     my ($value)=@_;
                   14465:     if ($value =~ /^__FROZEN__/) {
                   14466: 	substr($value,0,10,undef);
                   14467: 	$value=&unescape($value);
                   14468: 	return &thaw($value);
                   14469:     }
                   14470:     return &unescape($value);
                   14471: }
                   14472: 
1.436     albertel 14473: sub correct_line_ends {
                   14474:     my ($result)=@_;
                   14475:     $$result =~s/\r\n/\n/mg;
                   14476:     $$result =~s/\r/\n/mg;
1.415     albertel 14477: }
1.1       albertel 14478: # ================================================================ Main Program
                   14479: 
1.184     www      14480: sub goodbye {
1.204     albertel 14481:    &logthis("Starting Shut down");
1.443     albertel 14482: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14483:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14484: #converted
1.599     albertel 14485: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14486:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14487: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14488: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14489: #1.1 only
1.870     albertel 14490: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14491: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14492: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14493: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14494:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14495:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14496:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14497:    &flushcourselogs();
                   14498:    &logthis("Shutting down");
                   14499: }
                   14500: 
1.852     albertel 14501: sub get_dns {
1.1210    raeburn  14502:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14503:     if (!$ignore_cache) {
                   14504: 	my ($content,$cached)=
                   14505: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14506: 	if ($cached) {
1.1210    raeburn  14507: 	    &$func($content,$hashref);
1.869     albertel 14508: 	    return;
                   14509: 	}
                   14510:     }
                   14511: 
                   14512:     my %alldns;
1.1379    raeburn  14513:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14514:         foreach my $dns (<$config>) {
                   14515: 	    next if ($dns !~ /^\^(\S*)/x);
                   14516:             my $line = $1;
                   14517:             my ($host,$protocol) = split(/:/,$line);
                   14518:             if ($protocol ne 'https') {
                   14519:                 $protocol = 'http';
                   14520:             }
                   14521: 	    $alldns{$host} = $protocol;
1.979     raeburn  14522:         }
1.1379    raeburn  14523:         close($config);
1.869     albertel 14524:     }
                   14525:     while (%alldns) {
1.1263    raeburn  14526: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  14527: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  14528:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  14529:         delete($alldns{$dns});
1.852     albertel 14530: 	next if ($response->is_error());
1.1379    raeburn  14531:         if ($url eq '/adm/dns/loncapaCRL') {
                   14532:             return &$func($response);
                   14533:         } else {
                   14534: 	    my @content = split("\n",$response->content);
                   14535: 	    unless ($nocache) {
                   14536: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14537: 	    }
                   14538: 	    &$func(\@content,$hashref);
                   14539:             return;
                   14540:         }
                   14541:     }
                   14542:     my $which = (split('/',$url,4))[3];
                   14543:     if ($which eq 'loncapaCRL') {
                   14544:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14545:         if (-e $diskfile) {
                   14546:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14547:         } else {
                   14548:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14549:         }
                   14550:     } else {
                   14551:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14552:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14553:             my @content = <$config>;
                   14554:             close($config);
                   14555:             &$func(\@content,$hashref);
                   14556:         }
1.852     albertel 14557:     }
1.1210    raeburn  14558:     return;
                   14559: }
                   14560: 
                   14561: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14562: sub parse_dns_checksums_tab {
1.1210    raeburn  14563:     my ($lines,$hashref) = @_;
1.1264    raeburn  14564:     my $lonhost = $perlvar{'lonHostID'};
                   14565:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14566:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14567:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14568:     my $webconfdir = '/etc/httpd/conf';
                   14569:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14570:         $webconfdir = '/etc/apache2';
                   14571:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14572:         if ($1 >= 10) {
                   14573:             $webconfdir = '/etc/apache2';
                   14574:         }
                   14575:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14576:         if ($1 >= 10.0) {
                   14577:             $webconfdir = '/etc/apache2';
                   14578:         }
                   14579:     }
1.1210    raeburn  14580:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14581:     my (%chksum,%revnum);
                   14582:     if (ref($lines) eq 'ARRAY') {
                   14583:         chomp(@{$lines});
1.1238    raeburn  14584:         my $version = shift(@{$lines});
                   14585:         if ($version eq $release) {  
1.1210    raeburn  14586:             foreach my $line (@{$lines}) {
1.1238    raeburn  14587:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14588:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14589:                     if ($webconfdir eq '/etc/apache2') {
                   14590:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14591:                     }
                   14592:                 }
1.1238    raeburn  14593:                 $chksum{$file} = $shasum;
                   14594:                 $revnum{$file} = $version;
1.1210    raeburn  14595:             }
                   14596:             if (ref($hashref) eq 'HASH') {
                   14597:                 %{$hashref} = (
                   14598:                                 sums     => \%chksum,
                   14599:                                 versions => \%revnum,
                   14600:                               );
                   14601:             }
                   14602:         }
                   14603:     }
1.869     albertel 14604:     return;
1.852     albertel 14605: }
1.1210    raeburn  14606: 
                   14607: sub fetch_dns_checksums {
1.1238    raeburn  14608:     my %checksums;
                   14609:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14610:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14611:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14612:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14613:              \%checksums);
1.1210    raeburn  14614:     return \%checksums;
                   14615: }
                   14616: 
1.1379    raeburn  14617: sub fetch_crl_pemfile {
                   14618:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14619: }
                   14620: 
                   14621: sub save_crl_pem {
                   14622:     my ($response) = @_;
1.1380    raeburn  14623:     my ($msg,$hadchanges);
1.1379    raeburn  14624:     if (ref($response)) {
                   14625:         my $now = time;
                   14626:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14627:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14628:         if (open(my $fh,'>',"$tmpcrl")) {
                   14629:             print $fh $response->content;
                   14630:             close($fh);
                   14631:             if (-e $lonca) {
                   14632:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14633:                     my $check = <PIPE>;
                   14634:                     close(PIPE);
                   14635:                     chomp($check);
                   14636:                     if ($check eq 'verify OK') {
                   14637:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  14638:                         my $backup;
1.1379    raeburn  14639:                         if (-e $dest) {
1.1380    raeburn  14640:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   14641:                                 $backup = 'ok';
                   14642:                             }
1.1379    raeburn  14643:                         }
                   14644:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   14645:                             $msg = 'ok';
1.1380    raeburn  14646:                             if ($backup) {
                   14647:                                 my (%oldnums,%newnums);
                   14648:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   14649:                                     while (<PIPE>) {
                   14650:                                         $oldnums{(split(/:/))[1]} = 1;
                   14651:                                     }
                   14652:                                     close(PIPE);
                   14653:                                 }
                   14654:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   14655:                                     while(<PIPE>) {
                   14656:                                         $newnums{(split(/:/))[1]} = 1;
                   14657:                                     }
                   14658:                                     close(PIPE);
                   14659:                                 }
                   14660:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   14661:                                     unless (exists($oldnums{$key})) {
                   14662:                                         $hadchanges = 1;
                   14663:                                         last;
                   14664:                                     }
                   14665:                                 }
                   14666:                                 unless ($hadchanges) {
                   14667:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   14668:                                         unless (exists($newnums{$key})) {
                   14669:                                             $hadchanges = 1;
                   14670:                                             last;
                   14671:                                         }
                   14672:                                     }
                   14673:                                 }
                   14674:                             }
1.1379    raeburn  14675:                         }
                   14676:                     } else {
                   14677:                         unlink($tmpcrl);
                   14678:                     }
                   14679:                 } else {
                   14680:                     unlink($tmpcrl);
                   14681:                 }
                   14682:             } else {
                   14683:                 unlink($tmpcrl);
                   14684:             }
                   14685:         }
                   14686:     }
1.1380    raeburn  14687:     return ($msg,$hadchanges);
1.1379    raeburn  14688: }
                   14689: 
1.327     albertel 14690: # ------------------------------------------------------------ Read domain file
                   14691: {
1.852     albertel 14692:     my $loaded;
1.846     albertel 14693:     my %domain;
                   14694: 
1.852     albertel 14695:     sub parse_domain_tab {
                   14696: 	my ($lines) = @_;
                   14697: 	foreach my $line (@$lines) {
                   14698: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14699: 
1.846     albertel 14700: 	    chomp($line);
1.852     albertel 14701: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14702: 	    my %this_domain;
                   14703: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14704: 			       'lang_def', 'city', 'longi', 'lati',
                   14705: 			       'primary') {
                   14706: 		$this_domain{$field} = shift(@elements);
                   14707: 	    }
                   14708: 	    $domain{$name} = \%this_domain;
1.852     albertel 14709: 	}
                   14710:     }
1.864     albertel 14711: 
                   14712:     sub reset_domain_info {
                   14713: 	undef($loaded);
                   14714: 	undef(%domain);
                   14715:     }
                   14716: 
1.852     albertel 14717:     sub load_domain_tab {
1.1293    raeburn  14718: 	my ($ignore_cache,$nocache) = @_;
                   14719: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14720: 	my $fh;
1.1359    raeburn  14721: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14722: 	    my @lines = <$fh>;
                   14723: 	    &parse_domain_tab(\@lines);
1.448     albertel 14724: 	}
1.852     albertel 14725: 	close($fh);
                   14726: 	$loaded = 1;
1.327     albertel 14727:     }
1.846     albertel 14728: 
                   14729:     sub domain {
1.852     albertel 14730: 	&load_domain_tab() if (!$loaded);
                   14731: 
1.846     albertel 14732: 	my ($name,$what) = @_;
                   14733: 	return if ( !exists($domain{$name}) );
                   14734: 
                   14735: 	if (!$what) {
                   14736: 	    return $domain{$name}{'description'};
                   14737: 	}
                   14738: 	return $domain{$name}{$what};
                   14739:     }
1.974     raeburn  14740: 
                   14741:     sub domain_info {
                   14742:         &load_domain_tab() if (!$loaded);
                   14743:         return %domain;
                   14744:     }
                   14745: 
1.327     albertel 14746: }
                   14747: 
                   14748: 
1.1       albertel 14749: # ------------------------------------------------------------- Read hosts file
                   14750: {
1.838     albertel 14751:     my %hostname;
1.844     albertel 14752:     my %hostdom;
1.845     albertel 14753:     my %libserv;
1.852     albertel 14754:     my $loaded;
1.888     albertel 14755:     my %name_to_host;
1.1074    raeburn  14756:     my %internetdom;
1.1107    raeburn  14757:     my %LC_dns_serv;
1.852     albertel 14758: 
                   14759:     sub parse_hosts_tab {
                   14760: 	my ($file) = @_;
                   14761: 	foreach my $configline (@$file) {
                   14762: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14763:             chomp($configline);
                   14764: 	    if ($configline =~ /^\^/) {
                   14765:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14766:                     $LC_dns_serv{$1} = 1;
                   14767:                 }
                   14768:                 next;
                   14769:             }
1.1074    raeburn  14770: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14771: 	    $name=~s/\s//g;
                   14772: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  14773:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14774:                     my $curr = $hostname{$id};
                   14775:                     my $skip;
                   14776:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14777:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14778:                             $skip = 1;
                   14779:                         } else {
                   14780:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14781:                         }
                   14782:                     }
                   14783:                     unless ($skip) {
                   14784:                         push(@{$name_to_host{$name}},$id);
                   14785:                     }
                   14786:                 } else {
                   14787:                     push(@{$name_to_host{$name}},$id);
                   14788:                 }
1.852     albertel 14789: 		$hostname{$id}=$name;
                   14790: 		$hostdom{$id}=$domain;
                   14791: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14792:                 if (defined($protocol)) {
                   14793:                     if ($protocol eq 'https') {
                   14794:                         $protocol{$id} = $protocol;
                   14795:                     } else {
                   14796:                         $protocol{$id} = 'http'; 
                   14797:                     }
1.968     raeburn  14798:                 } else {
1.969     raeburn  14799:                     $protocol{$id} = 'http';
1.968     raeburn  14800:                 }
1.1074    raeburn  14801:                 if (defined($intdom)) {
                   14802:                     $internetdom{$id} = $intdom;
                   14803:                 }
1.852     albertel 14804: 	    }
                   14805: 	}
                   14806:     }
1.864     albertel 14807:     
                   14808:     sub reset_hosts_info {
1.897     albertel 14809: 	&purge_remembered();
1.864     albertel 14810: 	&reset_domain_info();
                   14811: 	&reset_hosts_ip_info();
1.1339    raeburn  14812:         undef(%internetdom);
1.892     albertel 14813: 	undef(%name_to_host);
1.864     albertel 14814: 	undef(%hostname);
                   14815: 	undef(%hostdom);
                   14816: 	undef(%libserv);
                   14817: 	undef($loaded);
                   14818:     }
1.1       albertel 14819: 
1.852     albertel 14820:     sub load_hosts_tab {
1.1293    raeburn  14821: 	my ($ignore_cache,$nocache) = @_;
                   14822: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  14823: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14824: 	my @config = <$config>;
                   14825: 	&parse_hosts_tab(\@config);
                   14826: 	close($config);
                   14827: 	$loaded=1;
1.1       albertel 14828:     }
1.852     albertel 14829: 
1.838     albertel 14830:     sub hostname {
1.852     albertel 14831: 	&load_hosts_tab() if (!$loaded);
                   14832: 
1.838     albertel 14833: 	my ($lonid) = @_;
                   14834: 	return $hostname{$lonid};
                   14835:     }
1.845     albertel 14836: 
1.838     albertel 14837:     sub all_hostnames {
1.852     albertel 14838: 	&load_hosts_tab() if (!$loaded);
                   14839: 
1.838     albertel 14840: 	return %hostname;
                   14841:     }
1.845     albertel 14842: 
1.888     albertel 14843:     sub all_names {
1.1293    raeburn  14844:         my ($ignore_cache,$nocache) = @_;
                   14845: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14846: 
                   14847: 	return %name_to_host;
                   14848:     }
                   14849: 
1.974     raeburn  14850:     sub all_host_domain {
                   14851:         &load_hosts_tab() if (!$loaded);
                   14852:         return %hostdom;
                   14853:     }
                   14854: 
1.1339    raeburn  14855:     sub all_host_intdom {
                   14856:         &load_hosts_tab() if (!$loaded);
                   14857:         return %internetdom;
                   14858:     }
                   14859: 
1.845     albertel 14860:     sub is_library {
1.852     albertel 14861: 	&load_hosts_tab() if (!$loaded);
                   14862: 
1.845     albertel 14863: 	return exists($libserv{$_[0]});
                   14864:     }
                   14865: 
                   14866:     sub all_library {
1.852     albertel 14867: 	&load_hosts_tab() if (!$loaded);
                   14868: 
1.845     albertel 14869: 	return %libserv;
                   14870:     }
                   14871: 
1.1062    droeschl 14872:     sub unique_library {
                   14873: 	#2x reverse removes all hostnames that appear more than once
                   14874:         my %unique = reverse &all_library();
                   14875:         return reverse %unique;
                   14876:     }
                   14877: 
1.841     albertel 14878:     sub get_servers {
1.852     albertel 14879: 	&load_hosts_tab() if (!$loaded);
                   14880: 
1.841     albertel 14881: 	my ($domain,$type) = @_;
                   14882: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14883: 	                                          : %hostname;
                   14884: 	my %result;
1.842     albertel 14885: 	if (ref($domain) eq 'ARRAY') {
                   14886: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14887: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14888: 		    $result{$host} = $hostname;
                   14889: 		}
                   14890: 	    }
                   14891: 	} else {
                   14892: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14893: 		if ($hostdom{$host} eq $domain) {
                   14894: 		    $result{$host} = $hostname;
                   14895: 		}
1.841     albertel 14896: 	    }
                   14897: 	}
                   14898: 	return %result;
                   14899:     }
1.845     albertel 14900: 
1.1062    droeschl 14901:     sub get_unique_servers {
                   14902:         my %unique = reverse &get_servers(@_);
                   14903: 	return reverse %unique;
                   14904:     }
                   14905: 
1.844     albertel 14906:     sub host_domain {
1.852     albertel 14907: 	&load_hosts_tab() if (!$loaded);
                   14908: 
1.844     albertel 14909: 	my ($lonid) = @_;
                   14910: 	return $hostdom{$lonid};
                   14911:     }
                   14912: 
1.841     albertel 14913:     sub all_domains {
1.852     albertel 14914: 	&load_hosts_tab() if (!$loaded);
                   14915: 
1.841     albertel 14916: 	my %seen;
                   14917: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14918: 	return @uniq;
                   14919:     }
1.1074    raeburn  14920: 
                   14921:     sub internet_dom {
                   14922:         &load_hosts_tab() if (!$loaded);
                   14923: 
                   14924:         my ($lonid) = @_;
                   14925:         return $internetdom{$lonid};
                   14926:     }
1.1107    raeburn  14927: 
                   14928:     sub is_LC_dns {
                   14929:         &load_hosts_tab() if (!$loaded);
                   14930: 
                   14931:         my ($hostname) = @_;
                   14932:         return exists($LC_dns_serv{$hostname});
                   14933:     }
                   14934: 
1.1       albertel 14935: }
                   14936: 
1.847     albertel 14937: { 
                   14938:     my %iphost;
1.856     albertel 14939:     my %name_to_ip;
                   14940:     my %lonid_to_ip;
1.869     albertel 14941: 
1.847     albertel 14942:     sub get_hosts_from_ip {
                   14943: 	my ($ip) = @_;
                   14944: 	my %iphosts = &get_iphost();
                   14945: 	if (ref($iphosts{$ip})) {
                   14946: 	    return @{$iphosts{$ip}};
                   14947: 	}
                   14948: 	return;
1.839     albertel 14949:     }
1.864     albertel 14950:     
                   14951:     sub reset_hosts_ip_info {
                   14952: 	undef(%iphost);
                   14953: 	undef(%name_to_ip);
                   14954: 	undef(%lonid_to_ip);
                   14955:     }
1.856     albertel 14956: 
                   14957:     sub get_host_ip {
                   14958: 	my ($lonid) = @_;
                   14959: 	if (exists($lonid_to_ip{$lonid})) {
                   14960: 	    return $lonid_to_ip{$lonid};
                   14961: 	}
                   14962: 	my $name=&hostname($lonid);
                   14963:    	my $ip = gethostbyname($name);
                   14964: 	return if (!$ip || length($ip) ne 4);
                   14965: 	$ip=inet_ntoa($ip);
                   14966: 	$name_to_ip{$name}   = $ip;
                   14967: 	$lonid_to_ip{$lonid} = $ip;
                   14968: 	return $ip;
                   14969:     }
1.847     albertel 14970:     
                   14971:     sub get_iphost {
1.1293    raeburn  14972: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14973: 
1.869     albertel 14974: 	if (!$ignore_cache) {
                   14975: 	    if (%iphost) {
                   14976: 		return %iphost;
                   14977: 	    }
                   14978: 	    my ($ip_info,$cached)=
                   14979: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14980: 	    if ($cached) {
                   14981: 		%iphost      = %{$ip_info->[0]};
                   14982: 		%name_to_ip  = %{$ip_info->[1]};
                   14983: 		%lonid_to_ip = %{$ip_info->[2]};
                   14984: 		return %iphost;
                   14985: 	    }
                   14986: 	}
1.894     albertel 14987: 
                   14988: 	# get yesterday's info for fallback
                   14989: 	my %old_name_to_ip;
                   14990: 	my ($ip_info,$cached)=
                   14991: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14992: 	if ($cached) {
                   14993: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14994: 	}
                   14995: 
1.1293    raeburn  14996: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14997: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14998: 	    my $ip;
                   14999: 	    if (!exists($name_to_ip{$name})) {
                   15000: 		$ip = gethostbyname($name);
                   15001: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15002: 		    if (defined($old_name_to_ip{$name})) {
                   15003: 			$ip = $old_name_to_ip{$name};
                   15004: 			&logthis("Can't find $name defaulting to old $ip");
                   15005: 		    } else {
                   15006: 			&logthis("Name $name no IP found");
                   15007: 			next;
                   15008: 		    }
                   15009: 		} else {
                   15010: 		    $ip=inet_ntoa($ip);
1.847     albertel 15011: 		}
                   15012: 		$name_to_ip{$name} = $ip;
                   15013: 	    } else {
                   15014: 		$ip = $name_to_ip{$name};
1.653     albertel 15015: 	    }
1.888     albertel 15016: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15017: 		$lonid_to_ip{$id} = $ip;
                   15018: 	    }
                   15019: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15020: 	}
1.1293    raeburn  15021:         unless ($nocache) {
                   15022: 	    &do_cache_new('iphost','iphost',
                   15023: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15024: 		          48*60*60);
                   15025:         }
1.869     albertel 15026: 
1.847     albertel 15027: 	return %iphost;
1.598     albertel 15028:     }
                   15029: 
1.992     raeburn  15030:     #
                   15031:     #  Given a DNS returns the loncapa host name for that DNS 
                   15032:     # 
                   15033:     sub host_from_dns {
                   15034:         my ($dns) = @_;
                   15035:         my @hosts;
                   15036:         my $ip;
                   15037: 
1.993     raeburn  15038:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15039:             $ip = $name_to_ip{$dns};
                   15040:         }
                   15041:         if (!$ip) {
                   15042:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15043:             if (length($ip) == 4) { 
                   15044: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15045:             }
                   15046:         }
                   15047:         if ($ip) {
                   15048: 	    @hosts = get_hosts_from_ip($ip);
                   15049: 	    return $hosts[0];
                   15050:         }
                   15051:         return undef;
1.986     foxr     15052:     }
1.992     raeburn  15053: 
1.1074    raeburn  15054:     sub get_internet_names {
                   15055:         my ($lonid) = @_;
                   15056:         return if ($lonid eq '');
                   15057:         my ($idnref,$cached)=
                   15058:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15059:         if ($cached) {
                   15060:             return $idnref;
                   15061:         }
                   15062:         my $ip = &get_host_ip($lonid);
                   15063:         my @hosts = &get_hosts_from_ip($ip);
                   15064:         my %iphost = &get_iphost();
                   15065:         my (@idns,%seen);
                   15066:         foreach my $id (@hosts) {
                   15067:             my $dom = &host_domain($id);
                   15068:             my $prim_id = &domain($dom,'primary');
                   15069:             my $prim_ip = &get_host_ip($prim_id);
                   15070:             next if ($seen{$prim_ip});
                   15071:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15072:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15073:                     my $intdom = &internet_dom($id);
                   15074:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15075:                         push(@idns,$intdom);
                   15076:                     }
                   15077:                 }
                   15078:             }
                   15079:             $seen{$prim_ip} = 1;
                   15080:         }
1.1219    raeburn  15081:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15082:     }
                   15083: 
1.986     foxr     15084: }
                   15085: 
1.1079    raeburn  15086: sub all_loncaparevs {
1.1249    raeburn  15087:     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  15088: }
                   15089: 
1.1227    raeburn  15090: # ---------------------------------------------------------- Read loncaparev table
                   15091: {
                   15092:     sub load_loncaparevs { 
                   15093:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  15094:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  15095:                 while (my $configline=<$config>) {
                   15096:                     chomp($configline);
                   15097:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15098:                     $loncaparevs{$hostid}=$loncaparev;
                   15099:                 }
                   15100:                 close($config);
                   15101:             }
                   15102:         }
                   15103:     }
                   15104: }
                   15105: 
                   15106: # ---------------------------------------------------------- Read serverhostID table
                   15107: {
                   15108:     sub load_serverhomeIDs {
                   15109:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  15110:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  15111:                 while (my $configline=<$config>) {
                   15112:                     chomp($configline);
                   15113:                     my ($name,$id)=split(/:/,$configline);
                   15114:                     $serverhomeIDs{$name}=$id;
                   15115:                 }
                   15116:                 close($config);
                   15117:             }
                   15118:         }
                   15119:     }
                   15120: }
                   15121: 
                   15122: 
1.862     albertel 15123: BEGIN {
                   15124: 
                   15125: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15126:     unless ($readit) {
                   15127: {
                   15128:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15129:     %perlvar = (%perlvar,%{$configvars});
                   15130: }
                   15131: 
                   15132: 
1.1       albertel 15133: # ------------------------------------------------------ Read spare server file
                   15134: {
1.1359    raeburn  15135:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15136: 
                   15137:     while (my $configline=<$config>) {
                   15138:        chomp($configline);
1.284     matthew  15139:        if ($configline) {
1.784     albertel 15140: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15141: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15142: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15143:        }
                   15144:     }
1.448     albertel 15145:     close($config);
1.1       albertel 15146: }
1.11      www      15147: # ------------------------------------------------------------ Read permissions
                   15148: {
1.1359    raeburn  15149:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15150: 
                   15151:     while (my $configline=<$config>) {
1.448     albertel 15152: 	chomp($configline);
                   15153: 	if ($configline) {
                   15154: 	    my ($role,$perm)=split(/ /,$configline);
                   15155: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15156: 	}
1.11      www      15157:     }
1.448     albertel 15158:     close($config);
1.11      www      15159: }
                   15160: 
                   15161: # -------------------------------------------- Read plain texts for permissions
                   15162: {
1.1359    raeburn  15163:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15164: 
                   15165:     while (my $configline=<$config>) {
1.448     albertel 15166: 	chomp($configline);
                   15167: 	if ($configline) {
1.742     raeburn  15168: 	    my ($short,@plain)=split(/:/,$configline);
                   15169:             %{$prp{$short}} = ();
                   15170: 	    if (@plain > 0) {
                   15171:                 $prp{$short}{'std'} = $plain[0];
                   15172:                 for (my $i=1; $i<@plain; $i++) {
                   15173:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15174:                 }
                   15175:             }
1.448     albertel 15176: 	}
1.135     www      15177:     }
1.448     albertel 15178:     close($config);
1.135     www      15179: }
                   15180: 
                   15181: # ---------------------------------------------------------- Read package table
                   15182: {
1.1359    raeburn  15183:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15184: 
                   15185:     while (my $configline=<$config>) {
1.483     albertel 15186: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15187: 	chomp($configline);
                   15188: 	my ($short,$plain)=split(/:/,$configline);
                   15189: 	my ($pack,$name)=split(/\&/,$short);
                   15190: 	if ($plain ne '') {
                   15191: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15192: 	    $packagetab{$short}=$plain; 
                   15193: 	}
1.11      www      15194:     }
1.448     albertel 15195:     close($config);
1.329     matthew  15196: }
                   15197: 
1.1073    raeburn  15198: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  15199: 
                   15200: &load_loncaparevs();
1.1073    raeburn  15201: 
1.1074    raeburn  15202: # ---------------------------------------------------------- Read serverhostID table
                   15203: 
1.1227    raeburn  15204: &load_serverhomeIDs();
                   15205: 
                   15206: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15207: {
                   15208:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15209:     if (-e $file) {
                   15210:         my $parser = HTML::LCParser->new($file);
                   15211:         while (my $token = $parser->get_token()) {
                   15212:             if ($token->[0] eq 'S') {
                   15213:                 my $item = $token->[1];
                   15214:                 my $name = $token->[2]{'name'};
                   15215:                 my $value = $token->[2]{'value'};
1.1285    raeburn  15216:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  15217:                 my $namematch = $token->[2]{'namematch'};
                   15218:                 if ($item eq 'parameter') {
                   15219:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   15220:                         my $release = $parser->get_text();
                   15221:                         $release =~ s/(^\s*|\s*$ )//gx;
                   15222:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   15223:                     }
                   15224:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  15225:                     my $release = $parser->get_text();
                   15226:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  15227:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  15228:                 }
                   15229:             }
                   15230:         }
                   15231:     }
1.1073    raeburn  15232: }
                   15233: 
1.1138    raeburn  15234: # ---------------------------------------------------------- Read managers table
                   15235: {
                   15236:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  15237:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15238:             while (my $configline=<$config>) {
                   15239:                 chomp($configline);
                   15240:                 next if ($configline =~ /^\#/);
                   15241:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15242:                     $managerstab{$configline} = 1;
                   15243:                 }
                   15244:             }
                   15245:             close($config);
                   15246:         }
                   15247:     }
                   15248: }
                   15249: 
1.329     matthew  15250: # ------------- set up temporary directory
                   15251: {
1.1117    foxr     15252:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15253: 
1.11      www      15254: }
                   15255: 
1.1405    raeburn  15256: # ------------- set default texengine (domain default overrides this)
                   15257: {
                   15258:     $deftex = LONCAPA::texengine();
                   15259: }
                   15260: 
1.1416    raeburn  15261: # ------------- set default minimum length for passwords for internal auth users
                   15262: {
                   15263:     $passwdmin = LONCAPA::passwd_min();
                   15264: }
                   15265: 
1.794     albertel 15266: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15267: 				'compress_threshold'=> 20_000,
                   15268:  			        });
1.185     www      15269: 
1.281     www      15270: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15271: $dumpcount=0;
1.958     www      15272: $locknum=0;
1.22      www      15273: 
1.163     harris41 15274: &logtouch();
1.672     albertel 15275: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15276: $readit=1;
1.564     albertel 15277:     {
                   15278: 	use integer;
                   15279: 	my $test=(2**32)+1;
1.568     albertel 15280: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15281: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15282:     }
1.195     www      15283: }
1.1       albertel 15284: }
1.179     www      15285: 
1.1       albertel 15286: 1;
1.191     harris41 15287: __END__
                   15288: 
1.243     albertel 15289: =pod
                   15290: 
1.191     harris41 15291: =head1 NAME
                   15292: 
1.243     albertel 15293: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15294: 
                   15295: =head1 SYNOPSIS
                   15296: 
1.243     albertel 15297: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15298: 
                   15299:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15300: 
1.243     albertel 15301: Common parameters:
                   15302: 
                   15303: =over 4
                   15304: 
                   15305: =item *
                   15306: 
                   15307: $uname : an internal username (if $cname expecting a course Id specifically)
                   15308: 
                   15309: =item *
                   15310: 
                   15311: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15312: 
                   15313: =item *
                   15314: 
                   15315: $symb : a resource instance identifier
                   15316: 
                   15317: =item *
                   15318: 
                   15319: $namespace : the name of a .db file that contains the data needed or
                   15320: being set.
                   15321: 
                   15322: =back
                   15323: 
1.394     bowersj2 15324: =head1 OVERVIEW
1.191     harris41 15325: 
1.394     bowersj2 15326: lonnet provides subroutines which interact with the
                   15327: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15328: about classes, users, and resources.
1.243     albertel 15329: 
                   15330: For many of these objects you can also use this to store data about
                   15331: them or modify them in various ways.
1.191     harris41 15332: 
1.394     bowersj2 15333: =head2 Symbs
1.191     harris41 15334: 
1.394     bowersj2 15335: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15336: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15337: map, the resource number of the resource in the map, and the URL of
                   15338: the resource itself. The latter is somewhat redundant, but might help
                   15339: if maps change.
                   15340: 
                   15341: An example is
                   15342: 
                   15343:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15344: 
                   15345: The respective map entry is
                   15346: 
                   15347:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15348:   title="Problem 2">
                   15349:  </resource>
                   15350: 
                   15351: Symbs are used by the random number generator, as well as to store and
                   15352: restore data specific to a certain instance of for example a problem.
                   15353: 
                   15354: =head2 Storing And Retrieving Data
                   15355: 
                   15356: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15357: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15358: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15359: is is the non-critical message twin of cstore. These functions are for
                   15360: handlers to store a perl hash to a user's permanent data space in an
                   15361: easy manner, and to retrieve it again on another call. It is expected
                   15362: that a handler would use this once at the beginning to retrieve data,
                   15363: and then again once at the end to send only the new data back.
                   15364: 
                   15365: The data is stored in the user's data directory on the user's
                   15366: homeserver under the ID of the course.
                   15367: 
                   15368: The hash that is returned by restore will have all of the previous
                   15369: value for all of the elements of the hash.
                   15370: 
                   15371: Example:
                   15372: 
                   15373:  #creating a hash
                   15374:  my %hash;
                   15375:  $hash{'foo'}='bar';
                   15376: 
                   15377:  #storing it
                   15378:  &Apache::lonnet::cstore(\%hash);
                   15379: 
                   15380:  #changing a value
                   15381:  $hash{'foo'}='notbar';
                   15382: 
                   15383:  #adding a new value
                   15384:  $hash{'bar'}='foo';
                   15385:  &Apache::lonnet::cstore(\%hash);
                   15386: 
                   15387:  #retrieving the hash
                   15388:  my %history=&Apache::lonnet::restore();
                   15389: 
                   15390:  #print the hash
                   15391:  foreach my $key (sort(keys(%history))) {
                   15392:    print("\%history{$key} = $history{$key}");
                   15393:  }
                   15394: 
                   15395: Will print out:
1.191     harris41 15396: 
1.394     bowersj2 15397:  %history{1:foo} = bar
                   15398:  %history{1:keys} = foo:timestamp
                   15399:  %history{1:timestamp} = 990455579
                   15400:  %history{2:bar} = foo
                   15401:  %history{2:foo} = notbar
                   15402:  %history{2:keys} = foo:bar:timestamp
                   15403:  %history{2:timestamp} = 990455580
                   15404:  %history{bar} = foo
                   15405:  %history{foo} = notbar
                   15406:  %history{timestamp} = 990455580
                   15407:  %history{version} = 2
                   15408: 
                   15409: Note that the special hash entries C<keys>, C<version> and
                   15410: C<timestamp> were added to the hash. C<version> will be equal to the
                   15411: total number of versions of the data that have been stored. The
                   15412: C<timestamp> attribute will be the UNIX time the hash was
                   15413: stored. C<keys> is available in every historical section to list which
                   15414: keys were added or changed at a specific historical revision of a
                   15415: hash.
                   15416: 
                   15417: B<Warning>: do not store the hash that restore returns directly. This
                   15418: will cause a mess since it will restore the historical keys as if the
                   15419: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15420: 
1.394     bowersj2 15421: Calling convention:
1.191     harris41 15422: 
1.1225    raeburn  15423:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15424:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15425: 
1.394     bowersj2 15426: For more detailed information, see lonnet specific documentation.
1.191     harris41 15427: 
1.394     bowersj2 15428: =head1 RETURN MESSAGES
1.191     harris41 15429: 
1.394     bowersj2 15430: =over 4
1.191     harris41 15431: 
1.394     bowersj2 15432: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15433: 
1.394     bowersj2 15434: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15435: when the connection is brought back up
1.191     harris41 15436: 
1.394     bowersj2 15437: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15438: for later delivery
1.191     harris41 15439: 
1.967     bisitz   15440: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15441: 
1.394     bowersj2 15442: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15443: that was requested
1.191     harris41 15444: 
1.243     albertel 15445: =back
1.191     harris41 15446: 
1.243     albertel 15447: =head1 PUBLIC SUBROUTINES
1.191     harris41 15448: 
1.243     albertel 15449: =head2 Session Environment Functions
1.191     harris41 15450: 
1.243     albertel 15451: =over 4
1.191     harris41 15452: 
1.394     bowersj2 15453: =item * 
                   15454: X<appenv()>
1.949     raeburn  15455: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15456: the user envirnoment file, and will be restored for each access this
1.620     albertel 15457: user makes during this session, also modifies the %env for the current
1.949     raeburn  15458: process. Optional rolesarrayref - if defined contains a reference to an array
                   15459: of roles which are exempt from the restriction on modifying user.role entries 
                   15460: in the user's environment.db and in %env.    
1.191     harris41 15461: 
                   15462: =item *
1.394     bowersj2 15463: X<delenv()>
1.987     raeburn  15464: B<delenv($delthis,$regexp)>: removes all items from the session
                   15465: environment file that begin with $delthis. If the 
                   15466: optional second arg - $regexp - is true, $delthis is treated as a 
                   15467: regular expression, otherwise \Q$delthis\E is used. 
                   15468: The values are also deleted from the current processes %env.
1.191     harris41 15469: 
1.795     albertel 15470: =item * get_env_multiple($name) 
                   15471: 
                   15472: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15473: values may be defined and end up as an array ref.
                   15474: 
                   15475: returns an array of values
                   15476: 
1.243     albertel 15477: =back
                   15478: 
                   15479: =head2 User Information
1.191     harris41 15480: 
1.243     albertel 15481: =over 4
1.191     harris41 15482: 
                   15483: =item *
1.394     bowersj2 15484: X<queryauthenticate()>
                   15485: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15486: authentication scheme
                   15487: 
                   15488: =item *
1.394     bowersj2 15489: X<authenticate()>
1.1073    raeburn  15490: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15491: authenticate user from domain's lib servers (first use the current
                   15492: one). C<$upass> should be the users password.
1.1073    raeburn  15493: $checkdefauth is optional (value is 1 if a check should be made to
                   15494:    authenticate user using default authentication method, and allow
                   15495:    account creation if username does not have account in the domain).
                   15496: $clientcancheckhost is optional (value is 1 if checking whether the
                   15497:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15498: 
                   15499: =item *
1.394     bowersj2 15500: X<homeserver()>
                   15501: B<homeserver($uname,$udom)>: find the server which has
                   15502: the user's directory and files (there must be only one), this caches
                   15503: the answer, and also caches if there is a borken connection.
1.191     harris41 15504: 
                   15505: =item *
1.394     bowersj2 15506: X<idget()>
1.1300    raeburn  15507: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   15508: a list of student/employee IDs or clicker IDs
                   15509: (student/employee IDs are a unique resource in a domain, there must be 
                   15510: only 1 ID per username, and only 1 username per ID in a specific domain).
                   15511: clickerIDs are not necessarily unique, as students might share clickers.
                   15512: (returns hash: id=>name,id=>name)
1.191     harris41 15513: 
                   15514: =item *
1.394     bowersj2 15515: X<idrget()>
                   15516: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15517: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15518: 
                   15519: =item *
1.394     bowersj2 15520: X<idput()>
1.1300    raeburn  15521: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   15522: names and associated student/employee IDs or clicker IDs.
                   15523: 
                   15524: =item *
                   15525: X<iddel()>
                   15526: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15527: student/employee ID or clicker ID username look-ups from domain.
                   15528: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15529: If no $uhome is provided, it will be determined usig &homeserver()
                   15530: for each user.  If no $namespace is provided, the default is ids.
                   15531: 
                   15532: =item *
                   15533: X<updateclickers()>
                   15534: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15535: clicker ID-to-username look-ups in clickers.db on library server.
                   15536: Permitted actions are add or del (i.e., add or delete). The 
                   15537: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15538: value is an escaped comma-separated list of usernames (for whom the
                   15539: library server is the homeserver), who registered that particular ID.
                   15540: If $critical is true, the update will be sent via &critical, otherwise
                   15541: &reply() will be used.
1.191     harris41 15542: 
                   15543: =item *
1.394     bowersj2 15544: X<rolesinit()>
1.1169    droeschl 15545: B<rolesinit($udom,$username)>: get user privileges.
                   15546: returns user role, first access and timer interval hashes
1.243     albertel 15547: 
                   15548: =item *
1.1171    droeschl 15549: X<privileged()>
                   15550: B<privileged($username,$domain)>: returns a true if user has a
                   15551: privileged and active role (i.e. su or dc), false otherwise.
                   15552: 
                   15553: =item *
1.551     albertel 15554: X<getsection()>
                   15555: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15556: course $cname, return section name/number or '' for "not in course"
                   15557: and '-1' for "no section"
                   15558: 
                   15559: =item *
1.394     bowersj2 15560: X<userenvironment()>
                   15561: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15562: passed in @what from the requested user's environment, returns a hash
                   15563: 
1.858     raeburn  15564: =item * 
                   15565: X<userlog_query()>
1.859     albertel 15566: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15567: activity.log file. %filters defines filters applied when parsing the
                   15568: log file. These can be start or end timestamps, or the type of action
                   15569: - log to look for Login or Logout events, check for Checkin or
                   15570: Checkout, role for role selection. The response is in the form
                   15571: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15572: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15573: 
1.243     albertel 15574: =back
                   15575: 
                   15576: =head2 User Roles
                   15577: 
                   15578: =over 4
                   15579: 
                   15580: =item *
                   15581: 
1.1284    raeburn  15582: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15583: returns codes for allowed actions.
                   15584: 
                   15585: The first argument is required, all others are optional.
                   15586: 
                   15587: $priv is the privilege being checked.
                   15588: $uri contains additional information about what is being checked for access (e.g.,
                   15589: URL, course ID etc.). 
                   15590: $symb is the unique resource instance identifier in a course; if needed,
                   15591: but not provided, it will be retrieved via a call to &symbread(). 
                   15592: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15593: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15594: files).
                   15595: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15596: prevents recursive calls to &allowed.
                   15597: 
1.243     albertel 15598:  F: full access
                   15599:  U,I,K: authentication modes (cxx only)
                   15600:  '': forbidden
                   15601:  1: user needs to choose course
                   15602:  2: browse allowed
1.766     albertel 15603:  A: passphrase authentication needed
1.1284    raeburn  15604:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  15605:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15606: 
                   15607: =item *
                   15608: 
1.1192    raeburn  15609: constructaccess($url,$setpriv) : check for access to construction space URL
                   15610: 
                   15611: See if the owner domain and name in the URL match those in the
                   15612: expected environment.  If so, return three element list
                   15613: ($ownername,$ownerdomain,$ownerhome).
                   15614: 
                   15615: Otherwise return the null string.
                   15616: 
                   15617: If second argument 'setpriv' is true, it assigns the privileges,
                   15618: and returns the same three element list, unless the owner has
                   15619: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15620: in which case the null string is returned.
                   15621: 
                   15622: =item *
                   15623: 
1.1326    raeburn  15624: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15625: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15626: for system, domain, and course level. $uname and $udom are optional (current
                   15627: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15628: 
                   15629: =item *
                   15630: 
1.988     raeburn  15631: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15632: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15633: $type is Course (default) or Community.
1.988     raeburn  15634: If $forcedefault evaluates to true, text returned will be default 
                   15635: text for $type. Otherwise, if this is a course, the text returned 
                   15636: will be a custom name for the role (if defined in the course's 
                   15637: environment).  If no custom name is defined the default is returned.
                   15638:    
1.832     raeburn  15639: =item *
                   15640: 
1.1219    raeburn  15641: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15642: All arguments are optional. Returns a hash of a roles, either for
                   15643: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15644: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15645: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15646: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15647: For each key, value is set to colon-separated start and end times for
                   15648: the role.  If no username and domain are specified, will default to
1.934     raeburn  15649: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15650: of role statuses (active, future or previous), roles 
                   15651: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15652: to restrict the list of roles reported. If no array ref is 
                   15653: provided for types, will default to return only active roles.
1.834     albertel 15654: 
1.1195    raeburn  15655: =item *
                   15656: 
                   15657: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  15658: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   15659: 
                   15660: Additional optional arguments are: $type (if role checking is to be restricted 
                   15661: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  15662: available roles) or future (roles available in the future), and
                   15663: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  15664: have active Domain Coordinator role in course's domain or in additional
                   15665: domains (specified in 'Domains to check for privileged users' in course
                   15666: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15667: 
                   15668: =item *
                   15669: 
                   15670: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15671: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15672: $possdomains and $possroles are optional array refs -- to domains to check and
                   15673: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15674: users' roles.db to check for a dc or su role in any domain. This can be
                   15675: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15676: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15677: this then allows &privileged_by_domain() to be used, which caches the identity
                   15678: of privileged users, eliminating the need for repeated calls to &dump().
                   15679: 
                   15680: =item *
                   15681: 
                   15682: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15683: where the outer hash keys are domains specified in the $possdomains array ref,
                   15684: next inner hash keys are privileged roles specified in the $roles array ref,
                   15685: and the innermost hash contains key = value pairs for username:domain = end:start
                   15686: for active or future "privileged" users with that role in that domain. To avoid
                   15687: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15688: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  15689: 
1.243     albertel 15690: =back
                   15691: 
                   15692: =head2 User Modification
                   15693: 
                   15694: =over 4
                   15695: 
                   15696: =item *
                   15697: 
1.957     raeburn  15698: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15699: user for the level given by URL.  Optional start and end dates (leave empty
                   15700: string or zero for "no date")
1.191     harris41 15701: 
                   15702: =item *
                   15703: 
1.243     albertel 15704: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15705: change a users, password, possible return values are: ok,
                   15706: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15707: refused
1.191     harris41 15708: 
                   15709: =item *
                   15710: 
1.243     albertel 15711: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15712: 
                   15713: =item *
                   15714: 
1.1058    raeburn  15715: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15716:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15717: 
                   15718: will update user information (firstname,middlename,lastname,generation,
                   15719: permanentemail), and if forceid is true, student/employee ID also.
                   15720: A user's institutional affiliation(s) can also be updated.
                   15721: User information fields will not be overwritten with empty entries 
                   15722: unless the field is included in the $candelete array reference.
                   15723: This array is included when a single user is modified via "Manage Users",
                   15724: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15725: 
                   15726: =item *
                   15727: 
1.286     matthew  15728: modifystudent
                   15729: 
1.957     raeburn  15730: modify a student's enrollment and identification information.
1.1235    raeburn  15731: The course id is resolved based on the current user's environment.  
                   15732: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15733: associated with a course.
                   15734: 
1.297     matthew  15735: This call is essentially a wrapper for lonnet::modifyuser and
                   15736: lonnet::modify_student_enrollment
1.286     matthew  15737: 
                   15738: Inputs: 
                   15739: 
                   15740: =over 4
                   15741: 
1.957     raeburn  15742: =item B<$udom> Student's loncapa domain
1.286     matthew  15743: 
1.957     raeburn  15744: =item B<$uname> Student's loncapa login name
1.286     matthew  15745: 
1.964     bisitz   15746: =item B<$uid> Student/Employee ID
1.286     matthew  15747: 
1.957     raeburn  15748: =item B<$umode> Student's authentication mode
1.286     matthew  15749: 
1.957     raeburn  15750: =item B<$upass> Student's password
1.286     matthew  15751: 
1.957     raeburn  15752: =item B<$first> Student's first name
1.286     matthew  15753: 
1.957     raeburn  15754: =item B<$middle> Student's middle name
1.286     matthew  15755: 
1.957     raeburn  15756: =item B<$last> Student's last name
1.286     matthew  15757: 
1.957     raeburn  15758: =item B<$gene> Student's generation
1.286     matthew  15759: 
1.957     raeburn  15760: =item B<$usec> Student's section in course
1.286     matthew  15761: 
                   15762: =item B<$end> Unix time of the roles expiration
                   15763: 
                   15764: =item B<$start> Unix time of the roles start date
                   15765: 
                   15766: =item B<$forceid> If defined, allow $uid to be changed
                   15767: 
                   15768: =item B<$desiredhome> server to use as home server for student
                   15769: 
1.957     raeburn  15770: =item B<$email> Student's permanent e-mail address
                   15771: 
                   15772: =item B<$type> Type of enrollment (auto or manual)
                   15773: 
1.963     raeburn  15774: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15775: 
                   15776: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15777: 
1.963     raeburn  15778: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15779: 
1.963     raeburn  15780: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15781: 
1.1216    raeburn  15782: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15783: 
                   15784: =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  15785: 
1.286     matthew  15786: =back
1.297     matthew  15787: 
                   15788: =item *
                   15789: 
                   15790: modify_student_enrollment
                   15791: 
1.1235    raeburn  15792: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15793: 'role.request.course' must be defined for this function to proceed.
                   15794: 
                   15795: Inputs:
                   15796: 
                   15797: =over 4
                   15798: 
1.1235    raeburn  15799: =item $udom, student's domain
1.297     matthew  15800: 
1.1235    raeburn  15801: =item $uname, student's name
1.297     matthew  15802: 
1.1235    raeburn  15803: =item $uid, student's user id
1.297     matthew  15804: 
1.1235    raeburn  15805: =item $first, student's first name
1.297     matthew  15806: 
                   15807: =item $middle
                   15808: 
                   15809: =item $last
                   15810: 
                   15811: =item $gene
                   15812: 
                   15813: =item $usec
                   15814: 
                   15815: =item $end
                   15816: 
                   15817: =item $start
                   15818: 
1.957     raeburn  15819: =item $type
                   15820: 
                   15821: =item $locktype
                   15822: 
                   15823: =item $cid
                   15824: 
                   15825: =item $selfenroll
                   15826: 
                   15827: =item $context
                   15828: 
1.1216    raeburn  15829: =item $credits, number of credits student will earn from this class
                   15830: 
1.1314    raeburn  15831: =item $instsec, institutional course section code for student
                   15832: 
1.297     matthew  15833: =back
                   15834: 
1.191     harris41 15835: 
                   15836: =item *
                   15837: 
1.243     albertel 15838: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15839: custom role; give a custom role to a user for the level given by URL.  Specify
                   15840: name and domain of role author, and role name
1.191     harris41 15841: 
                   15842: =item *
                   15843: 
1.243     albertel 15844: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15845: 
                   15846: =item *
                   15847: 
1.243     albertel 15848: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15849: 
                   15850: =back
                   15851: 
                   15852: =head2 Course Infomation
                   15853: 
                   15854: =over 4
1.191     harris41 15855: 
                   15856: =item *
                   15857: 
1.1118    foxr     15858: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15859: specified course id, including all environment settings for the
                   15860: course, the description of the course will be in the hash under the
                   15861: key 'description'
1.191     harris41 15862: 
1.1118    foxr     15863: $options is an optional parameter that if supplied is a hash reference that controls
                   15864: what how this function works.  It has the following key/values:
                   15865: 
                   15866: =over 4
                   15867: 
                   15868: =item freshen_cache
                   15869: 
                   15870: If defined, and the environment cache for the course is valid, it is 
                   15871: returned in the returned hash.
                   15872: 
                   15873: =item one_time
                   15874: 
                   15875: If defined, the last cache time is set to _now_
                   15876: 
                   15877: =item user
                   15878: 
                   15879: If defined, the supplied username is used instead of the current user.
                   15880: 
                   15881: 
                   15882: =back
                   15883: 
1.191     harris41 15884: =item *
                   15885: 
1.624     albertel 15886: resdata($name,$domain,$type,@which) : request for current parameter
                   15887: setting for a specific $type, where $type is either 'course' or 'user',
                   15888: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15889: answers for 10 minutes.
1.243     albertel 15890: 
1.877     foxr     15891: =item *
                   15892: 
                   15893: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15894: data base, returning a hash that is keyed by the resource name and has
                   15895: values that are the resource value.  I believe that the timestamps and
                   15896: versions are also returned.
                   15897: 
1.1236    raeburn  15898: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15899: supplemental content area. This routine caches the number of files for 
                   15900: 10 minutes.
                   15901: 
1.243     albertel 15902: =back
                   15903: 
                   15904: =head2 Course Modification
                   15905: 
                   15906: =over 4
1.191     harris41 15907: 
                   15908: =item *
                   15909: 
1.243     albertel 15910: writecoursepref($courseid,%prefs) : write preferences (environment
                   15911: database) for a course
1.191     harris41 15912: 
                   15913: =item *
                   15914: 
1.1011    raeburn  15915: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15916: 
                   15917: =item *
                   15918: 
1.1038    raeburn  15919: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15920: 
1.1167    droeschl 15921: =item *
                   15922: 
                   15923: is_course($courseid), is_course($cdom, $cnum)
                   15924: 
                   15925: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15926: two component version $cdom, $cnum. It checks if the specified course exists.
                   15927: 
                   15928: Returns:
                   15929:     undef if the course doesn't exist, otherwise
                   15930:     in scalar context the combined courseid.
                   15931:     in list context the two components of the course identifier, domain and 
                   15932:     courseid.    
                   15933: 
1.243     albertel 15934: =back
                   15935: 
1.1401    raeburn  15936: =head2 Bubblesheet Configuration
                   15937: 
                   15938: =over 4
                   15939: 
                   15940: =item *
                   15941: 
                   15942: get_scantron_config($which)
                   15943: 
                   15944: $which - the name of the configuration to parse from the file.
                   15945: 
                   15946: Parses and returns the bubblesheet configuration line selected as a
                   15947: hash of configuration file fields.
                   15948: 
                   15949: 
                   15950: Returns:
                   15951:     If the named configuration is not in the file, an empty
                   15952:     hash is returned.
                   15953: 
                   15954:     a hash with the fields
                   15955:       name         - internal name for the this configuration setup
                   15956:       description  - text to display to operator that describes this config
                   15957:       CODElocation - if 0 or the string 'none'
                   15958:                           - no CODE exists for this config
                   15959:                      if -1 || the string 'letter'
                   15960:                           - a CODE exists for this config and is
                   15961:                             a string of letters
                   15962:                      Unsupported value (but planned for future support)
                   15963:                           if a positive integer
                   15964:                                - The CODE exists as the first n items from
                   15965:                                  the question section of the form
                   15966:                           if the string 'number'
                   15967:                                - The CODE exists for this config and is
                   15968:                                  a string of numbers
                   15969:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15970:                      the CODE starts
                   15971:       CODElength  - length of the CODE
                   15972:       IDstart     - column where the student/employee ID starts
                   15973:       IDlength    - length of the student/employee ID info
                   15974:       Qstart      - column where the information from the bubbled
                   15975:                     'questions' start
                   15976:       Qlength     - number of columns comprising a single bubble line from
                   15977:                     the sheet. (usually either 1 or 10)
                   15978:       Qon         - either a single character representing the character used
                   15979:                     to signal a bubble was chosen in the positional setup, or
                   15980:                     the string 'letter' if the letter of the chosen bubble is
                   15981:                     in the final, or 'number' if a number representing the
                   15982:                     chosen bubble is in the file (1->A 0->J)
                   15983:       Qoff        - the character used to represent that a bubble was
                   15984:                     left blank
                   15985:       PaperID     - if the scanning process generates a unique number for each
                   15986:                     sheet scanned the column that this ID number starts in
                   15987:       PaperIDlength - number of columns that comprise the unique ID number
                   15988:                       for the sheet of paper
                   15989:       FirstName   - column that the first name starts in
                   15990:       FirstNameLength - number of columns that the first name spans
                   15991:       LastName    - column that the last name starts in
                   15992:       LastNameLength - number of columns that the last name spans
                   15993:       BubblesPerRow - number of bubbles available in each row used to
                   15994:                       bubble an answer. (If not specified, 10 assumed).
                   15995: 
                   15996: 
                   15997: =item *
                   15998: 
                   15999: get_scantronformat_file($cdom)
                   16000: 
                   16001: $cdom - the course's domain (optional); if not supplied, uses
                   16002: domain for current $env{'request.course.id'}.
                   16003: 
                   16004: Returns an array containing lines from the scantron format file for
                   16005: the domain of the course.
                   16006: 
                   16007: If a url for a custom.tab file is listed in domain's configuration.db,
                   16008: lines are from this file.
                   16009: 
                   16010: Otherwise, if a default.tab has been published in RES space by the
                   16011: domainconfig user, lines are from this file.
                   16012: 
                   16013: Otherwise, fall back to getting lines from the legacy file on the
                   16014: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16015: 
                   16016: =back
                   16017: 
1.243     albertel 16018: =head2 Resource Subroutines
                   16019: 
                   16020: =over 4
1.191     harris41 16021: 
                   16022: =item *
                   16023: 
1.243     albertel 16024: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16025: 
                   16026: =item *
                   16027: 
1.243     albertel 16028: repcopy($filename) : subscribes to the requested file, and attempts to
                   16029: replicate from the owning library server, Might return
1.607     raeburn  16030: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16031: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16032: resource. Expects the local filesystem pathname
                   16033: (/home/httpd/html/res/....)
                   16034: 
                   16035: =back
                   16036: 
                   16037: =head2 Resource Information
                   16038: 
                   16039: =over 4
1.191     harris41 16040: 
                   16041: =item *
                   16042: 
1.1228    raeburn  16043: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16044: and returns the value of a variety of different possible values,
                   16045: $varname should be a request string, and the other parameters can be
                   16046: used to specify who and what one is asking about. Ordinarily, $cid 
                   16047: does not need to be specified, as it is retrived from 
                   16048: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16049: within lonuserstate::loadmap() when initializing a course, before
                   16050: $env{'request.course.id'} has been set, so it needs to be provided
                   16051: in that one case.
1.243     albertel 16052: 
                   16053: Possible values for $varname are environment.lastname (or other item
                   16054: from the envirnment hash), user.name (or someother aspect about the
                   16055: user), resource.0.maxtries (or some other part and parameter of a
                   16056: resource)
1.204     albertel 16057: 
                   16058: =item *
                   16059: 
1.243     albertel 16060: directcondval($number) : get current value of a condition; reads from a state
                   16061: string
1.204     albertel 16062: 
                   16063: =item *
                   16064: 
1.243     albertel 16065: condval($condidx) : value of condition index based on state
1.204     albertel 16066: 
                   16067: =item *
                   16068: 
1.1362    raeburn  16069: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16070: resource's metadata, $what should be either a specific key, or either
                   16071: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  16072: packages that this resource currently uses, the last 3 arguments are 
                   16073: only used internally for recursive metadata.
                   16074: 
                   16075: the toolsymb is only used where the uri is for an external tool (for which
                   16076: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16077: 
1.1371    raeburn  16078: this function automatically caches all requests except any made recursively
                   16079: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   16080: defined).
1.191     harris41 16081: 
                   16082: =item *
                   16083: 
1.243     albertel 16084: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16085: network of library servers; returns file handle of where SQL and regex results
                   16086: will be stored for query
1.191     harris41 16087: 
                   16088: =item *
                   16089: 
1.1282    raeburn  16090: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   16091: return symbolic list entry (all arguments optional). 
                   16092: 
                   16093: Args: filename is the filename (including path) for the file for which a symb 
                   16094: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   16095: to check access status if more than one resource was found in the bighash 
                   16096: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   16097: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   16098: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16099: cause possible symbs to be checked to determine if they are subject to content
                   16100: blocking, if so they will not be included as possible symbs; possibles is a
                   16101: ref to a hash, which, as a side effect, will be populated with all possible 
                   16102: symbs (content blocking not tested).
                   16103:  
1.243     albertel 16104: returns the data handle
1.191     harris41 16105: 
                   16106: =item *
                   16107: 
1.1190    raeburn  16108: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   16109: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16110: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  16111: on failure, user must be in a course, as it assumes the existence of
                   16112: the course initial hash, and uses $env('request.course.id'}.  The third
                   16113: arg is an optional reference to a scalar.  If this arg is passed in the 
                   16114: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16115: encrypted; otherwise it will be null.  
1.191     harris41 16116: 
                   16117: =item *
                   16118: 
1.243     albertel 16119: symbclean($symb) : removes versions numbers from a symb, returns the
                   16120: cleaned symb
1.191     harris41 16121: 
                   16122: =item *
                   16123: 
1.243     albertel 16124: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16125: course map, user must be in a course for it to work.
1.191     harris41 16126: 
                   16127: =item *
                   16128: 
1.243     albertel 16129: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16130: 
                   16131: =item *
                   16132: 
1.243     albertel 16133: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16134: a random seed, all arguments are optional, if they aren't sent it uses the
                   16135: environment to derive them. Note: if symb isn't sent and it can't get one
                   16136: from &symbread it will use the current time as its return value
1.191     harris41 16137: 
                   16138: =item *
                   16139: 
1.243     albertel 16140: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16141: unfakeable, receipt
1.191     harris41 16142: 
                   16143: =item *
                   16144: 
1.620     albertel 16145: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16146: 
                   16147: =item *
                   16148: 
1.243     albertel 16149: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16150: 
                   16151: =item *
                   16152: 
1.243     albertel 16153: 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 16154: 
                   16155: =item *
                   16156: 
1.243     albertel 16157: 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 16158: 
                   16159: =item *
                   16160: 
1.243     albertel 16161: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16162: 
                   16163: =item *
                   16164: 
1.243     albertel 16165: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16166: forcing spreadsheet to reevaluate the resource scores next time.
                   16167: 
1.1195    raeburn  16168: =item * 
                   16169: 
1.1196    raeburn  16170: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16171: when viewing in course context.
1.1195    raeburn  16172: 
1.1196    raeburn  16173:  input: six args -- filename (decluttered), course number, course domain,
                   16174:                     url, symb (if registered) and group (if this is a 
                   16175:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  16176: 
1.1196    raeburn  16177:  output: array of five scalars --
1.1195    raeburn  16178:          $cfile -- url for file editing if editable on current server
                   16179:          $home -- homeserver of resource (i.e., for author if published,
                   16180:                                           or course if uploaded.).
                   16181:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  16182:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   16183:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  16184: 
                   16185: =item *
                   16186: 
                   16187: is_course_upload($file,$cnum,$cdom)
                   16188: 
                   16189: Used in course context to determine if current file was uploaded to 
                   16190: the course (i.e., would be found in /userfiles/docs on the course's 
                   16191: homeserver.
                   16192: 
                   16193:   input: 3 args -- filename (decluttered), course number and course domain.
                   16194:   output: boolean -- 1 if file was uploaded.
                   16195: 
1.243     albertel 16196: =back
                   16197: 
                   16198: =head2 Storing/Retreiving Data
                   16199: 
                   16200: =over 4
1.191     harris41 16201: 
                   16202: =item *
                   16203: 
1.1269    raeburn  16204: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   16205: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16206: the remaining args aren't required and if they aren't passed or are '' they will
                   16207: be derived from the env (with the exception of $laststore, which is an 
                   16208: optional arg used when a user's submission is stored in grading).
                   16209: $laststore is $version=$timestamp, where $version is the most recent version
                   16210: number retrieved for the corresponding $symb in the $namespace db file, and
                   16211: $timestamp is the timestamp for that transaction (UNIX time).
                   16212: $laststore is currently only passed when cstore() is called by 
                   16213: structuretags::finalize_storage().
1.191     harris41 16214: 
                   16215: =item *
                   16216: 
1.1269    raeburn  16217: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   16218: but uses critical subroutine
1.191     harris41 16219: 
                   16220: =item *
                   16221: 
1.243     albertel 16222: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16223: all args are optional
1.191     harris41 16224: 
                   16225: =item *
                   16226: 
1.717     albertel 16227: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16228: dumps the complete (or key matching regexp) namespace into a hash
                   16229: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16230: normally &store()ed into
                   16231: 
                   16232: $range should be either an integer '100' (give me the first 100
                   16233:                                            matching records)
                   16234:               or be  two integers sperated by a - with no spaces
                   16235:                  '30-50' (give me the 30th through the 50th matching
                   16236:                           records)
                   16237: 
                   16238: 
                   16239: =item *
                   16240: 
1.1269    raeburn  16241: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16242: replaces a &store() version of data with a replacement set of data
                   16243: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  16244: reference. If $tolog is true, the transaction is logged in the courselog
                   16245: with an action=PUTSTORE.
1.717     albertel 16246: 
                   16247: =item *
                   16248: 
1.243     albertel 16249: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16250: works very similar to store/cstore, but all data is stored in a
                   16251: temporary location and can be reset using tmpreset, $storehash should
                   16252: be a hash reference, returns nothing on success
1.191     harris41 16253: 
                   16254: =item *
                   16255: 
1.243     albertel 16256: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16257: similar to restore, but all data is stored in a temporary location and
                   16258: can be reset using tmpreset. Returns a hash of values on success,
                   16259: error string otherwise.
1.191     harris41 16260: 
                   16261: =item *
                   16262: 
1.243     albertel 16263: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16264: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16265: 
                   16266: =item *
                   16267: 
1.243     albertel 16268: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16269: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16270: 
                   16271: =item *
                   16272: 
1.243     albertel 16273: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16274: namesp ($udom and $uname are optional)
1.191     harris41 16275: 
                   16276: =item *
                   16277: 
1.702     albertel 16278: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16279: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16280: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16281: 
1.702     albertel 16282: $range should be either an integer '100' (give me the first 100
                   16283:                                            matching records)
                   16284:               or be  two integers sperated by a - with no spaces
                   16285:                  '30-50' (give me the 30th through the 50th matching
                   16286:                           records)
1.449     matthew  16287: =item *
                   16288: 
                   16289: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16290: $store can be a scalar, an array reference, or if the amount to be 
                   16291: incremented is > 1, a hash reference.
                   16292: 
                   16293: ($udom and $uname are optional)
1.191     harris41 16294: 
                   16295: =item *
                   16296: 
1.243     albertel 16297: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16298: ($udom and $uname are optional)
1.191     harris41 16299: 
                   16300: =item *
                   16301: 
1.243     albertel 16302: cput($namespace,$storehash,$udom,$uname) : critical put
                   16303: ($udom and $uname are optional)
1.191     harris41 16304: 
                   16305: =item *
                   16306: 
1.748     albertel 16307: newput($namespace,$storehash,$udom,$uname) :
                   16308: 
                   16309: Attempts to store the items in the $storehash, but only if they don't
                   16310: currently exist, if this succeeds you can be certain that you have 
                   16311: successfully created a new key value pair in the $namespace db.
                   16312: 
                   16313: 
                   16314: Args:
                   16315:  $namespace: name of database to store values to
                   16316:  $storehash: hashref to store to the db
                   16317:  $udom: (optional) domain of user containing the db
                   16318:  $uname: (optional) name of user caontaining the db
                   16319: 
                   16320: Returns:
                   16321:  'ok' -> succeeded in storing all keys of $storehash
                   16322:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16323:                         least <key> already existed in the db (other
                   16324:                         requested keys may also already exist)
1.967     bisitz   16325:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16326:  'con_lost' -> unable to contact request server
                   16327:  'refused' -> action was not allowed by remote machine
                   16328: 
                   16329: 
                   16330: =item *
                   16331: 
1.243     albertel 16332: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16333: reference filled in from namesp (encrypts the return communication)
                   16334: ($udom and $uname are optional)
1.191     harris41 16335: 
                   16336: =item *
                   16337: 
1.243     albertel 16338: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16339: critical subroutine
                   16340: 
1.806     raeburn  16341: =item *
                   16342: 
1.860     raeburn  16343: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16344: array reference filled in from namespace found in domain level on either
                   16345: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16346: 
                   16347: =item *
                   16348: 
1.860     raeburn  16349: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16350: domain level either on specified domain server ($uhome) or primary domain 
                   16351: server ($udom and $uhome are optional)
1.806     raeburn  16352: 
1.943     raeburn  16353: =item * 
                   16354: 
1.1240    raeburn  16355: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16356: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16357: the target domain.
                   16358: 
                   16359: May also include additional key => value pairs for the following groups:
                   16360: 
                   16361: =over
                   16362: 
                   16363: =item
                   16364: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16365: 
                   16366: =over
                   16367: 
                   16368: =item defaultquota, authorquota
                   16369: 
                   16370: =back
                   16371: 
                   16372: =item
                   16373: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16374: portfolio for users).
                   16375: 
                   16376: =over
                   16377: 
                   16378: =item
                   16379: aboutme, blog, webdav, portfolio
                   16380: 
                   16381: =back
                   16382: 
                   16383: =item
                   16384: requestcourses: ability to request courses, and how requests are processed.
                   16385: 
                   16386: =over
                   16387: 
                   16388: =item
1.1305    raeburn  16389: official, unofficial, community, textbook, placement
1.1240    raeburn  16390: 
                   16391: =back
                   16392: 
                   16393: =item
                   16394: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16395: 
                   16396: =over
                   16397: 
                   16398: =item
1.1256    raeburn  16399: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16400: 
                   16401: =back
                   16402: 
                   16403: =item
                   16404: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16405: for course's uploaded content.
                   16406: 
                   16407: =over
                   16408: 
                   16409: =item
1.1246    raeburn  16410: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16411: communityquota, textbookquota, placementquota
1.1240    raeburn  16412: 
                   16413: =back
                   16414: 
                   16415: =item
                   16416: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16417: on your servers.
                   16418: 
                   16419: =over
                   16420: 
                   16421: =item 
                   16422: remotesessions, hostedsessions
                   16423: 
                   16424: =back
                   16425: 
                   16426: =back
                   16427: 
                   16428: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16429: utility to create a configuration.db file on a domain's primary library server 
                   16430: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16431: -- corresponding values are authentication type (internal, krb4, krb5,
                   16432: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16433: will be available. Values are retrieved from cache (if current), unless the
                   16434: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16435: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16436: 
                   16437: Typical usage:
1.943     raeburn  16438: 
1.1240    raeburn  16439: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16440: 
1.243     albertel 16441: =back
                   16442: 
                   16443: =head2 Network Status Functions
                   16444: 
                   16445: =over 4
1.191     harris41 16446: 
                   16447: =item *
                   16448: 
1.1137    raeburn  16449: dirlist() : return directory list based on URI (first arg).
                   16450: 
                   16451: Inputs: 1 required, 5 optional.
                   16452: 
                   16453: =over
                   16454: 
                   16455: =item 
                   16456: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16457: 
                   16458: =item
                   16459: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16460: 
                   16461: =item
                   16462: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16463: 
                   16464: =item
                   16465: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16466: 
                   16467: =item
                   16468: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16469: 
                   16470: =item 
                   16471: $alternateRoot - path to prepend in place of path from $uri.
                   16472: 
                   16473: =back
                   16474: 
                   16475: Returns: Array of up to two items.
                   16476: 
                   16477: =over
                   16478: 
                   16479: a reference to an array of files/subdirectories
                   16480: 
                   16481: =over
                   16482: 
                   16483: Each element in the array of files/subdirectories is a & separated list of
                   16484: item name and the result of running stat on the item.  If dirlist was requested
                   16485: for a file instead of a directory, the item name will be ''. For a directory 
                   16486: listing, if the item is a metadata file, the element will end &N&M 
                   16487: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16488: default copyright set (1).  
                   16489: 
                   16490: =back
                   16491: 
                   16492: a scalar containing error condition (if encountered).
                   16493: 
                   16494: =over
                   16495: 
                   16496: =item 
                   16497: no_host (no homeserver identified for $username:$domain).
                   16498: 
                   16499: =item 
                   16500: no_such_host (server contacted for listing not identified as valid host).
                   16501: 
                   16502: =item 
                   16503: con_lost (connection to remote server failed).
                   16504: 
                   16505: =item 
                   16506: refused (invalid $username:$domain received on lond side).
                   16507: 
                   16508: =item 
                   16509: no_such_dir (directory at specified path on lond side does not exist). 
                   16510: 
                   16511: =item 
                   16512: empty (directory at specified path on lond side is empty).
                   16513: 
                   16514: =over
                   16515: 
                   16516: This is currently not encountered because the &ls3, &ls2, 
                   16517: &ls (_handler) routines on the lond side do not filter out
                   16518: . and .. from a directory listing. 
                   16519: 
                   16520: =back
                   16521: 
                   16522: =back
                   16523: 
                   16524: =back
1.191     harris41 16525: 
                   16526: =item *
                   16527: 
1.243     albertel 16528: spareserver() : find server with least workload from spare.tab
                   16529: 
1.986     foxr     16530: 
                   16531: =item *
                   16532: 
                   16533: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16534: if there is no corresponding loncapa host.
                   16535: 
1.243     albertel 16536: =back
                   16537: 
1.986     foxr     16538: 
1.243     albertel 16539: =head2 Apache Request
                   16540: 
                   16541: =over 4
1.191     harris41 16542: 
                   16543: =item *
                   16544: 
1.243     albertel 16545: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16546: localhost, posts hash
                   16547: 
                   16548: =back
                   16549: 
                   16550: =head2 Data to String to Data
                   16551: 
                   16552: =over 4
1.191     harris41 16553: 
                   16554: =item *
                   16555: 
1.243     albertel 16556: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16557: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16558: 
                   16559: =item *
                   16560: 
1.243     albertel 16561: hashref2str($hashref) : convert a hashref into a string complete with
                   16562: escaping and '=' and '&' separators, supports elements that are
                   16563: arrayrefs and hashrefs
1.191     harris41 16564: 
                   16565: =item *
                   16566: 
1.243     albertel 16567: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16568: with escaping and '&' separators, supports elements that are arrayrefs
                   16569: and hashrefs
1.191     harris41 16570: 
                   16571: =item *
                   16572: 
1.243     albertel 16573: str2hash($string) : convert string to hash using unescaping and
                   16574: splitting on '=' and '&', supports elements that are arrayrefs and
                   16575: hashrefs
1.191     harris41 16576: 
                   16577: =item *
                   16578: 
1.243     albertel 16579: str2array($string) : convert string to hash using unescaping and
                   16580: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16581: 
                   16582: =back
                   16583: 
                   16584: =head2 Logging Routines
                   16585: 
                   16586: 
                   16587: These routines allow one to make log messages in the lonnet.log and
                   16588: lonnet.perm logfiles.
1.191     harris41 16589: 
1.1119    foxr     16590: =over 4
                   16591: 
1.191     harris41 16592: =item *
                   16593: 
1.243     albertel 16594: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16595: 
                   16596: =item *
                   16597: 
1.243     albertel 16598: logthis() : append message to the normal lonnet.log file, it gets
                   16599: preiodically rolled over and deleted.
1.191     harris41 16600: 
                   16601: =item *
                   16602: 
1.243     albertel 16603: logperm() : append a permanent message to lonnet.perm.log, this log
                   16604: file never gets deleted by any automated portion of the system, only
                   16605: messages of critical importance should go in here.
                   16606: 
1.1119    foxr     16607: 
1.243     albertel 16608: =back
                   16609: 
                   16610: =head2 General File Helper Routines
                   16611: 
                   16612: =over 4
1.191     harris41 16613: 
                   16614: =item *
                   16615: 
1.481     raeburn  16616: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16617: (a) files in /uploaded
                   16618:   (i) If a local copy of the file exists - 
                   16619:       compares modification date of local copy with last-modified date for 
                   16620:       definitive version stored on home server for course. If local copy is 
                   16621:       stale, requests a new version from the home server and stores it. 
                   16622:       If the original has been removed from the home server, then local copy 
                   16623:       is unlinked.
                   16624:   (ii) If local copy does not exist -
                   16625:       requests the file from the home server and stores it. 
                   16626:   
                   16627:   If $caller is 'uploadrep':  
                   16628:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16629:     for request for files originally uploaded via DOCS. 
                   16630:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16631:   
                   16632:   Otherwise:
                   16633:      This indicates a call from the content generation phase of the request.
                   16634:      -  returns the entire contents of the file or -1.
                   16635:      
                   16636: (b) files in /res
                   16637:    - returns the entire contents of a file or -1; 
                   16638:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16639: 
1.712     albertel 16640: 
                   16641: =item *
                   16642: 
                   16643: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16644:                   reference
                   16645: 
                   16646: returns either a stat() list of data about the file or an empty list
                   16647: if the file doesn't exist or couldn't find out about it (connection
                   16648: problems or user unknown)
                   16649: 
1.191     harris41 16650: =item *
                   16651: 
1.243     albertel 16652: filelocation($dir,$file) : returns file system location of a file
                   16653: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16654: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16655: and a file of ../bob will become /a/bob)
1.191     harris41 16656: 
                   16657: =item *
                   16658: 
                   16659: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16660: filelocation except for hrefs
                   16661: 
                   16662: =item *
                   16663: 
1.1261    raeburn  16664: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16665: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16666: 
1.243     albertel 16667: =back
                   16668: 
1.608     albertel 16669: =head2 Usererfile file routines (/uploaded*)
                   16670: 
                   16671: =over 4
                   16672: 
                   16673: =item *
                   16674: 
                   16675: userfileupload(): main rotine for putting a file in a user or course's
                   16676:                   filespace, arguments are,
                   16677: 
1.620     albertel 16678:  formname - required - this is the name of the element in $env where the
1.608     albertel 16679:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16680:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16681:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16682:  context - if coursedoc, store the file in the course of the active role
                   16683:              of the current user; 
                   16684:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16685:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16686:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16687:          if undefined, it will be placed in "unknown"
                   16688: 
                   16689:  (This routine calls clean_filename() to remove any dangerous
                   16690:  characters from the filename, and then calls finuserfileupload() to
                   16691:  complete the transaction)
                   16692: 
                   16693:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16694:  and /adm/notfound.html if unsuccessful
                   16695: 
                   16696: =item *
                   16697: 
                   16698: clean_filename(): routine for cleaing a filename up for storage in
                   16699:                  userfile space, argument is:
                   16700: 
                   16701:  filename - proposed filename
                   16702: 
                   16703: returns: the new clean filename
                   16704: 
                   16705: =item *
                   16706: 
1.1090    raeburn  16707: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16708: userspace, probably shouldn't be called directly
                   16709: 
                   16710:   docuname: username or courseid of destination for the file
                   16711:   docudom: domain of user/course of destination for the file
                   16712:   formname: same as for userfileupload()
1.1090    raeburn  16713:   fname: filename (including subdirectories) for the file
                   16714:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  16715:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16716:   allfiles: reference to hash used to store objects found by parser
                   16717:   codebase: reference to hash used for codebases of java objects found by parser
                   16718:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16719:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16720:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16721:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16722:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16723:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16724:   mimetype: reference to scalar to accommodate mime type determined
                   16725:             from File::MMagic if $parser = parse.
1.608     albertel 16726: 
                   16727:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16728:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16729:  was 'overwrite').
                   16730:  
1.608     albertel 16731: 
                   16732: =item *
                   16733: 
                   16734: renameuserfile(): renames an existing userfile to a new name
                   16735: 
                   16736:   Args:
                   16737:    docuname: username or courseid of destination for the file
                   16738:    docudom: domain of user/course of destination for the file
                   16739:    old: current file name (including any subdirs under userfiles)
                   16740:    new: desired file name (including any subdirs under userfiles)
                   16741: 
                   16742: =item *
                   16743: 
                   16744: mkdiruserfile(): creates a directory is a userfiles dir
                   16745: 
                   16746:   Args:
                   16747:    docuname: username or courseid of destination for the file
                   16748:    docudom: domain of user/course of destination for the file
                   16749:    dir: dir to create (including any subdirs under userfiles)
                   16750: 
                   16751: =item *
                   16752: 
                   16753: removeuserfile(): removes a file that exists in userfiles
                   16754: 
                   16755:   Args:
                   16756:    docuname: username or courseid of destination for the file
                   16757:    docudom: domain of user/course of destination for the file
                   16758:    fname: filname to delete (including any subdirs under userfiles)
                   16759: 
                   16760: =item *
                   16761: 
                   16762: removeuploadedurl(): convience function for removeuserfile()
                   16763: 
                   16764:   Args:
                   16765:    url:  a full /uploaded/... url to delete
                   16766: 
1.747     albertel 16767: =item * 
                   16768: 
                   16769: get_portfile_permissions():
                   16770:   Args:
                   16771:     domain: domain of user or course contain the portfolio files
                   16772:     user: name of user or num of course contain the portfolio files
                   16773:   Returns:
                   16774:     hashref of a dump of the proper file_permissions.db
                   16775:    
                   16776: 
                   16777: =item * 
                   16778: 
                   16779: get_access_controls():
                   16780: 
                   16781: Args:
                   16782:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16783:   group: (optional) the group you want the files associated with
                   16784:   file: (optional) the file you want access info on
                   16785: 
                   16786: Returns:
1.749     raeburn  16787:     a hash (keys are file names) of hashes containing
                   16788:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16789:         values are XML containing access control settings (see below) 
1.747     albertel 16790: 
                   16791: Internal notes:
                   16792: 
1.749     raeburn  16793:  access controls are stored in file_permissions.db as key=value pairs.
                   16794:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16795:         where scope -> public,guest,course,group,domains or users.
                   16796:               end -> UNIX time for end of access (0 -> no end date)
                   16797:               start -> UNIX time for start of access
                   16798: 
                   16799:     value -> XML description of access control
                   16800:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16801:             <start></start>
                   16802:             <end></end>
                   16803: 
                   16804:             <password></password>  for scope type = guest
                   16805: 
                   16806:             <domain></domain>     for scope type = course or group
                   16807:             <number></number>
                   16808:             <roles id="">
                   16809:              <role></role>
                   16810:              <access></access>
                   16811:              <section></section>
                   16812:              <group></group>
                   16813:             </roles>
                   16814: 
                   16815:             <dom></dom>         for scope type = domains
                   16816: 
                   16817:             <users>             for scope type = users
                   16818:              <user>
                   16819:               <uname></uname>
                   16820:               <udom></udom>
                   16821:              </user>
                   16822:             </users>
                   16823:            </scope> 
                   16824:               
                   16825:  Access data is also aggregated for each file in an additional key=value pair:
                   16826:  key -> path to file/file_name\0accesscontrol 
                   16827:  value -> reference to hash
                   16828:           hash contains key = value pairs
                   16829:           where key = uniqueID:scope_end_start
                   16830:                 value = UNIX time record was last updated
                   16831: 
                   16832:           Used to improve speed of look-ups of access controls for each file.  
                   16833:  
                   16834:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16835: 
1.1198    raeburn  16836: =item *
                   16837: 
1.749     raeburn  16838: modify_access_controls():
                   16839: 
                   16840: Modifies access controls for a portfolio file
                   16841: Args
                   16842: 1. file name
                   16843: 2. reference to hash of required changes,
                   16844: 3. domain
                   16845: 4. username
                   16846:   where domain,username are the domain of the portfolio owner 
                   16847:   (either a user or a course) 
                   16848: 
                   16849: Returns:
                   16850: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16851: 2. result of deletions ('ok' or 'error', with error message).
                   16852: 3. reference to hash of any new or updated access controls.
                   16853: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16854:    key = integer (inbound ID)
1.1198    raeburn  16855:    value = uniqueID
                   16856: 
                   16857: =item *
                   16858: 
                   16859: get_timebased_id():
                   16860: 
                   16861: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   16862: course via the Course Editor (e.g., folders, composite pages, 
                   16863: group bulletin boards).
                   16864: 
                   16865: Args: (first three required; six others optional)
                   16866: 
                   16867: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16868:    docssequence, or name of group
                   16869: 
                   16870: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16871:    e.g., num, boardids
                   16872: 
                   16873: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   16874:    file will be named nohist_namespace.db
                   16875: 
                   16876: 4. cdom: domain of course; default is current course domain from %env
                   16877: 
                   16878: 5. cnum: course number; default is current course number from %env
                   16879: 
                   16880: 6. idtype: set to concat if an additional digit is to be appended to the 
                   16881:    unix timestamp to form the suffix, if the plain timestamp is already
                   16882:    in use.  Default is to not do this, but simply increment the unix 
                   16883:    timestamp by 1 until a unique key is obtained.
                   16884: 
                   16885: 7. who: holder of locking key; defaults to user:domain for user.
                   16886: 
                   16887: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   16888:    retrying); default is 3.
                   16889: 
                   16890: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   16891: 
                   16892: Returns:
                   16893: 
                   16894: 1. suffix obtained (numeric)
                   16895: 
                   16896: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16897: 
                   16898: 3. error: contains (localized) error message if an error occurred.
                   16899: 
1.747     albertel 16900: 
1.608     albertel 16901: =back
                   16902: 
1.243     albertel 16903: =head2 HTTP Helper Routines
                   16904: 
                   16905: =over 4
                   16906: 
1.191     harris41 16907: =item *
                   16908: 
                   16909: escape() : unpack non-word characters into CGI-compatible hex codes
                   16910: 
                   16911: =item *
                   16912: 
                   16913: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16914: 
1.243     albertel 16915: =back
                   16916: 
                   16917: =head1 PRIVATE SUBROUTINES
                   16918: 
                   16919: =head2 Underlying communication routines (Shouldn't call)
                   16920: 
                   16921: =over 4
                   16922: 
                   16923: =item *
                   16924: 
                   16925: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16926: 
                   16927: =item *
                   16928: 
                   16929: reply() : uses subreply to send a message to remote machine, logs all failures
                   16930: 
                   16931: =item *
                   16932: 
                   16933: critical() : passes a critical message to another server; if cannot
                   16934: get through then place message in connection buffer directory and
                   16935: returns con_delayed, if incapable of saving message, returns
                   16936: con_failed
                   16937: 
                   16938: =item *
                   16939: 
                   16940: reconlonc() : tries to reconnect lonc client processes.
                   16941: 
                   16942: =back
                   16943: 
                   16944: =head2 Resource Access Logging
                   16945: 
                   16946: =over 4
                   16947: 
                   16948: =item *
                   16949: 
                   16950: flushcourselogs() : flush (save) buffer logs and access logs
                   16951: 
                   16952: =item *
                   16953: 
                   16954: courselog($what) : save message for course in hash
                   16955: 
                   16956: =item *
                   16957: 
                   16958: courseacclog($what) : save message for course using &courselog().  Perform
                   16959: special processing for specific resource types (problems, exams, quizzes, etc).
                   16960: 
1.191     harris41 16961: =item *
                   16962: 
                   16963: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16964: as a PerlChildExitHandler
1.243     albertel 16965: 
                   16966: =back
                   16967: 
                   16968: =head2 Other
                   16969: 
                   16970: =over 4
                   16971: 
                   16972: =item *
                   16973: 
                   16974: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16975: 
                   16976: =back
                   16977: 
                   16978: =cut
1.877     foxr     16979: 

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