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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1421  ! raeburn     4: # $Id: lonnet.pm,v 1.1420 2020/03/30 11:04:08 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.807     albertel   99: use LONCAPA qw(:DEFAULT :match);
1.740     www       100: use LONCAPA::Configuration;
1.1160    www       101: use LONCAPA::lonmetadata;
1.1167    droeschl  102: use LONCAPA::Lond;
1.1345    raeburn   103: use LONCAPA::LWPReq;
1.1406    raeburn   104: use LONCAPA::transliterate;
1.1117    foxr      105: 
1.1090    raeburn   106: use File::Copy;
1.676     albertel  107: 
1.195     www       108: my $readit;
1.1288    damieng   109: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  110: 
1.619     albertel  111: require Exporter;
                    112: 
                    113: our @ISA = qw (Exporter);
                    114: our @EXPORT = qw(%env);
                    115: 
1.449     matthew   116: 
1.1187    raeburn   117: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       118: {
                    119:     my $logid;
1.1187    raeburn   120:     sub write_log {
1.1188    raeburn   121: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   122:         if ($context eq 'course') {
                    123:             if (($cnum eq '') || ($cdom eq '')) {
                    124:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    125:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    126:             }
1.957     raeburn   127:         }
1.1184    raeburn   128: 	$logid ++;
1.957     raeburn   129:         my $now = time();
                    130: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   131:         my $logentry = { 
                    132:                           $id => {
                    133:                                    'exe_uname' => $env{'user.name'},
                    134:                                    'exe_udom'  => $env{'user.domain'},
                    135:                                    'exe_time'  => $now,
                    136:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    137:                                    'delflag'   => $delflag,
                    138:                                    'logentry'  => $storehash,
                    139:                                    'uname'     => $uname,
                    140:                                    'udom'      => $udom,
                    141:                                   }
                    142:                        };
                    143: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       144:     }
                    145: }
1.1       albertel  146: 
1.163     harris41  147: sub logtouch {
                    148:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  149:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  151: 	close $fh;
                    152:     }
                    153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    155: }
                    156: 
1.1       albertel  157: sub logthis {
                    158:     my $message=shift;
                    159:     my $execdir=$perlvar{'lonDaemons'};
                    160:     my $now=time;
                    161:     my $local=localtime($now);
1.1359    raeburn   162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    164: 	print $fh $logstring;
1.448     albertel  165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
                    170: sub logperm {
                    171:     my $message=shift;
                    172:     my $execdir=$perlvar{'lonDaemons'};
                    173:     my $now=time;
                    174:     my $local=localtime($now);
1.1359    raeburn   175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  176: 	print $fh "$now:$message:$local\n";
                    177: 	close($fh);
                    178:     }
1.1       albertel  179:     return 1;
                    180: }
                    181: 
1.850     albertel  182: sub create_connection {
1.853     albertel  183:     my ($hostname,$lonid) = @_;
1.851     albertel  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  185: 				     Type    => SOCK_STREAM,
                    186: 				     Timeout => 10);
                    187:     return 0 if (!$client);
1.1399    raeburn   188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850     albertel  189:     my $result = <$client>;
                    190:     chomp($result);
                    191:     return 1 if ($result eq 'done');
                    192:     return 0;
                    193: }
                    194: 
1.983     raeburn   195: sub get_server_timezone {
                    196:     my ($cnum,$cdom) = @_;
                    197:     my $home=&homeserver($cnum,$cdom);
                    198:     if ($home ne 'no_host') {
                    199:         my $cachetime = 24*3600;
                    200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    201:         if (defined($cached)) {
                    202:             return $timezone;
                    203:         } else {
                    204:             my $timezone = &reply('servertimezone',$home);
                    205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    206:         }
                    207:     }
                    208: }
1.850     albertel  209: 
1.1106    raeburn   210: sub get_server_distarch {
                    211:     my ($lonhost,$ignore_cache) = @_;
                    212:     if (defined($lonhost)) {
                    213:         if (!defined(&hostname($lonhost))) {
                    214:             return;
                    215:         }
                    216:         my $cachetime = 12*3600;
                    217:         if (!$ignore_cache) {
                    218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    219:             if (defined($cached)) {
                    220:                 return $distarch;
                    221:             }
                    222:         }
                    223:         my $rep = &reply('serverdistarch',$lonhost);
                    224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    226:                 $rep eq '') {
                    227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    228:         }
                    229:     }
                    230:     return;
                    231: }
                    232: 
1.1315    raeburn   233: sub get_servercerts_info {
1.1383    raeburn   234:     my ($lonhost,$hostname,$context) = @_;
                    235:     return if ($lonhost eq '');
                    236:     if ($hostname eq '') {
                    237:         $hostname = &hostname($lonhost);
                    238:     }
                    239:     return if ($hostname eq '');
1.1315    raeburn   240:     my ($rep,$uselocal);
1.1388    raeburn   241:     if ($context eq 'install') {
1.1387    raeburn   242:         $uselocal = 1;
                    243:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   244:         $uselocal = 1;
                    245:     }
1.1387    raeburn   246:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   247:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   248:         if ($distro eq '') {
                    249:             $uselocal = 0;
                    250:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   251:             if ($1 < 6) {
                    252:                 $uselocal = 0;
                    253:             }
1.1346    raeburn   254:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    255:             if ($1 < 12) {
                    256:                 $uselocal = 0;
                    257:             }
1.1315    raeburn   258:         }
                    259:     }
                    260:     if ($uselocal) {
1.1383    raeburn   261:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   262:     } else {
                    263:         $rep=&reply('servercerts',$lonhost);
                    264:     }
                    265:     my ($result,%returnhash);
                    266:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    267:         ($rep eq 'unknown_cmd')) {
                    268:         $result = $rep;
                    269:     } else {
                    270:         $result = 'ok';
                    271:         my @pairs=split(/\&/,$rep);
                    272:         foreach my $item (@pairs) {
                    273:             my ($key,$value)=split(/=/,$item,2);
                    274:             my $what = &unescape($key);
                    275:             $returnhash{$what}=&thaw_unescape($value);
                    276:         }
                    277:     }
                    278:     return ($result,\%returnhash);
                    279: }
                    280: 
1.993     raeburn   281: sub get_server_loncaparev {
1.1073    raeburn   282:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   283:     if (defined($lonhost)) {
                    284:         if (!defined(&hostname($lonhost))) {
                    285:             undef($lonhost);
                    286:         }
                    287:     }
                    288:     if (!defined($lonhost)) {
                    289:         if (defined(&domain($dom,'primary'))) {
                    290:             $lonhost=&domain($dom,'primary');
                    291:             if ($lonhost eq 'no_host') {
                    292:                 undef($lonhost);
                    293:             }
                    294:         }
                    295:     }
                    296:     if (defined($lonhost)) {
1.1073    raeburn   297:         my $cachetime = 12*3600;
                    298:         if (!$ignore_cache) {
                    299:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    300:             if (defined($cached)) {
                    301:                 return $loncaparev;
                    302:             }
                    303:         }
                    304:         my ($answer,$loncaparev);
                    305:         my @ids=&current_machine_ids();
                    306:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    307:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   308:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   309:                 $loncaparev = $1;
                    310:             }
                    311:         } else {
                    312:             $answer = &reply('serverloncaparev',$lonhost);
                    313:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    314:                 if ($caller eq 'loncron') {
1.1397    raeburn   315:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   316:                     my $protocol = $protocol{$lonhost};
                    317:                     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn   318:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   319:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   320:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   321:                     unless ($response->is_error()) {
                    322:                         my $content = $response->content;
1.1081    raeburn   323:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   324:                             $loncaparev = $1;
                    325:                         }
                    326:                     }
                    327:                 } else {
                    328:                     $loncaparev = $loncaparevs{$lonhost};
                    329:                 }
1.1081    raeburn   330:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   331:                 $loncaparev = $1;
                    332:             }
1.993     raeburn   333:         }
1.1073    raeburn   334:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   335:     }
                    336: }
                    337: 
1.1074    raeburn   338: sub get_server_homeID {
                    339:     my ($hostname,$ignore_cache,$caller) = @_;
                    340:     unless ($ignore_cache) {
                    341:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    342:         if (defined($cached)) {
                    343:             return $serverhomeID;
                    344:         }
                    345:     }
                    346:     my $cachetime = 12*3600;
                    347:     my $serverhomeID;
                    348:     if ($caller eq 'loncron') { 
                    349:         my @machine_ids = &machine_ids($hostname);
                    350:         foreach my $id (@machine_ids) {
                    351:             my $response = &reply('serverhomeID',$id);
                    352:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    353:                 $serverhomeID = $response;
                    354:                 last;
                    355:             }
                    356:         }
                    357:         if ($serverhomeID eq '') {
                    358:             $serverhomeID = $machine_ids[-1];
                    359:         }
                    360:     } else {
                    361:         $serverhomeID = $serverhomeIDs{$hostname};
                    362:     }
                    363:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    364: }
                    365: 
1.1121    raeburn   366: sub get_remote_globals {
                    367:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   368:     my ($result,%returnhash,%whatneeded);
                    369:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   370:         foreach my $what (sort(keys(%{$whathash}))) {
                    371:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   372:             my ($response,$cached);
1.1121    raeburn   373:             unless ($ignore_cache) {
1.1125    raeburn   374:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   375:             }
                    376:             if (defined($cached)) {
1.1125    raeburn   377:                 $returnhash{$what} = $response;
1.1121    raeburn   378:             } else {
1.1125    raeburn   379:                 $whatneeded{$what} = 1;
1.1121    raeburn   380:             }
                    381:         }
1.1125    raeburn   382:         if (keys(%whatneeded) == 0) {
                    383:             $result = 'ok';
                    384:         } else {
1.1121    raeburn   385:             my $requested = &freeze_escape(\%whatneeded);
                    386:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   387:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    388:                 ($rep eq 'unknown_cmd')) {
                    389:                 $result = $rep;
                    390:             } else {
                    391:                 $result = 'ok';
1.1121    raeburn   392:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   393:                 foreach my $item (@pairs) {
                    394:                     my ($key,$value)=split(/=/,$item,2);
                    395:                     my $what = &unescape($key);
                    396:                     my $hashid = $lonhost.'-'.$what;
                    397:                     $returnhash{$what}=&thaw_unescape($value);
                    398:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   399:                 }
                    400:             }
                    401:         }
                    402:     }
1.1125    raeburn   403:     return ($result,\%returnhash);
1.1121    raeburn   404: }
                    405: 
1.1124    raeburn   406: sub remote_devalidate_cache {
1.1241    raeburn   407:     my ($lonhost,$cachekeys) = @_;
                    408:     my $items;
                    409:     return unless (ref($cachekeys) eq 'ARRAY');
                    410:     my $cachestr = join('&',@{$cachekeys});
                    411:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   412:     return $response;
                    413: }
                    414: 
1.1       albertel  415: # -------------------------------------------------- Non-critical communication
                    416: sub subreply {
                    417:     my ($cmd,$server)=@_;
1.838     albertel  418:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      419:     #
                    420:     #  With loncnew process trimming, there's a timing hole between lonc server
                    421:     #  process exit and the master server picking up the listen on the AF_UNIX
                    422:     #  socket.  In that time interval, a lock file will exist:
                    423: 
                    424:     my $lockfile=$peerfile.".lock";
                    425:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   426: 	sleep(0.1);
1.549     foxr      427:     }
                    428:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      429:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      430:     #
1.550     foxr      431:     #   We'll give the connection a few tries before abandoning it.  If
                    432:     #   connection is not possible, we'll con_lost back to the client.
                    433:     #   
                    434:     my $client;
                    435:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    436: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    437: 				      Type    => SOCK_STREAM,
                    438: 				      Timeout => 10);
1.869     albertel  439: 	if ($client) {
1.550     foxr      440: 	    last;		# Connected!
1.850     albertel  441: 	} else {
1.853     albertel  442: 	    &create_connection(&hostname($server),$server);
1.550     foxr      443: 	}
1.1289    damieng   444:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      445:     }
                    446:     my $answer;
                    447:     if ($client) {
1.704     albertel  448: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      449: 	$answer=<$client>;
                    450: 	if (!$answer) { $answer="con_lost"; }
                    451: 	chomp($answer);
                    452:     } else {
                    453: 	$answer = 'con_lost';	# Failed connection.
                    454:     }
1.1       albertel  455:     return $answer;
                    456: }
                    457: 
                    458: sub reply {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  461:     my $answer=subreply($cmd,$server);
1.65      www       462:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   463:         my $logged = $cmd;
                    464:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    465:             my $subcmd = $1;
                    466:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    467:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    468:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    469:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    470:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    471:                     splice(@rest,2,1,'Hidden');
                    472:                 } elsif ($subcmd eq 'passwd') {
                    473:                     splice(@rest,2,2,('Hidden','Hidden'));
                    474:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    475:                          ($subcmd eq 'autoexportgrades')) {
                    476:                     splice(@rest,3,1,'Hidden');
                    477:                 }
                    478:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    479:             }
                    480:         }
                    481:         &logthis("<font color=\"blue\">WARNING:".
                    482:                  " $logged to $server returned $answer</font>");
1.12      www       483:     }
1.1       albertel  484:     return $answer;
                    485: }
                    486: 
                    487: # ----------------------------------------------------------- Send USR1 to lonc
                    488: 
                    489: sub reconlonc {
1.891     albertel  490:     my ($lonid) = @_;
                    491:     if ($lonid) {
1.1295    raeburn   492:         my $hostname = &hostname($lonid);
1.891     albertel  493: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    494: 	if ($hostname && -e $peerfile) {
                    495: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    496: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    497: 					     Type    => SOCK_STREAM,
                    498: 					     Timeout => 10);
                    499: 	    if ($client) {
                    500: 		print $client ("reset_retries\n");
                    501: 		my $answer=<$client>;
                    502: 		#reset just this one.
                    503: 	    }
                    504: 	}
                    505: 	return;
                    506:     }
                    507: 
1.836     www       508:     &logthis("Trying to reconnect lonc");
1.1       albertel  509:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   510:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  511: 	my $loncpid=<$fh>;
                    512:         chomp($loncpid);
                    513:         if (kill 0 => $loncpid) {
                    514: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    515:             kill USR1 => $loncpid;
                    516:             sleep 1;
1.1295    raeburn   517:         } else {
1.12      www       518: 	    &logthis(
1.672     albertel  519:                "<font color=\"blue\">WARNING:".
1.12      www       520:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  521:         }
                    522:     } else {
1.836     www       523: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  524:     }
                    525: }
                    526: 
                    527: # ------------------------------------------------------ Critical communication
1.12      www       528: 
1.1       albertel  529: sub critical {
                    530:     my ($cmd,$server)=@_;
1.838     albertel  531:     unless (&hostname($server)) {
1.672     albertel  532:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       533:                " Critical message to unknown server ($server)</font>");
                    534:         return 'no_such_host';
                    535:     }
1.1       albertel  536:     my $answer=reply($cmd,$server);
                    537:     if ($answer eq 'con_lost') {
1.1295    raeburn   538: 	&reconlonc($server);
1.589     albertel  539: 	my $answer=reply($cmd,$server);
1.1       albertel  540:         if ($answer eq 'con_lost') {
                    541:             my $now=time;
                    542:             my $middlename=$cmd;
1.5       www       543:             $middlename=substr($middlename,0,16);
1.1       albertel  544:             $middlename=~s/\W//g;
                    545:             my $dfilename=
1.305     www       546:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    547:             $dumpcount++;
1.1       albertel  548:             {
1.448     albertel  549: 		my $dfh;
1.1359    raeburn   550: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  551: 		    print $dfh "$cmd\n"; 
                    552: 		    close($dfh);
                    553: 		}
1.1       albertel  554:             }
1.1288    damieng   555:             sleep 1;
1.1       albertel  556:             my $wcmd='';
                    557:             {
1.448     albertel  558: 		my $dfh;
1.1359    raeburn   559: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  560: 		    $wcmd=<$dfh>; 
                    561: 		    close($dfh);
                    562: 		}
1.1       albertel  563:             }
                    564:             chomp($wcmd);
1.7       www       565:             if ($wcmd eq $cmd) {
1.672     albertel  566: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       567:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  568:                 &logperm("D:$server:$cmd");
                    569: 	        return 'con_delayed';
                    570:             } else {
1.672     albertel  571:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       572:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  573:                 &logperm("F:$server:$cmd");
                    574:                 return 'con_failed';
                    575:             }
                    576:         }
                    577:     }
                    578:     return $answer;
1.405     albertel  579: }
                    580: 
1.755     albertel  581: # ------------------------------------------- check if return value is an error
                    582: 
                    583: sub error {
                    584:     my ($result) = @_;
1.756     albertel  585:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  586: 	if ($2 == 2) { return undef; }
                    587: 	return $1;
                    588:     }
                    589:     return undef;
                    590: }
                    591: 
1.783     albertel  592: sub convert_and_load_session_env {
                    593:     my ($lonidsdir,$handle)=@_;
                    594:     my @profile;
                    595:     {
1.917     albertel  596: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    597: 	if (!$opened) {
1.915     albertel  598: 	    return 0;
                    599: 	}
1.783     albertel  600: 	flock($idf,LOCK_SH);
                    601: 	@profile=<$idf>;
                    602: 	close($idf);
                    603:     }
                    604:     my %temp_env;
                    605:     foreach my $line (@profile) {
1.786     albertel  606: 	if ($line !~ m/=/) {
                    607: 	    return 0;
                    608: 	}
1.783     albertel  609: 	chomp($line);
                    610: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    611: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    612:     }
                    613:     unlink("$lonidsdir/$handle.id");
                    614:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    615: 	    0640)) {
                    616: 	%disk_env = %temp_env;
                    617: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    618: 	untie(%disk_env);
                    619:     }
1.786     albertel  620:     return 1;
1.783     albertel  621: }
                    622: 
1.374     www       623: # ------------------------------------------- Transfer profile into environment
1.780     albertel  624: my $env_loaded;
                    625: sub transfer_profile_to_env {
1.788     albertel  626:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    627:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       628: 
1.720     albertel  629:     if (!defined($lonidsdir)) {
                    630: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    631:     }
                    632:     if (!defined($handle)) {
                    633:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    634:     }
                    635: 
1.786     albertel  636:     my $convert;
                    637:     {
1.917     albertel  638:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    639: 	if (!$opened) {
1.915     albertel  640: 	    return;
                    641: 	}
1.786     albertel  642: 	flock($idf,LOCK_SH);
                    643: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    644: 		&GDBM_READER(),0640)) {
                    645: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    646: 	    untie(%disk_env);
                    647: 	} else {
                    648: 	    $convert = 1;
                    649: 	}
                    650:     }
                    651:     if ($convert) {
                    652: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    653: 	    &logthis("Failed to load session, or convert session.");
                    654: 	}
1.374     www       655:     }
1.783     albertel  656: 
1.786     albertel  657:     my %remove;
1.783     albertel  658:     while ( my $envname = each(%env) ) {
1.433     matthew   659:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    660:             if ($time < time-300) {
1.783     albertel  661:                 $remove{$key}++;
1.433     matthew   662:             }
                    663:         }
                    664:     }
1.783     albertel  665: 
1.619     albertel  666:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  667:     $env_loaded=1;
1.783     albertel  668:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   669:         &delenv($expired_key);
1.374     www       670:     }
1.1       albertel  671: }
                    672: 
1.916     albertel  673: # ---------------------------------------------------- Check for valid session 
                    674: sub check_for_valid_session {
1.1355    raeburn   675:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  676:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   677:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    678:     if ($name eq 'lonDAV') {
                    679:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    680:     } else {
                    681:         $lonidsdir=$r->dir_config('lonIDsDir');
                    682:         if ($name eq '') {
                    683:             $name = 'lonID';
                    684:         }
                    685:     }
                    686:     if ($name eq 'lonID') {
                    687:         $secure = 'lonSID';
1.1337    raeburn   688:         $linkname = 'lonLinkID';
                    689:         $pubname = 'lonPubID';
1.1378    raeburn   690:         if (exists($cookies{$secure})) {
                    691:             $lonid=$cookies{$secure};
                    692:         } elsif (exists($cookies{$name})) {
                    693:             $lonid=$cookies{$name};
1.1400    raeburn   694:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337    raeburn   695:             $lonid=$cookies{$linkname};
1.1378    raeburn   696:         } elsif (exists($cookies{$pubname})) {
                    697:             $lonid=$cookies{$pubname};
1.1337    raeburn   698:         }
1.1378    raeburn   699:     } else {
                    700:         $lonid=$cookies{$name};
1.1337    raeburn   701:     }
1.916     albertel  702:     return undef if (!$lonid);
                    703: 
                    704:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   705:     if (-l "$lonidsdir/$handle.id") {
                    706:         my $link = readlink("$lonidsdir/$handle.id");
                    707:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    708:             $handle = $1;
                    709:         }
1.1155    raeburn   710:     }
1.1355    raeburn   711:     if (!-e "$lonidsdir/$handle.id") {
                    712:         if ((ref($domref)) && ($name eq 'lonID') && 
                    713:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    714:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    715:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    716:                 $$domref = $possudom;
                    717:             }
                    718:         }
                    719:         return undef;
                    720:     }
1.916     albertel  721: 
1.917     albertel  722:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    723:     return undef if (!$opened);
1.916     albertel  724: 
                    725:     flock($idf,LOCK_SH);
                    726:     my %disk_env;
                    727:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    728: 	    &GDBM_READER(),0640)) {
                    729: 	return undef;	
                    730:     }
                    731: 
                    732:     if (!defined($disk_env{'user.name'})
                    733: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   734:         untie(%disk_env);
1.916     albertel  735: 	return undef;
                    736:     }
1.1245    raeburn   737: 
                    738:     if (ref($userhashref) eq 'HASH') {
                    739:         $userhashref->{'name'} = $disk_env{'user.name'};
                    740:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   741:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   742:         if ($userhashref->{'lti'}) {
                    743:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    744:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    745:         }
1.1212    raeburn   746:     }
1.1394    raeburn   747:     untie(%disk_env);
1.1245    raeburn   748: 
1.916     albertel  749:     return $handle;
                    750: }
                    751: 
1.830     albertel  752: sub timed_flock {
                    753:     my ($file,$lock_type) = @_;
                    754:     my $failed=0;
                    755:     eval {
                    756: 	local $SIG{__DIE__}='DEFAULT';
                    757: 	local $SIG{ALRM}=sub {
                    758: 	    $failed=1;
                    759: 	    die("failed lock");
                    760: 	};
                    761: 	alarm(13);
                    762: 	flock($file,$lock_type);
                    763: 	alarm(0);
                    764:     };
                    765:     if ($failed) {
                    766: 	return undef;
                    767:     } else {
                    768: 	return 1;
                    769:     }
                    770: }
                    771: 
1.1392    raeburn   772: sub get_sessionfile_vars {
                    773:     my ($handle,$lonidsdir,$storearr) = @_;
                    774:     my %returnhash;
                    775:     unless (ref($storearr) eq 'ARRAY') {
                    776:         return %returnhash;
                    777:     }
                    778:     if (-l "$lonidsdir/$handle.id") {
                    779:         my $link = readlink("$lonidsdir/$handle.id");
                    780:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    781:             $handle = $1;
                    782:         }
                    783:     }
                    784:     if ((-e "$lonidsdir/$handle.id") &&
                    785:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    786:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    787:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    788:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    789:                 flock($idf,LOCK_SH);
                    790:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    791:                         &GDBM_READER(),0640)) {
                    792:                     foreach my $item (@{$storearr}) {
                    793:                         $returnhash{$item} = $disk_env{$item};
                    794:                     }
                    795:                     untie(%disk_env);
                    796:                 }
                    797:             }
                    798:         }
                    799:     }
                    800:     return %returnhash;
                    801: }
                    802: 
1.5       www       803: # ---------------------------------------------------------- Append Environment
                    804: 
                    805: sub appenv {
1.949     raeburn   806:     my ($newenv,$roles) = @_;
                    807:     if (ref($newenv) eq 'HASH') {
                    808:         foreach my $key (keys(%{$newenv})) {
                    809:             my $refused = 0;
                    810: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    811:                 $refused = 1;
                    812:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   813:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   814:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    815:                         $refused = 0;
                    816:                     }
                    817:                 }
                    818:             }
                    819:             if ($refused) {
                    820:                 &logthis("<font color=\"blue\">WARNING: ".
                    821:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    822:                          .'</font>');
                    823: 	        delete($newenv->{$key});
                    824:             } else {
                    825:                 $env{$key}=$newenv->{$key};
                    826:             }
                    827:         }
1.1376    raeburn   828:         my $lonids = $perlvar{'lonIDsDir'};
                    829:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    830:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    831:             if ($opened
                    832: 	        && &timed_flock($env_file,LOCK_EX)
                    833: 	        &&
                    834: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    835: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    836: 	        while (my ($key,$value) = each(%{$newenv})) {
                    837: 	            $disk_env{$key} = $value;
                    838: 	        }
                    839: 	        untie(%disk_env);
                    840:             }
1.35      www       841:         }
1.191     harris41  842:     }
1.56      www       843:     return 'ok';
                    844: }
                    845: # ----------------------------------------------------- Delete from Environment
                    846: 
                    847: sub delenv {
1.1104    raeburn   848:     my ($delthis,$regexp,$roles) = @_;
                    849:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    850:         my $refused = 1;
                    851:         if (ref($roles) eq 'ARRAY') {
                    852:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    853:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    854:                 $refused = 0;
                    855:             }
                    856:         }
                    857:         if ($refused) {
                    858:             &logthis("<font color=\"blue\">WARNING: ".
                    859:                      "Attempt to delete from environment ".$delthis);
                    860:             return 'error';
                    861:         }
1.56      www       862:     }
1.917     albertel  863:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    864:     if ($opened
1.915     albertel  865: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  866: 	&&
                    867: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    868: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  869: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   870: 	    if ($regexp) {
                    871:                 if ($key=~/^$delthis/) {
                    872:                     delete($env{$key});
                    873:                     delete($disk_env{$key});
                    874:                 } 
                    875:             } else {
                    876:                 if ($key=~/^\Q$delthis\E/) {
                    877: 		    delete($env{$key});
                    878: 		    delete($disk_env{$key});
                    879: 	        }
                    880:             }
1.448     albertel  881: 	}
1.783     albertel  882: 	untie(%disk_env);
1.5       www       883:     }
                    884:     return 'ok';
1.369     albertel  885: }
                    886: 
1.790     albertel  887: sub get_env_multiple {
                    888:     my ($name) = @_;
                    889:     my @values;
                    890:     if (defined($env{$name})) {
                    891:         # exists is it an array
                    892:         if (ref($env{$name})) {
                    893:             @values=@{ $env{$name} };
                    894:         } else {
                    895:             $values[0]=$env{$name};
                    896:         }
                    897:     }
                    898:     return(@values);
                    899: }
                    900: 
1.958     www       901: # ------------------------------------------------------------------- Locking
                    902: 
                    903: sub set_lock {
                    904:     my ($text)=@_;
                    905:     $locknum++;
                    906:     my $id=$$.'-'.$locknum;
                    907:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    908:              'session.lock.'.$id => $text});
                    909:     return $id;
                    910: }
                    911: 
                    912: sub get_locks {
                    913:     my $num=0;
                    914:     my %texts=();
                    915:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    916:        if ($lock=~/\w/) {
                    917:           $num++;
                    918:           $texts{$lock}=$env{'session.lock.'.$lock};
                    919:        }
                    920:    }
                    921:    return ($num,%texts);
                    922: }
                    923: 
                    924: sub remove_lock {
                    925:     my ($id)=@_;
                    926:     my $newlocks='';
                    927:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    928:        if (($lock=~/\w/) && ($lock ne $id)) {
                    929:           $newlocks.=','.$lock;
                    930:        }
                    931:     }
                    932:     &appenv({'session.locks' => $newlocks});
                    933:     &delenv('session.lock.'.$id);
                    934: }
                    935: 
                    936: sub remove_all_locks {
                    937:     my $activelocks=$env{'session.locks'};
                    938:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    939:        if ($lock=~/\w/) {
                    940:           &remove_lock($lock);
                    941:        }
                    942:     }
                    943: }
                    944: 
                    945: 
1.369     albertel  946: # ------------------------------------------ Find out current server userload
                    947: sub userload {
                    948:     my $numusers=0;
                    949:     {
                    950: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    951: 	my $filename;
                    952: 	my $curtime=time;
                    953: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  954: 	    next if ($filename eq '.' || $filename eq '..');
                    955: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   956:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  957: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  958: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  959: 	}
                    960: 	closedir(LONIDS);
                    961:     }
                    962:     my $userloadpercent=0;
                    963:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    964:     if ($maxuserload) {
1.371     albertel  965: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  966:     }
1.372     albertel  967:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  968:     return $userloadpercent;
1.283     www       969: }
                    970: 
1.1       albertel  971: # ------------------------------ Find server with least workload from spare.tab
1.11      www       972: 
1.1       albertel  973: sub spareserver {
1.1083    raeburn   974:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  975:     my $spare_server;
1.370     albertel  976:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  977:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    978:                                                      :  $userloadpercent;
1.1083    raeburn   979:     my ($uint_dom,$remotesessions);
                    980:     if (($udom ne '') && (&domain($udom) ne '')) {
                    981:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    982:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    983:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    984:         $remotesessions = $udomdefaults{'remotesessions'};
                    985:     }
1.1123    raeburn   986:     my $spareshash = &this_host_spares($udom);
                    987:     if (ref($spareshash) eq 'HASH') {
                    988:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    989:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   990:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    991:                                              $try_server));
1.1123    raeburn   992: 	        ($spare_server, $lowest_load) =
                    993: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    994:             }
1.1083    raeburn   995:         }
1.784     albertel  996: 
1.1123    raeburn   997:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    998: 
                    999:         if (!$found_server) {
                   1000:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1001: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1002:                     next unless (&spare_can_host($udom,$uint_dom,
                   1003:                                                  $remotesessions,$try_server));
1.1123    raeburn  1004: 	            ($spare_server, $lowest_load) =
                   1005: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1006:                 }
                   1007: 	    }
                   1008:         }
1.784     albertel 1009:     }
                   1010: 
                   1011:     if (!$want_server_name) {
1.1001    raeburn  1012:         if (defined($spare_server)) {
                   1013:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1014:             if (defined($hostname)) {
1.1397    raeburn  1015:                 my $protocol = 'http';
                   1016:                 if ($protocol{$spare_server} eq 'https') {
                   1017:                     $protocol = $protocol{$spare_server};
                   1018:                 }
1.1001    raeburn  1019: 	        $spare_server = $protocol.'://'.$hostname;
                   1020:             }
                   1021:         }
1.784     albertel 1022:     }
                   1023:     return $spare_server;
                   1024: }
                   1025: 
                   1026: sub compare_server_load {
1.1253    raeburn  1027:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1028: 
                   1029:     if ($required) {
                   1030:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1031:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1032:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1033:         if (($major eq '' && $minor eq '') ||
                   1034:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1035:             return ($spare_server,$lowest_load);
                   1036:         }
                   1037:     }
1.784     albertel 1038: 
                   1039:     my $loadans     = &reply('load',    $try_server);
                   1040:     my $userloadans = &reply('userload',$try_server);
                   1041: 
                   1042:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1043: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1044:     }
                   1045: 
                   1046:     my $load;
                   1047:     if ($loadans =~ /\d/) {
                   1048: 	if ($userloadans =~ /\d/) {
                   1049: 	    #both are numbers, pick the bigger one
                   1050: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1051: 		                              : $userloadans;
1.411     albertel 1052: 	} else {
1.784     albertel 1053: 	    $load = $loadans;
1.411     albertel 1054: 	}
1.784     albertel 1055:     } else {
                   1056: 	$load = $userloadans;
                   1057:     }
                   1058: 
                   1059:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1060: 	$spare_server = $try_server;
                   1061: 	$lowest_load  = $load;
1.370     albertel 1062:     }
1.784     albertel 1063:     return ($spare_server,$lowest_load);
1.202     matthew  1064: }
1.914     albertel 1065: 
                   1066: # --------------------------- ask offload servers if user already has a session
                   1067: sub find_existing_session {
                   1068:     my ($udom,$uname) = @_;
1.1123    raeburn  1069:     my $spareshash = &this_host_spares($udom);
                   1070:     if (ref($spareshash) eq 'HASH') {
                   1071:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1072:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1073:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1074:             }
                   1075:         }
                   1076:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1077:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1078:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1079:             }
                   1080:         }
1.914     albertel 1081:     }
                   1082:     return;
                   1083: }
                   1084: 
1.1411    raeburn  1085: sub delusersession {
                   1086:     my ($lonid,$udom,$uname) = @_;
                   1087:     my $uprimary_id = &domain($udom,'primary');
                   1088:     my $uintdom = &internet_dom($uprimary_id);
                   1089:     my $intdom = &internet_dom($lonid);
                   1090:     my $serverhomedom = &host_domain($lonid);
                   1091:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1092:         return &reply(join(':','delusersession',
                   1093:                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1094:     }
                   1095:     return;
                   1096: }
                   1097: 
1.1389    raeburn  1098: # check if user's browser sent load balancer cookie and server still has session
                   1099: # and is not overloaded.
                   1100: sub check_for_balancer_cookie {
                   1101:     my ($r,$update_mtime) = @_;
                   1102:     my ($otherserver,$cookie);
                   1103:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1104:     if (exists($cookies{'balanceID'})) {
                   1105:         my $balid = $cookies{'balanceID'};
                   1106:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1107:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1108:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1109:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1110:                 my ($possudom,$possuname) = ($1,$2);
                   1111:                 my $has_session = 0;
                   1112:                 if ((&domain($possudom) ne '') &&
                   1113:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1114:                     my $try_server;
                   1115:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1116:                     if ($opened) {
                   1117:                         flock($idf,LOCK_SH);
                   1118:                         while (my $line = <$idf>) {
                   1119:                             chomp($line);
                   1120:                             if (&hostname($line) ne '') {
                   1121:                                 $try_server = $line;
                   1122:                                 last;
                   1123:                             }
                   1124:                         }
                   1125:                         close($idf);
                   1126:                         if (($try_server) &&
                   1127:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1128:                             my $lowest_load = 30000;
                   1129:                             ($otherserver,$lowest_load) =
                   1130:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1131:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1132:                                 $has_session = 1;
                   1133:                             } else {
                   1134:                                 undef($otherserver);
                   1135:                             }
                   1136:                         }
                   1137:                     }
                   1138:                 }
                   1139:                 if ($has_session) {
                   1140:                     if ($update_mtime) {
                   1141:                         my $atime = my $mtime = time;
                   1142:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1143:                     }
                   1144:                 } else {
                   1145:                     unlink("$balancedir/$cookie.id");
                   1146:                 }
                   1147:             }
                   1148:         }
                   1149:     }
                   1150:     return ($otherserver,$cookie);
                   1151: }
                   1152: 
                   1153: sub delbalcookie {
                   1154:     my ($cookie,$balancer) =@_;
                   1155:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1156:         my ($udom,$uname) = ($1,$2);
                   1157:         my $uprimary_id = &domain($udom,'primary');
                   1158:         my $uintdom = &internet_dom($uprimary_id);
                   1159:         my $intdom = &internet_dom($balancer);
                   1160:         my $serverhomedom = &host_domain($balancer);
                   1161:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1162:             return &reply("delbalcookie:$cookie",$balancer);
                   1163:         }
                   1164:     }
                   1165: }
                   1166: 
1.914     albertel 1167: # -------------------------------- ask if server already has a session for user
                   1168: sub has_user_session {
                   1169:     my ($lonid,$udom,$uname) = @_;
                   1170:     my $result = &reply(join(':','userhassession',
                   1171: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1172:     return 1 if ($result eq 'ok');
                   1173: 
                   1174:     return 0;
                   1175: }
                   1176: 
1.1076    raeburn  1177: # --------- determine least loaded server in a user's domain which allows login
                   1178: 
                   1179: sub choose_server {
1.1259    raeburn  1180:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1181:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1182:     my %servers = &get_servers($udom);
1.1076    raeburn  1183:     my $lowest_load = 30000;
1.1259    raeburn  1184:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1185:     if ($skiploadbal) {
                   1186:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1187:         unless (defined($cached)) {
                   1188:             my $cachetime = 60*60*24;
                   1189:             my %domconfig =
                   1190:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1191:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1192:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1193:                                            $cachetime);
                   1194:             }
                   1195:         }
                   1196:     }
1.1076    raeburn  1197:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1198:         if ($skiploadbal) {
                   1199:             if (ref($balancers) eq 'HASH') {
                   1200:                 next if (exists($balancers->{$lonhost}));
                   1201:             }
1.1389    raeburn  1202:         }
1.1115    raeburn  1203:         my $loginvia;
                   1204:         if ($checkloginvia) {
                   1205:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1206:             if ($loginvia) {
                   1207:                 my ($server,$path) = split(/:/,$loginvia);
                   1208:                 ($login_host, $lowest_load) =
1.1253    raeburn  1209:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1210:                 if ($login_host eq $server) {
                   1211:                     $portal_path = $path;
1.1151    raeburn  1212:                     $isredirect = 1;
1.1116    raeburn  1213:                 }
                   1214:             } else {
                   1215:                 ($login_host, $lowest_load) =
1.1253    raeburn  1216:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1217:                 if ($login_host eq $lonhost) {
                   1218:                     $portal_path = '';
1.1151    raeburn  1219:                     $isredirect = ''; 
1.1116    raeburn  1220:                 }
                   1221:             }
                   1222:         } else {
1.1076    raeburn  1223:             ($login_host, $lowest_load) =
1.1253    raeburn  1224:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1225:         }
                   1226:     }
                   1227:     if ($login_host ne '') {
1.1116    raeburn  1228:         $hostname = &hostname($login_host);
1.1076    raeburn  1229:     }
1.1331    raeburn  1230:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1231: }
                   1232: 
1.1420    raeburn  1233: sub get_course_sessions {
                   1234:     my ($cnum,$cdom,$lastactivity) = @_;
                   1235:     my %servers = &internet_dom_servers($cdom);
                   1236:     my %returnhash;
                   1237:     foreach my $server (sort(keys(%servers))) {
                   1238:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1239:         my @pairs=split(/\&/,$rep);
                   1240:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1241:             foreach my $item (@pairs) {
                   1242:                 my ($key,$value)=split(/=/,$item,2);
                   1243:                 $key = &unescape($key);
                   1244:                 next if ($key =~ /^error: 2 /);
                   1245:                 if (exists($returnhash{$key})) {
                   1246:                     next if ($value < $returnhash{$key});
                   1247:                 }
                   1248:                 $returnhash{$key}=$value;
                   1249:             }
                   1250:         }
                   1251:     }
                   1252:     return %returnhash;
                   1253: }
                   1254: 
1.202     matthew  1255: # --------------------------------------------- Try to change a user's password
                   1256: 
                   1257: sub changepass {
1.799     raeburn  1258:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1259:     $currentpass = &escape($currentpass);
                   1260:     $newpass     = &escape($newpass);
1.1030    raeburn  1261:     my $lonhost = $perlvar{'lonHostID'};
                   1262:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1263: 		       $server);
                   1264:     if (! $answer) {
                   1265: 	&logthis("No reply on password change request to $server ".
                   1266: 		 "by $uname in domain $udom.");
                   1267:     } elsif ($answer =~ "^ok") {
                   1268:         &logthis("$uname in $udom successfully changed their password ".
                   1269: 		 "on $server.");
                   1270:     } elsif ($answer =~ "^pwchange_failure") {
                   1271: 	&logthis("$uname in $udom was unable to change their password ".
                   1272: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1273: 		 "or pwchange");
                   1274:     } elsif ($answer =~ "^non_authorized") {
                   1275:         &logthis("$uname in $udom did not get their password correct when ".
                   1276: 		 "attempting to change it on $server.");
                   1277:     } elsif ($answer =~ "^auth_mode_error") {
                   1278:         &logthis("$uname in $udom attempted to change their password despite ".
                   1279: 		 "not being locally or internally authenticated on $server.");
                   1280:     } elsif ($answer =~ "^unknown_user") {
                   1281:         &logthis("$uname in $udom attempted to change their password ".
                   1282: 		 "on $server but were unable to because $server is not ".
                   1283: 		 "their home server.");
                   1284:     } elsif ($answer =~ "^refused") {
                   1285: 	&logthis("$server refused to change $uname in $udom password because ".
                   1286: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1287:     } elsif ($answer =~ "invalid_client") {
                   1288:         &logthis("$server refused to change $uname in $udom password because ".
                   1289:                  "it was a reset by e-mail originating from an invalid server.");
1.1408    raeburn  1290:     } elsif ($answer =~ "^prioruse") {
                   1291:        &logthis("$server refused to change $uname in $udom password because ".
                   1292:                 "the password had been used before");
1.202     matthew  1293:     }
                   1294:     return $answer;
1.1       albertel 1295: }
                   1296: 
1.169     harris41 1297: # ----------------------- Try to determine user's current authentication scheme
                   1298: 
                   1299: sub queryauthenticate {
                   1300:     my ($uname,$udom)=@_;
1.456     albertel 1301:     my $uhome=&homeserver($uname,$udom);
                   1302:     if (!$uhome) {
                   1303: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1304: 	return 'no_host';
                   1305:     }
                   1306:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1307:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1308: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1309:     }
1.456     albertel 1310:     return $answer;
1.169     harris41 1311: }
                   1312: 
1.1       albertel 1313: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1314: 
1.1       albertel 1315: sub authenticate {
1.1073    raeburn  1316:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1317:     $upass=&escape($upass);
                   1318:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1319:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1320:     my $newhome;
1.836     www      1321:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1322: # Maybe the machine was offline and only re-appeared again recently?
                   1323:         &reconlonc();
                   1324: # One more
1.952     raeburn  1325: 	$uhome=&homeserver($uname,$udom,1);
                   1326:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1327:             if (defined(&domain($udom,'primary'))) {
                   1328:                 $newhome=&domain($udom,'primary');
                   1329:             }
                   1330:             if ($newhome ne '') {
                   1331:                 $uhome = $newhome;
                   1332:             }
                   1333:         }
1.836     www      1334: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1335: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1336: 	    return 'no_host';
                   1337:         }
1.1       albertel 1338:     }
1.1073    raeburn  1339:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1340:     if ($answer eq 'authorized') {
1.952     raeburn  1341:         if ($newhome) {
                   1342:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1343:             return 'no_account_on_host'; 
                   1344:         } else {
                   1345:             &logthis("User $uname at $udom authorized by $uhome");
                   1346:             return $uhome;
                   1347:         }
1.471     albertel 1348:     }
                   1349:     if ($answer eq 'non_authorized') {
                   1350: 	&logthis("User $uname at $udom rejected by $uhome");
                   1351: 	return 'no_host'; 
1.9       www      1352:     }
1.471     albertel 1353:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1354:     return 'no_host';
                   1355: }
                   1356: 
1.1073    raeburn  1357: sub can_host_session {
1.1074    raeburn  1358:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1359:     my $canhost = 1;
1.1074    raeburn  1360:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1361:     if (ref($remotesessions) eq 'HASH') {
                   1362:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1363:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1364:                 $canhost = 0;
                   1365:             } else {
                   1366:                 $canhost = 1;
                   1367:             }
                   1368:         }
                   1369:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1370:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1371:                 $canhost = 1;
                   1372:             } else {
                   1373:                 $canhost = 0;
                   1374:             }
                   1375:         }
                   1376:         if ($canhost) {
                   1377:             if ($remotesessions->{'version'} ne '') {
                   1378:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1379:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1380:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1381:                         my $major = $1;
                   1382:                         my $minor = $2;
                   1383:                         if (($major < $reqmajor ) ||
                   1384:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1385:                             $canhost = 0;
                   1386:                         }
                   1387:                     } else {
                   1388:                         $canhost = 0;
                   1389:                     }
                   1390:                 }
                   1391:             }
                   1392:         }
                   1393:     }
                   1394:     if ($canhost) {
                   1395:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1396:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1397:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1398:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1399:                 if (($uint_dom ne '') && 
                   1400:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1401:                     $canhost = 0;
                   1402:                 } else {
                   1403:                     $canhost = 1;
                   1404:                 }
                   1405:             }
                   1406:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1407:                 if (($uint_dom ne '') && 
                   1408:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1409:                     $canhost = 1;
                   1410:                 } else {
                   1411:                     $canhost = 0;
                   1412:                 }
                   1413:             }
                   1414:         }
                   1415:     }
                   1416:     return $canhost;
                   1417: }
                   1418: 
1.1083    raeburn  1419: sub spare_can_host {
                   1420:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1421:     my $canhost=1;
1.1279    raeburn  1422:     my $try_server_hostname = &hostname($try_server);
                   1423:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1424:     my $serverhomedom = &host_domain($serverhomeID);
                   1425:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1426:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1427:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1428:             $canhost = 0;
                   1429:         }
                   1430:     }
                   1431:     if (($canhost) && ($uint_dom)) {
                   1432:         my @intdoms;
                   1433:         my $internet_names = &get_internet_names($try_server);
                   1434:         if (ref($internet_names) eq 'ARRAY') {
                   1435:             @intdoms = @{$internet_names};
                   1436:         }
                   1437:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1438:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1439:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1440:                                          $remotesessions,
                   1441:                                          $defdomdefaults{'hostedsessions'});
                   1442:         }
1.1083    raeburn  1443:     }
                   1444:     return $canhost;
                   1445: }
                   1446: 
1.1123    raeburn  1447: sub this_host_spares {
                   1448:     my ($dom) = @_;
1.1126    raeburn  1449:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1450:     my @hosts = &current_machine_ids();
                   1451:     foreach my $lonhost (@hosts) {
                   1452:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1453:             $dom_in_use = $dom;
                   1454:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1455:             last;
                   1456:         }
                   1457:     }
1.1126    raeburn  1458:     if ($dom_in_use ne '') {
                   1459:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1460:     }
                   1461:     if (ref($result) ne 'HASH') {
                   1462:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1463:         $dom_in_use = &host_domain($lonhost_in_use);
                   1464:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1465:         if (ref($result) ne 'HASH') {
                   1466:             $result = \%spareid;
                   1467:         }
                   1468:     }
                   1469:     return $result;
                   1470: }
                   1471: 
                   1472: sub spares_for_offload  {
                   1473:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1474:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1475:     if (defined($cached)) {
                   1476:         return $result;
                   1477:     } else {
1.1126    raeburn  1478:         my $cachetime = 60*60*24;
                   1479:         my %domconfig =
                   1480:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1481:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1482:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1483:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1484:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1485:                 }
                   1486:             }
                   1487:         }
                   1488:     }
1.1126    raeburn  1489:     return;
1.1123    raeburn  1490: }
                   1491: 
1.1129    raeburn  1492: sub get_lonbalancer_config {
                   1493:     my ($servers) = @_;
                   1494:     my ($currbalancer,$currtargets);
                   1495:     if (ref($servers) eq 'HASH') {
                   1496:         foreach my $server (keys(%{$servers})) {
                   1497:             my %what = (
                   1498:                          spareid => 1,
                   1499:                          perlvar => 1,
                   1500:                        );
                   1501:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1502:             if ($result eq 'ok') {
                   1503:                 if (ref($returnhash) eq 'HASH') {
                   1504:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1505:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1506:                             $currbalancer = $server;
                   1507:                             $currtargets = {};
                   1508:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1509:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1510:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1511:                                 }
                   1512:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1513:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1514:                                 }
                   1515:                             }
                   1516:                             last;
                   1517:                         }
                   1518:                     }
                   1519:                 }
                   1520:             }
                   1521:         }
                   1522:     }
                   1523:     return ($currbalancer,$currtargets);
                   1524: }
                   1525: 
                   1526: sub check_loadbalancing {
1.1331    raeburn  1527:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1528:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1529:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1530:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1531:     my @hosts = &current_machine_ids();
1.1129    raeburn  1532:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1533:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1534:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1535:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1536:     my $domneedscache;
1.1129    raeburn  1537:     my $cachetime = 60*60*24;
                   1538: 
                   1539:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1540:         $dom_in_use = $udom;
                   1541:         $homeintdom = 1;
                   1542:     } else {
                   1543:         $dom_in_use = $serverhomedom;
                   1544:     }
                   1545:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1546:     unless (defined($cached)) {
                   1547:         my %domconfig =
                   1548:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1549:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1550:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1551:         } else {
                   1552:             $domneedscache = $dom_in_use;
1.1129    raeburn  1553:         }
                   1554:     }
                   1555:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1556:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1557:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1558:         if ($is_balancer) {
                   1559:             if (ref($currrules) eq 'HASH') {
                   1560:                 if ($homeintdom) {
                   1561:                     if ($uname ne '') {
                   1562:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1563:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1564:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1565:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1566:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1567:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1568:                             }
                   1569:                         }
                   1570:                         if ($rule_in_effect eq '') {
                   1571:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1572:                             if ($userenv{'inststatus'} ne '') {
                   1573:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1574:                                 my ($othertitle,$usertypes,$types) =
                   1575:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1576:                                 if (ref($types) eq 'ARRAY') {
                   1577:                                     foreach my $type (@{$types}) {
                   1578:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1579:                                             if (exists($currrules->{$type})) {
                   1580:                                                 $rule_in_effect = $currrules->{$type};
                   1581:                                             }
                   1582:                                         }
                   1583:                                     }
                   1584:                                 }
                   1585:                             } else {
                   1586:                                 if (exists($currrules->{'default'})) {
                   1587:                                     $rule_in_effect = $currrules->{'default'};
                   1588:                                 }
                   1589:                             }
                   1590:                         }
                   1591:                     } else {
                   1592:                         if (exists($currrules->{'default'})) {
                   1593:                             $rule_in_effect = $currrules->{'default'};
                   1594:                         }
                   1595:                     }
                   1596:                 } else {
                   1597:                     if ($currrules->{'_LC_external'} ne '') {
                   1598:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1599:                     }
                   1600:                 }
                   1601:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1602:                                                        $uname,$udom);
                   1603:             }
                   1604:         }
                   1605:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1606:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1607:         unless (defined($cached)) {
                   1608:             my %domconfig =
                   1609:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1610:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1611:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1612:             } else {
                   1613:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1614:             }
                   1615:         }
                   1616:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1617:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1618:                 &check_balancer_result($result,@hosts);
                   1619:             if ($is_balancer) {
1.1129    raeburn  1620:                 if (ref($currrules) eq 'HASH') {
                   1621:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1622:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1623:                     }
                   1624:                 }
                   1625:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1626:                                                        $uname,$udom);
                   1627:             }
                   1628:         } else {
                   1629:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1630:                 $is_balancer = 1;
                   1631:                 $offloadto = &this_host_spares($dom_in_use);
                   1632:             }
1.1307    raeburn  1633:             unless (defined($cached)) {
                   1634:                 $domneedscache = $serverhomedom;
                   1635:             }
1.1129    raeburn  1636:         }
                   1637:     } else {
                   1638:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1639:             $is_balancer = 1;
                   1640:             $offloadto = &this_host_spares($dom_in_use);
                   1641:         }
1.1307    raeburn  1642:         unless (defined($cached)) {
                   1643:             $domneedscache = $serverhomedom;
                   1644:         }
                   1645:     }
                   1646:     if ($domneedscache) {
                   1647:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1648:     }
1.1176    raeburn  1649:     if ($is_balancer) {
                   1650:         my $lowest_load = 30000;
                   1651:         if (ref($offloadto) eq 'HASH') {
                   1652:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1653:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1654:                     ($otherserver,$lowest_load) =
                   1655:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1656:                 }
1.1129    raeburn  1657:             }
1.1176    raeburn  1658:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1659: 
1.1176    raeburn  1660:             if (!$found_server) {
                   1661:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1662:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1663:                         ($otherserver,$lowest_load) =
                   1664:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1665:                     }
                   1666:                 }
                   1667:             }
                   1668:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1669:             if (@{$offloadto} == 1) {
                   1670:                 $otherserver = $offloadto->[0];
                   1671:             } elsif (@{$offloadto} > 1) {
                   1672:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1673:                     ($otherserver,$lowest_load) =
                   1674:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1675:                 }
                   1676:             }
                   1677:         }
1.1331    raeburn  1678:         unless ($caller eq 'login') {
                   1679:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1680:                 $is_balancer = 0;
                   1681:                 if ($uname ne '' && $udom ne '') {
                   1682:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1683:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1684:                                  'user.loadbalcheck.time' => time});
                   1685:                     }
1.1176    raeburn  1686:                 }
1.1129    raeburn  1687:             }
                   1688:         }
1.1389    raeburn  1689:         unless ($homeintdom) {
                   1690:             undef($setcookie);
                   1691:         }
1.1129    raeburn  1692:     }
1.1391    raeburn  1693:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1694: }
                   1695: 
1.1191    raeburn  1696: sub check_balancer_result {
                   1697:     my ($result,@hosts) = @_;
1.1391    raeburn  1698:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1699:     if (ref($result) eq 'HASH') {
                   1700:         if ($result->{'lonhost'} ne '') {
                   1701:             my $currbalancer = $result->{'lonhost'};
                   1702:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1703:                 $is_balancer = 1;
                   1704:                 $currtargets = $result->{'targets'};
                   1705:                 $currrules = $result->{'rules'};
                   1706:             }
1.1391    raeburn  1707:             $dom_balancers = $currbalancer;
1.1191    raeburn  1708:         } else {
1.1391    raeburn  1709:             if (keys(%{$result})) {
                   1710:                 foreach my $key (keys(%{$result})) {
                   1711:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1712:                         (ref($result->{$key}) eq 'HASH')) {
                   1713:                         $is_balancer = 1;
                   1714:                         $currrules = $result->{$key}{'rules'};
                   1715:                         $currtargets = $result->{$key}{'targets'};
                   1716:                         $setcookie = $result->{$key}{'cookie'};
                   1717:                         last;
                   1718:                     }
1.1191    raeburn  1719:                 }
1.1391    raeburn  1720:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1721:             }
                   1722:         }
                   1723:     }
1.1391    raeburn  1724:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1725: }
                   1726: 
1.1129    raeburn  1727: sub get_loadbalancer_targets {
                   1728:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1729:     my $offloadto;
1.1175    raeburn  1730:     if ($rule_in_effect eq 'none') {
                   1731:         return [$perlvar{'lonHostID'}];
                   1732:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1733:         $offloadto = $currtargets;
                   1734:     } else {
                   1735:         if ($rule_in_effect eq 'homeserver') {
                   1736:             my $homeserver = &homeserver($uname,$udom);
                   1737:             if ($homeserver ne 'no_host') {
                   1738:                 $offloadto = [$homeserver];
                   1739:             }
                   1740:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1741:             my %domconfig =
                   1742:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1743:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1744:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1745:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1746:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1747:                     }
                   1748:                 }
                   1749:             } else {
1.1178    raeburn  1750:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1751:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1752:                 if (&hostname($remotebalancer) ne '') {
                   1753:                     $offloadto = [$remotebalancer];
                   1754:                 }
                   1755:             }
                   1756:         } elsif (&hostname($rule_in_effect) ne '') {
                   1757:             $offloadto = [$rule_in_effect];
                   1758:         }
                   1759:     }
                   1760:     return $offloadto;
                   1761: }
                   1762: 
1.1127    raeburn  1763: sub internet_dom_servers {
                   1764:     my ($dom) = @_;
                   1765:     my (%uniqservers,%servers);
                   1766:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1767:     my @machinedoms = &machine_domains($primaryserver);
                   1768:     foreach my $mdom (@machinedoms) {
                   1769:         my %currservers = %servers;
                   1770:         my %server = &get_servers($mdom);
                   1771:         %servers = (%currservers,%server);
                   1772:     }
                   1773:     my %by_hostname;
                   1774:     foreach my $id (keys(%servers)) {
                   1775:         push(@{$by_hostname{$servers{$id}}},$id);
                   1776:     }
                   1777:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1778:         if (@{$by_hostname{$hostname}} > 1) {
                   1779:             my $match = 0;
                   1780:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1781:                 if (&host_domain($id) eq $dom) {
                   1782:                     $uniqservers{$id} = $hostname;
                   1783:                     $match = 1;
                   1784:                 }
                   1785:             }
                   1786:             unless ($match) {
                   1787:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1788:             }
                   1789:         } else {
                   1790:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1791:         }
                   1792:     }
                   1793:     return %uniqservers;
                   1794: }
                   1795: 
1.1347    raeburn  1796: sub trusted_domains {
                   1797:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1798:     my ($trusted,$untrusted);
1.1347    raeburn  1799:     if (&domain($calldom) eq '') {
1.1349    raeburn  1800:         return ($trusted,$untrusted);
1.1347    raeburn  1801:     }
1.1395    raeburn  1802:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1803:         return ($trusted,$untrusted);
1.1347    raeburn  1804:     }
                   1805:     my $callprimary = &domain($calldom,'primary');
                   1806:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1807:     if ($intcalldom eq '') {
1.1349    raeburn  1808:         return ($trusted,$untrusted);
1.1347    raeburn  1809:     }
                   1810: 
                   1811:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1812:     unless (defined($cached)) {
                   1813:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1814:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1815:         $trustconfig = $domconfig{'trust'};
                   1816:     }
                   1817:     if (ref($trustconfig)) {
                   1818:         my (%possexc,%possinc,@allexc,@allinc); 
                   1819:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1820:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1821:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1822:             }
                   1823:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1824:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1825:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1826:             }
                   1827:         }
                   1828:         if (keys(%possexc)) {
                   1829:             if (keys(%possinc)) {
                   1830:                 foreach my $key (sort(keys(%possexc))) {
                   1831:                     next if ($key eq $intcalldom);
                   1832:                     unless ($possinc{$key}) {
                   1833:                         push(@allexc,$key);
                   1834:                     }
                   1835:                 }
                   1836:             } else {
                   1837:                 @allexc = sort(keys(%possexc));
                   1838:             }
                   1839:         }
                   1840:         if (keys(%possinc)) {
                   1841:             $possinc{$intcalldom} = 1;
                   1842:             @allinc = sort(keys(%possinc));
                   1843:         }
                   1844:         if ((@allexc > 0) || (@allinc > 0)) {
                   1845:             my %doms_by_intdom;
                   1846:             my %allintdoms = &all_host_intdom();
                   1847:             my %alldoms = &all_host_domain();
                   1848:             foreach my $key (%allintdoms) {
                   1849:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1850:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1851:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1852:                     }
                   1853:                 } else {
                   1854:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1855:                 }
                   1856:             }
                   1857:             foreach my $exc (@allexc) {
                   1858:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1859:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1860:                 }
                   1861:             }
                   1862:             foreach my $inc (@allinc) {
                   1863:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1864:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1865:                 }
                   1866:             }
                   1867:         }
                   1868:     }
1.1349    raeburn  1869:     return ($trusted,$untrusted);
1.1347    raeburn  1870: }
                   1871: 
                   1872: sub will_trust {
                   1873:     my ($cmdtype,$domain,$possdom) = @_;
                   1874:     return 1 if ($domain eq $possdom);
                   1875:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1876:     my $willtrust; 
                   1877:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1878:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1879:             $willtrust = 1;
                   1880:         }
                   1881:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1882:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1883:             $willtrust = 1;
                   1884:         }
                   1885:     } else {
                   1886:         $willtrust = 1;
                   1887:     }
                   1888:     return $willtrust;
                   1889: }
                   1890: 
1.1       albertel 1891: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1892: 
1.599     albertel 1893: my %homecache;
1.1       albertel 1894: sub homeserver {
1.230     stredwic 1895:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1896:     my $index="$uname:$udom";
1.426     albertel 1897: 
1.599     albertel 1898:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1899: 
                   1900:     my %servers = &get_servers($udom,'library');
                   1901:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1902:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1903: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1904: 
                   1905: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1906: 	if ($answer eq 'found') {
                   1907: 	    delete($badServerCache{$tryserver}); 
                   1908: 	    return $homecache{$index}=$tryserver;
                   1909: 	} elsif ($answer eq 'no_host') {
                   1910: 	    $badServerCache{$tryserver}=1;
                   1911: 	}
1.1       albertel 1912:     }    
                   1913:     return 'no_host';
1.70      www      1914: }
                   1915: 
1.1300    raeburn  1916: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1917: 
                   1918: sub idget {
1.1300    raeburn  1919:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1920:     my %returnhash=();
1.1300    raeburn  1921:     my @ids=(); 
                   1922:     if (ref($idsref) eq 'ARRAY') {
                   1923:         @ids = @{$idsref};
                   1924:     } else {
                   1925:         return %returnhash; 
                   1926:     }
                   1927:     if ($namespace eq '') {
                   1928:         $namespace = 'ids';
                   1929:     }
1.70      www      1930:     
1.841     albertel 1931:     my %servers = &get_servers($udom,'library');
                   1932:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1933: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1934: 	if ($namespace eq 'ids') {
                   1935: 	    $idlist=~tr/A-Z/a-z/;
                   1936: 	}
                   1937: 	my $reply;
                   1938: 	if ($namespace eq 'ids') {
                   1939: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1940: 	} else {
                   1941: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1942: 	}
1.841     albertel 1943: 	my @answer=();
                   1944: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1945: 	    @answer=split(/\&/,$reply);
                   1946: 	}                    ;
                   1947: 	my $i;
                   1948: 	for ($i=0;$i<=$#ids;$i++) {
                   1949: 	    if ($answer[$i]) {
1.1299    raeburn  1950: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1951: 	    }
1.841     albertel 1952: 	}
1.1300    raeburn  1953:     }
1.70      www      1954:     return %returnhash;
                   1955: }
                   1956: 
                   1957: # ------------------------------------- Find the IDs behind a list of usernames
                   1958: 
                   1959: sub idrget {
                   1960:     my ($udom,@unames)=@_;
                   1961:     my %returnhash=();
1.800     albertel 1962:     foreach my $uname (@unames) {
                   1963:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1964:     }
1.70      www      1965:     return %returnhash;
                   1966: }
                   1967: 
1.1300    raeburn  1968: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1969: 
                   1970: sub idput {
1.1300    raeburn  1971:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1972:     my %servers=();
1.1300    raeburn  1973:     my %ids=();
                   1974:     my %byid = ();
                   1975:     if (ref($idsref) eq 'HASH') {
                   1976:         %ids=%{$idsref};
                   1977:     }
                   1978:     if ($namespace eq '') {
                   1979:         $namespace = 'ids'; 
                   1980:     }
1.800     albertel 1981:     foreach my $uname (keys(%ids)) {
                   1982: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1983:         if ($uhom eq '') {
                   1984:             $uhom=&homeserver($uname,$udom);
                   1985:         }
1.70      www      1986:         if ($uhom ne 'no_host') {
1.800     albertel 1987:             my $esc_unam=&escape($uname);
1.1300    raeburn  1988:             if ($namespace eq 'ids') {
                   1989:                 my $id=&escape($ids{$uname});
                   1990:                 $id=~tr/A-Z/a-z/;
                   1991:                 my $esc_unam=&escape($uname);
                   1992:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1993:             } else {
1.1300    raeburn  1994:                 my @currids = split(/,/,$ids{$uname});
                   1995:                 foreach my $id (@currids) {
                   1996:                     $byid{$uhom}{$id} .= $uname.',';
                   1997:                 }
                   1998:             }
                   1999:         }
                   2000:     }
                   2001:     if ($namespace eq 'clickers') {
                   2002:         foreach my $server (keys(%byid)) {
                   2003:             if (ref($byid{$server}) eq 'HASH') {
                   2004:                 foreach my $id (keys(%{$byid{$server}})) {
                   2005:                     $byid{$server} =~ s/,$//;
                   2006:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   2007:                 }
1.70      www      2008:             }
                   2009:         }
1.191     harris41 2010:     }
1.800     albertel 2011:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2012:         $servers{$server} =~ s/\&$//;
                   2013:         if ($namespace eq 'ids') {     
                   2014:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   2015:         } else {
                   2016:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   2017:         }
1.191     harris41 2018:     }
1.344     www      2019: }
                   2020: 
1.1300    raeburn  2021: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2022: 
                   2023: sub iddel {
1.1300    raeburn  2024:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2025:     my %result=();
1.1300    raeburn  2026:     my %ids=();
                   2027:     my %byid = ();
                   2028:     if (ref($idshashref) eq 'HASH') {
                   2029:         %ids=%{$idshashref};
                   2030:     } else {
1.1231    raeburn  2031:         return %result;
                   2032:     }
1.1300    raeburn  2033:     if ($namespace eq '') {
                   2034:         $namespace = 'ids';
                   2035:     }
1.1231    raeburn  2036:     my %servers=();
1.1300    raeburn  2037:     while (my ($id,$unamestr) = each(%ids)) {
                   2038:         if ($namespace eq 'ids') {
                   2039:             my $uhom = $uhome;
                   2040:             if ($uhom eq '') { 
                   2041:                 $uhom=&homeserver($unamestr,$udom);
                   2042:             }
                   2043:             if ($uhom ne 'no_host') {
                   2044:                 $servers{$uhom}.='&'.&escape($id);
                   2045:             }
                   2046:          } else {
                   2047:             my @curritems = split(/,/,$ids{$id});
                   2048:             foreach my $uname (@curritems) {
                   2049:                 my $uhom = $uhome;
                   2050:                 if ($uhom eq '') {
                   2051:                     $uhom=&homeserver($uname,$udom);
                   2052:                 }
                   2053:                 if ($uhom ne 'no_host') { 
                   2054:                     $byid{$uhom}{$id} .= $uname.',';
                   2055:                 }
                   2056:             }
1.1231    raeburn  2057:         }
1.1300    raeburn  2058:     }
                   2059:     if ($namespace eq 'clickers') {
                   2060:         foreach my $server (keys(%byid)) {
                   2061:             if (ref($byid{$server}) eq 'HASH') {
                   2062:                 foreach my $id (keys(%{$byid{$server}})) {
                   2063:                     $byid{$server}{$id} =~ s/,$//;
                   2064:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2065:                 }
1.1231    raeburn  2066:             }
                   2067:         }
                   2068:     }
                   2069:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2070:         $servers{$server} =~ s/\&$//;
                   2071:         if ($namespace eq 'ids') {
                   2072:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2073:         } elsif ($namespace eq 'clickers') {
                   2074:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2075:         }
1.1231    raeburn  2076:     }
                   2077:     return %result;
                   2078: }
                   2079: 
1.1300    raeburn  2080: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2081: 
                   2082: sub updateclickers {
                   2083:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2084:     my %clickers;
                   2085:     if (ref($idshashref) eq 'HASH') {
                   2086:         %clickers=%{$idshashref};
                   2087:     } else {
                   2088:         return;
                   2089:     }
                   2090:     my $items='';
                   2091:     foreach my $item (keys(%clickers)) {
                   2092:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2093:     }
                   2094:     $items=~s/\&$//;
                   2095:     my $request = "updateclickers:$udom:$action:$items";
                   2096:     if ($critical) {
                   2097:         return &critical($request,$uhome);
                   2098:     } else {
                   2099:         return &reply($request,$uhome);
                   2100:     }
                   2101: }
                   2102: 
1.1023    raeburn  2103: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2104: sub dump_dom {
1.1165    droeschl 2105:     my ($namespace, $udom, $regexp) = @_;
                   2106: 
                   2107:     $udom ||= $env{'user.domain'};
                   2108: 
                   2109:     return () unless $udom;
                   2110: 
                   2111:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2112: }
                   2113: 
1.1023    raeburn  2114: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2115: 
                   2116: sub get_dom {
1.860     raeburn  2117:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2118:     return if ($udom eq 'public');
1.806     raeburn  2119:     my $items='';
                   2120:     foreach my $item (@$storearr) {
                   2121:         $items.=&escape($item).'&';
                   2122:     }
                   2123:     $items=~s/\&$//;
1.860     raeburn  2124:     if (!$udom) {
                   2125:         $udom=$env{'user.domain'};
1.1267    raeburn  2126:         return if ($udom eq 'public');
1.860     raeburn  2127:         if (defined(&domain($udom,'primary'))) {
                   2128:             $uhome=&domain($udom,'primary');
                   2129:         } else {
1.874     albertel 2130:             undef($uhome);
1.860     raeburn  2131:         }
                   2132:     } else {
                   2133:         if (!$uhome) {
                   2134:             if (defined(&domain($udom,'primary'))) {
                   2135:                 $uhome=&domain($udom,'primary');
                   2136:             }
                   2137:         }
                   2138:     }
                   2139:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2140:         my $rep;
                   2141:         if ($namespace =~ /^enc/) {
                   2142:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2143:         } else {
                   2144:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2145:         }
1.866     raeburn  2146:         my %returnhash;
1.875     albertel 2147:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2148:             return %returnhash;
                   2149:         }
1.806     raeburn  2150:         my @pairs=split(/\&/,$rep);
                   2151:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2152:             return @pairs;
                   2153:         }
                   2154:         my $i=0;
                   2155:         foreach my $item (@$storearr) {
                   2156:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2157:             $i++;
                   2158:         }
                   2159:         return %returnhash;
                   2160:     } else {
1.880     banghart 2161:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2162:     }
                   2163: }
                   2164: 
                   2165: # -------------------------------------------- put items in domain db files 
                   2166: 
                   2167: sub put_dom {
1.860     raeburn  2168:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2169:     if (!$udom) {
                   2170:         $udom=$env{'user.domain'};
                   2171:         if (defined(&domain($udom,'primary'))) {
                   2172:             $uhome=&domain($udom,'primary');
                   2173:         } else {
1.874     albertel 2174:             undef($uhome);
1.860     raeburn  2175:         }
                   2176:     } else {
                   2177:         if (!$uhome) {
                   2178:             if (defined(&domain($udom,'primary'))) {
                   2179:                 $uhome=&domain($udom,'primary');
                   2180:             }
                   2181:         }
                   2182:     } 
                   2183:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2184:         my $items='';
                   2185:         foreach my $item (keys(%$storehash)) {
                   2186:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2187:         }
                   2188:         $items=~s/\&$//;
1.1344    raeburn  2189:         if ($namespace =~ /^enc/) {
                   2190:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2191:         } else {
                   2192:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2193:         }
1.806     raeburn  2194:     } else {
1.860     raeburn  2195:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2196:     }
                   2197: }
                   2198: 
1.1023    raeburn  2199: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2200: sub newput_dom {
1.1023    raeburn  2201:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2202:     my $result;
                   2203:     if (!$udom) {
                   2204:         $udom=$env{'user.domain'};
                   2205:     }
1.1023    raeburn  2206:     if ($udom) {
                   2207:         my $uname = &get_domainconfiguser($udom);
                   2208:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2209:     }
                   2210:     return $result;
                   2211: }
                   2212: 
1.1023    raeburn  2213: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2214: sub del_dom {
1.1023    raeburn  2215:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2216:     if (ref($storearr) eq 'ARRAY') {
                   2217:         if (!$udom) {
                   2218:             $udom=$env{'user.domain'};
                   2219:         }
1.1023    raeburn  2220:         if ($udom) {
                   2221:             my $uname = &get_domainconfiguser($udom); 
                   2222:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2223:         }
                   2224:     }
                   2225: }
                   2226: 
1.1023    raeburn  2227: # ----------------------------------construct domainconfig user for a domain 
                   2228: sub get_domainconfiguser {
                   2229:     my ($udom) = @_;
                   2230:     return $udom.'-domainconfig';
                   2231: }
                   2232: 
1.837     raeburn  2233: sub retrieve_inst_usertypes {
                   2234:     my ($udom) = @_;
                   2235:     my (%returnhash,@order);
1.989     raeburn  2236:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2237:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2238:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2239:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2240:     } else {
                   2241:         if (defined(&domain($udom,'primary'))) {
                   2242:             my $uhome=&domain($udom,'primary');
                   2243:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2244:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2245:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2246:                 return (\%returnhash,\@order);
                   2247:             }
                   2248:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2249:             my @pairs=split(/\&/,$hashitems);
                   2250:             foreach my $item (@pairs) {
                   2251:                 my ($key,$value)=split(/=/,$item,2);
                   2252:                 $key = &unescape($key);
                   2253:                 next if ($key =~ /^error: 2 /);
                   2254:                 $returnhash{$key}=&thaw_unescape($value);
                   2255:             }
                   2256:             my @esc_order = split(/\&/,$orderitems);
                   2257:             foreach my $item (@esc_order) {
                   2258:                 push(@order,&unescape($item));
                   2259:             }
                   2260:         } else {
1.1256    raeburn  2261:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2262:         }
1.1256    raeburn  2263:         return (\%returnhash,\@order);
1.837     raeburn  2264:     }
                   2265: }
                   2266: 
1.868     raeburn  2267: sub is_domainimage {
                   2268:     my ($url) = @_;
1.1306    raeburn  2269:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2270:         if (&domain($1) ne '') {
                   2271:             return '1';
                   2272:         }
                   2273:     }
                   2274:     return;
                   2275: }
                   2276: 
1.899     raeburn  2277: sub inst_directory_query {
                   2278:     my ($srch) = @_;
                   2279:     my $udom = $srch->{'srchdomain'};
                   2280:     my %results;
                   2281:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2282:     my $outcome;
1.899     raeburn  2283:     if ($homeserver ne '') {
1.1357    raeburn  2284:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2285:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2286:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2287:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2288:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2289:                     (($major == 2) && ($minor < 12))) {
                   2290:                     return;
                   2291:                 }
                   2292:             }
                   2293:         }
1.904     albertel 2294: 	my $queryid=&reply("querysend:instdirsearch:".
                   2295: 			   &escape($srch->{'srchby'}).':'.
                   2296: 			   &escape($srch->{'srchterm'}).':'.
                   2297: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2298: 	my $host=&hostname($homeserver);
                   2299: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2300: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2301: 	    return;
                   2302: 	}
                   2303: 	my $response = &get_query_reply($queryid);
                   2304: 	my $maxtries = 5;
                   2305: 	my $tries = 1;
                   2306: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2307: 	    $response = &get_query_reply($queryid);
                   2308: 	    $tries ++;
                   2309: 	}
                   2310: 
                   2311:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2312:             if ($response eq 'unavailable') {
                   2313:                 $outcome = $response;
                   2314:             } else {
                   2315:                 $outcome = 'ok';
                   2316:                 my @matches = split(/\n/,$response);
                   2317:                 foreach my $match (@matches) {
                   2318:                     my ($key,$value) = split(/=/,$match);
                   2319:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2320:                 }
1.899     raeburn  2321:             }
                   2322:         }
                   2323:     }
1.909     raeburn  2324:     return ($outcome,%results);
1.899     raeburn  2325: }
                   2326: 
                   2327: sub usersearch {
                   2328:     my ($srch) = @_;
                   2329:     my $dom = $srch->{'srchdomain'};
                   2330:     my %results;
                   2331:     my %libserv = &all_library();
                   2332:     my $query = 'usersearch';
                   2333:     foreach my $tryserver (keys(%libserv)) {
                   2334:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2335:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2336:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2337:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2338:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2339:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2340:                              (($major == 2) && ($minor < 12)));
                   2341:                 }
                   2342:             }
1.899     raeburn  2343:             my $host=&hostname($tryserver);
                   2344:             my $queryid=
1.911     raeburn  2345:                 &reply("querysend:".&escape($query).':'.
                   2346:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2347:                        &escape($srch->{'srchtype'}).':'.
                   2348:                        &escape($srch->{'srchterm'}),$tryserver);
                   2349:             if ($queryid !~/^\Q$host\E\_/) {
                   2350:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2351:                 next;
1.899     raeburn  2352:             }
                   2353:             my $reply = &get_query_reply($queryid);
                   2354:             my $maxtries = 1;
                   2355:             my $tries = 1;
                   2356:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2357:                 $reply = &get_query_reply($queryid);
                   2358:                 $tries ++;
                   2359:             }
                   2360:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2361:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2362:             } else {
1.911     raeburn  2363:                 my @matches;
                   2364:                 if ($reply =~ /\n/) {
                   2365:                     @matches = split(/\n/,$reply);
                   2366:                 } else {
                   2367:                     @matches = split(/\&/,$reply);
                   2368:                 }
1.899     raeburn  2369:                 foreach my $match (@matches) {
                   2370:                     my ($uname,$udom,%userhash);
1.911     raeburn  2371:                     foreach my $entry (split(/:/,$match)) {
                   2372:                         my ($key,$value) =
                   2373:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2374:                         $userhash{$key} = $value;
                   2375:                         if ($key eq 'username') {
                   2376:                             $uname = $value;
                   2377:                         } elsif ($key eq 'domain') {
                   2378:                             $udom = $value;
1.911     raeburn  2379:                         }
1.899     raeburn  2380:                     }
                   2381:                     $results{$uname.':'.$udom} = \%userhash;
                   2382:                 }
                   2383:             }
                   2384:         }
                   2385:     }
                   2386:     return %results;
                   2387: }
                   2388: 
1.912     raeburn  2389: sub get_instuser {
                   2390:     my ($udom,$uname,$id) = @_;
                   2391:     my $homeserver = &domain($udom,'primary');
                   2392:     my ($outcome,%results);
                   2393:     if ($homeserver ne '') {
                   2394:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2395:                            &escape($id).':'.&escape($udom),$homeserver);
                   2396:         my $host=&hostname($homeserver);
                   2397:         if ($queryid !~/^\Q$host\E\_/) {
                   2398:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2399:             return;
                   2400:         }
                   2401:         my $response = &get_query_reply($queryid);
                   2402:         my $maxtries = 5;
                   2403:         my $tries = 1;
                   2404:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2405:             $response = &get_query_reply($queryid);
                   2406:             $tries ++;
                   2407:         }
                   2408:         if (!&error($response) && $response ne 'refused') {
                   2409:             if ($response eq 'unavailable') {
                   2410:                 $outcome = $response;
                   2411:             } else {
                   2412:                 $outcome = 'ok';
                   2413:                 my @matches = split(/\n/,$response);
                   2414:                 foreach my $match (@matches) {
                   2415:                     my ($key,$value) = split(/=/,$match);
                   2416:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2417:                 }
                   2418:             }
                   2419:         }
                   2420:     }
                   2421:     my %userinfo;
                   2422:     if (ref($results{$uname}) eq 'HASH') {
                   2423:         %userinfo = %{$results{$uname}};
                   2424:     } 
                   2425:     return ($outcome,%userinfo);
                   2426: }
                   2427: 
1.1290    raeburn  2428: sub get_multiple_instusers {
                   2429:     my ($udom,$users,$caller) = @_;
                   2430:     my ($outcome,$results);
                   2431:     if (ref($users) eq 'HASH') {
                   2432:         my $count = keys(%{$users}); 
                   2433:         my $requested = &freeze_escape($users);
                   2434:         my $homeserver = &domain($udom,'primary');
                   2435:         if ($homeserver ne '') {
                   2436:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2437:             my $host=&hostname($homeserver);
                   2438:             if ($queryid !~/^\Q$host\E\_/) {
                   2439:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2440:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2441:                 return ($outcome,$results);
                   2442:             }
                   2443:             my $response = &get_query_reply($queryid);
                   2444:             my $maxtries = 5;
                   2445:             if ($count > 100) {
                   2446:                 $maxtries = 1+int($count/20);
                   2447:             }
                   2448:             my $tries = 1;
                   2449:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2450:                 $response = &get_query_reply($queryid);
                   2451:                 $tries ++;
                   2452:             }
                   2453:             if ($response eq '') {
                   2454:                 $results = {};
                   2455:                 foreach my $key (keys(%{$users})) {
                   2456:                     my ($uname,$id);
                   2457:                     if ($caller eq 'id') {
                   2458:                         $id = $key;
                   2459:                     } else {
                   2460:                         $uname = $key;
                   2461:                     }
                   2462:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2463:                     $outcome = $resp;
1.1290    raeburn  2464:                     if ($resp eq 'ok') {
                   2465:                         %{$results} = (%{$results}, %info);
                   2466:                     } else {
                   2467:                         last;
                   2468:                     }
                   2469:                 }
                   2470:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2471:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2472:                     $outcome = $response;
                   2473:                 } else {
1.1291    raeburn  2474:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2475:                     if ($outcome eq 'ok') {
                   2476:                         $results = &thaw_unescape($userdata); 
                   2477:                     }
                   2478:                 }
                   2479:             }
                   2480:         }
                   2481:     }
                   2482:     return ($outcome,$results);
                   2483: }
                   2484: 
1.912     raeburn  2485: sub inst_rulecheck {
1.923     raeburn  2486:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2487:     my %returnhash;
                   2488:     if ($udom ne '') {
                   2489:         if (ref($rules) eq 'ARRAY') {
                   2490:             @{$rules} = map {&escape($_);} (@{$rules});
                   2491:             my $rulestr = join(':',@{$rules});
                   2492:             my $homeserver=&domain($udom,'primary');
                   2493:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2494:                 my $response;
                   2495:                 if ($item eq 'username') {                
                   2496:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2497:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2498:                                               $homeserver));
1.923     raeburn  2499:                 } elsif ($item eq 'id') {
                   2500:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2501:                                               ':'.&escape($id).':'.$rulestr,
                   2502:                                               $homeserver));
1.945     raeburn  2503:                 } elsif ($item eq 'selfcreate') {
                   2504:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2505:                                                &escape($udom).':'.&escape($uname).
                   2506:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2507:                 }
1.912     raeburn  2508:                 if ($response ne 'refused') {
                   2509:                     my @pairs=split(/\&/,$response);
                   2510:                     foreach my $item (@pairs) {
                   2511:                         my ($key,$value)=split(/=/,$item,2);
                   2512:                         $key = &unescape($key);
                   2513:                         next if ($key =~ /^error: 2 /);
                   2514:                         $returnhash{$key}=&thaw_unescape($value);
                   2515:                     }
                   2516:                 }
                   2517:             }
                   2518:         }
                   2519:     }
                   2520:     return %returnhash;
                   2521: }
                   2522: 
                   2523: sub inst_userrules {
1.923     raeburn  2524:     my ($udom,$check) = @_;
1.912     raeburn  2525:     my (%ruleshash,@ruleorder);
                   2526:     if ($udom ne '') {
                   2527:         my $homeserver=&domain($udom,'primary');
                   2528:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2529:             my $response;
                   2530:             if ($check eq 'id') {
                   2531:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2532:                                  $homeserver);
1.943     raeburn  2533:             } elsif ($check eq 'email') {
                   2534:                 $response=&reply('instemailrules:'.&escape($udom),
                   2535:                                  $homeserver);
1.923     raeburn  2536:             } else {
                   2537:                 $response=&reply('instuserrules:'.&escape($udom),
                   2538:                                  $homeserver);
                   2539:             }
1.912     raeburn  2540:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2541:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2542:                 ($response ne 'no_such_host')) {
                   2543:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2544:                 my @pairs=split(/\&/,$hashitems);
                   2545:                 foreach my $item (@pairs) {
                   2546:                     my ($key,$value)=split(/=/,$item,2);
                   2547:                     $key = &unescape($key);
                   2548:                     next if ($key =~ /^error: 2 /);
                   2549:                     $ruleshash{$key}=&thaw_unescape($value);
                   2550:                 }
                   2551:                 my @esc_order = split(/\&/,$orderitems);
                   2552:                 foreach my $item (@esc_order) {
                   2553:                     push(@ruleorder,&unescape($item));
                   2554:                 }
                   2555:             }
                   2556:         }
                   2557:     }
                   2558:     return (\%ruleshash,\@ruleorder);
                   2559: }
                   2560: 
1.976     raeburn  2561: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2562: 
                   2563: sub get_domain_defaults {
1.1240    raeburn  2564:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2565:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2566:     my $cachetime = 60*60*24;
1.1240    raeburn  2567:     unless ($ignore_cache) {
                   2568:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2569:         if (defined($cached)) {
                   2570:             if (ref($result) eq 'HASH') {
                   2571:                 return %{$result};
                   2572:             }
1.943     raeburn  2573:         }
                   2574:     }
                   2575:     my %domdefaults;
                   2576:     my %domconfig =
1.989     raeburn  2577:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2578:                                   'requestcourses','inststatus',
1.1183    raeburn  2579:                                   'coursedefaults','usersessions',
1.1258    raeburn  2580:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2581:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2582:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2583:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2584:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2585:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2586:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2587:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2588:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2589:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2590:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2591:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2592:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2593:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2594:     } else {
                   2595:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2596:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2597:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2598:     }
1.976     raeburn  2599:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2600:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2601:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2602:         } else {
                   2603:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2604:         }
1.1177    raeburn  2605:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2606:         foreach my $item (@usertools) {
                   2607:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2608:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2609:             }
                   2610:         }
1.1229    raeburn  2611:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2612:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2613:         }
1.976     raeburn  2614:     }
1.985     raeburn  2615:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2616:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2617:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2618:         }
                   2619:     }
1.1183    raeburn  2620:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2621:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2622:     }
1.989     raeburn  2623:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2624:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2625:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2626:         }
                   2627:     }
1.1047    raeburn  2628:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2629:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2630:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2631:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2632:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2633:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2634:         }
1.1254    raeburn  2635:         foreach my $type (@coursetypes) {
                   2636:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2637:                 unless ($type eq 'community') {
                   2638:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2639:                 }
                   2640:             }
                   2641:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2642:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2643:             }
1.1277    raeburn  2644:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2645:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2646:                     $domdefaults{$type.'postsubtimeout'} = 
                   2647:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2648:                 }
                   2649:             }
1.1230    raeburn  2650:         }
1.1286    raeburn  2651:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2652:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2653:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2654:                 if (@clonecodes) {
                   2655:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2656:                 }
                   2657:             }
                   2658:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2659:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2660:         }
1.1356    raeburn  2661:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2662:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2663:         } 
1.1047    raeburn  2664:     }
1.1073    raeburn  2665:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2666:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2667:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2668:         }
                   2669:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2670:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2671:         }
1.1279    raeburn  2672:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2673:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2674:         }
1.1073    raeburn  2675:     }
1.1254    raeburn  2676:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2677:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2678:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2679:                             'approval','limit');
                   2680:             foreach my $type (@coursetypes) {
                   2681:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2682:                     my @mgrdc = ();
                   2683:                     foreach my $item (@settings) {
                   2684:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2685:                             push(@mgrdc,$item);
                   2686:                         }
                   2687:                     }
                   2688:                     if (@mgrdc) {
                   2689:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2690:                     }
                   2691:                 }
                   2692:             }
                   2693:         }
                   2694:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2695:             foreach my $type (@coursetypes) {
                   2696:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2697:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2698:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2699:                     }
                   2700:                 }
                   2701:             }
                   2702:         }
                   2703:     }
1.1258    raeburn  2704:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2705:         $domdefaults{'catauth'} = 'std';
                   2706:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2707:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2708:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2709:         }
                   2710:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2711:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2712:         }
                   2713:     }
1.1315    raeburn  2714:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2715:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2716:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2717:         }
1.1338    raeburn  2718:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2719:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2720:         }
                   2721:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2722:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2723:         }
                   2724:     }
1.1320    raeburn  2725:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2726:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2727:         foreach my $prefix (@prefixes) {
                   2728:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2729:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2730:             }
                   2731:         }
                   2732:     }
1.1314    raeburn  2733:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2734:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2735:     }
1.1332    raeburn  2736:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2737:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2738:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2739:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2740:         }
                   2741:     }
1.1219    raeburn  2742:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2743:     return %domdefaults;
                   2744: }
                   2745: 
1.1412    raeburn  2746: sub get_dom_cats {
                   2747:     my ($dom) = @_;
                   2748:     return unless (&domain($dom));
                   2749:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2750:     unless (defined($cached)) {
                   2751:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2752:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2753:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2754:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2755:             } else {
                   2756:                 $cats = {};
                   2757:             }
                   2758:         } else {
                   2759:             $cats = {};
                   2760:         }
                   2761:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2762:     }
1.1413    raeburn  2763:     return $cats;
                   2764: }
                   2765: 
                   2766: sub get_dom_instcats {
                   2767:     my ($dom) = @_;
                   2768:     return unless (&domain($dom));
                   2769:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2770:     unless (defined($cached)) {
                   2771:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2772:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2773:         if ($totcodes > 0) {
                   2774:             my $caller = 'global';
                   2775:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2776:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2777:                 $instcats = {
                   2778:                                 codes => \%codes,
                   2779:                                 codetitles => \@codetitles,
                   2780:                                 cat_titles => \%cat_titles,
                   2781:                                 cat_order => \%cat_order,
                   2782:                             };
                   2783:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2784:             }
                   2785:         }
                   2786:     }
                   2787:     return $instcats;
                   2788: }
                   2789: 
                   2790: sub retrieve_instcodes {
                   2791:     my ($coursecodes,$dom) = @_;
                   2792:     my $totcodes;
                   2793:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2794:     foreach my $course (keys(%courses)) {
                   2795:         if (ref($courses{$course}) eq 'HASH') {
                   2796:             if ($courses{$course}{'inst_code'} ne '') {
                   2797:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2798:                 $totcodes ++;
                   2799:             }
                   2800:         }
                   2801:     }
                   2802:     return $totcodes;
1.1412    raeburn  2803: }
                   2804: 
1.1311    raeburn  2805: sub course_portal_url {
                   2806:     my ($cnum,$cdom) = @_;
                   2807:     my $chome = &homeserver($cnum,$cdom);
                   2808:     my $hostname = &hostname($chome);
                   2809:     my $protocol = $protocol{$chome};
                   2810:     $protocol = 'http' if ($protocol ne 'https');
                   2811:     my %domdefaults = &get_domain_defaults($cdom);
                   2812:     my $firsturl;
                   2813:     if ($domdefaults{'portal_def'}) {
                   2814:         $firsturl = $domdefaults{'portal_def'};
                   2815:     } else {
                   2816:         $firsturl = $protocol.'://'.$hostname;
                   2817:     }
                   2818:     return $firsturl;
                   2819: }
                   2820: 
1.1407    raeburn  2821: # --------------------------------------------- Get domain config for passwords
                   2822: 
                   2823: sub get_passwdconf {
                   2824:     my ($dom) = @_;
                   2825:     my (%passwdconf,$gotconf,$lookup);
                   2826:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2827:     if (defined($cached)) {
                   2828:         if (ref($result) eq 'HASH') {
                   2829:             %passwdconf = %{$result};
                   2830:             $gotconf = 1;
                   2831:         }
                   2832:     }
                   2833:     unless ($gotconf) {
                   2834:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2835:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2836:             %passwdconf = %{$domconfig{'passwords'}};
                   2837:         }
                   2838:         my $cachetime = 24*60*60;
                   2839:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2840:     }
                   2841:     return %passwdconf;
                   2842: }
                   2843: 
1.344     www      2844: # --------------------------------------------------- Assign a key to a student
                   2845: 
                   2846: sub assign_access_key {
1.364     www      2847: #
                   2848: # a valid key looks like uname:udom#comments
                   2849: # comments are being appended
                   2850: #
1.498     www      2851:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2852:     $kdom=
1.620     albertel 2853:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2854:     $knum=
1.620     albertel 2855:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2856:     $cdom=
1.620     albertel 2857:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2858:     $cnum=
1.620     albertel 2859:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2860:     $udom=$env{'user.name'} unless (defined($udom));
                   2861:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2862:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2863:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2864:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2865:                                                   # assigned to this person
                   2866:                                                   # - this should not happen,
1.345     www      2867:                                                   # unless something went wrong
                   2868:                                                   # the first time around
                   2869: # ready to assign
1.364     www      2870:         $logentry=$1.'; '.$logentry;
1.496     www      2871:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2872:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2873: # key now belongs to user
1.346     www      2874: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2875:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2876:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2877:                 return 'ok';
                   2878:             } else {
                   2879:                 return 
                   2880:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2881: 	    }
                   2882:         } else {
                   2883:             return 'error: Could not assign key, try again later.';
                   2884:         }
1.364     www      2885:     } elsif (!$existing{$ckey}) {
1.345     www      2886: # the key does not exist
                   2887: 	return 'error: The key does not exist';
                   2888:     } else {
                   2889: # the key is somebody else's
                   2890: 	return 'error: The key is already in use';
                   2891:     }
1.344     www      2892: }
                   2893: 
1.364     www      2894: # ------------------------------------------ put an additional comment on a key
                   2895: 
                   2896: sub comment_access_key {
                   2897: #
                   2898: # a valid key looks like uname:udom#comments
                   2899: # comments are being appended
                   2900: #
                   2901:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2902:     $cdom=
1.620     albertel 2903:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2904:     $cnum=
1.620     albertel 2905:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2906:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2907:     if ($existing{$ckey}) {
                   2908:         $existing{$ckey}.='; '.$logentry;
                   2909: # ready to assign
1.367     www      2910:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2911:                                                  $cdom,$cnum) eq 'ok') {
                   2912: 	    return 'ok';
                   2913:         } else {
                   2914: 	    return 'error: Count not store comment.';
                   2915:         }
                   2916:     } else {
                   2917: # the key does not exist
                   2918: 	return 'error: The key does not exist';
                   2919:     }
                   2920: }
                   2921: 
1.344     www      2922: # ------------------------------------------------------ Generate a set of keys
                   2923: 
                   2924: sub generate_access_keys {
1.364     www      2925:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2926:     $cdom=
1.620     albertel 2927:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2928:     $cnum=
1.620     albertel 2929:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2930:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2931:     unless (($cdom) && ($cnum)) { return 0; }
                   2932:     if ($number>10000) { return 0; }
                   2933:     sleep(2); # make sure don't get same seed twice
                   2934:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2935:     my $total=0;
                   2936:     for (my $i=1;$i<=$number;$i++) {
                   2937:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2938:                   sprintf("%lx",int(100000*rand)).'-'.
                   2939:                   sprintf("%lx",int(100000*rand));
                   2940:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2941:        $newkey=~s/0/h/g; # and also 0 and O
                   2942:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2943:        if ($existing{$newkey}) {
                   2944:            $i--;
                   2945:        } else {
1.364     www      2946: 	  if (&put('accesskeys',
                   2947:               { $newkey => '# generated '.localtime().
1.620     albertel 2948:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2949:                            '; '.$logentry },
                   2950: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2951:               $total++;
                   2952: 	  }
                   2953:        }
                   2954:     }
1.620     albertel 2955:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2956:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2957:     return $total;
                   2958: }
                   2959: 
                   2960: # ------------------------------------------------------- Validate an accesskey
                   2961: 
                   2962: sub validate_access_key {
                   2963:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2964:     $cdom=
1.620     albertel 2965:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2966:     $cnum=
1.620     albertel 2967:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2968:     $udom=$env{'user.domain'} unless (defined($udom));
                   2969:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2970:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2971:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2972: }
                   2973: 
                   2974: # ------------------------------------- Find the section of student in a course
1.652     albertel 2975: sub devalidate_getsection_cache {
                   2976:     my ($udom,$unam,$courseid)=@_;
                   2977:     my $hashid="$udom:$unam:$courseid";
                   2978:     &devalidate_cache_new('getsection',$hashid);
                   2979: }
1.298     matthew  2980: 
1.815     albertel 2981: sub courseid_to_courseurl {
                   2982:     my ($courseid) = @_;
                   2983:     #already url style courseid
                   2984:     return $courseid if ($courseid =~ m{^/});
                   2985: 
                   2986:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2987: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2988: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2989: 	return "/$cdom/$cnum";
                   2990:     }
                   2991: 
                   2992:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2993:     if (exists($courseinfo{'num'})) {
                   2994: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2995:     }
                   2996: 
                   2997:     return undef;
                   2998: }
                   2999: 
1.298     matthew  3000: sub getsection {
                   3001:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3002:     my $cachetime=1800;
1.551     albertel 3003: 
                   3004:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3005:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3006:     if (defined($cached)) { return $result; }
                   3007: 
1.298     matthew  3008:     my %Pending; 
                   3009:     my %Expired;
                   3010:     #
                   3011:     # Each role can either have not started yet (pending), be active, 
                   3012:     #    or have expired.
                   3013:     #
                   3014:     # If there is an active role, we are done.
                   3015:     #
                   3016:     # If there is more than one role which has not started yet, 
                   3017:     #     choose the one which will start sooner
                   3018:     # If there is one role which has not started yet, return it.
                   3019:     #
                   3020:     # If there is more than one expired role, choose the one which ended last.
                   3021:     # If there is a role which has expired, return it.
                   3022:     #
1.815     albertel 3023:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3024:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3025:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3026:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3027:         my $section=$1;
                   3028:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3029:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3030:         my $now=time;
1.548     albertel 3031:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3032:             $Expired{$end}=$section;
                   3033:             next;
                   3034:         }
1.548     albertel 3035:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3036:             $Pending{$start}=$section;
                   3037:             next;
                   3038:         }
1.599     albertel 3039:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3040:     }
                   3041:     #
                   3042:     # Presumedly there will be few matching roles from the above
                   3043:     # loop and the sorting time will be negligible.
                   3044:     if (scalar(keys(%Pending))) {
                   3045:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3046:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3047:     } 
                   3048:     if (scalar(keys(%Expired))) {
                   3049:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3050:         my $time = pop(@sorted);
1.599     albertel 3051:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3052:     }
1.599     albertel 3053:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3054: }
1.70      www      3055: 
1.599     albertel 3056: sub save_cache {
                   3057:     &purge_remembered();
1.722     albertel 3058:     #&Apache::loncommon::validate_page();
1.620     albertel 3059:     undef(%env);
1.780     albertel 3060:     undef($env_loaded);
1.599     albertel 3061: }
1.452     albertel 3062: 
1.599     albertel 3063: my $to_remember=-1;
                   3064: my %remembered;
                   3065: my %accessed;
                   3066: my $kicks=0;
                   3067: my $hits=0;
1.849     albertel 3068: sub make_key {
                   3069:     my ($name,$id) = @_;
1.872     albertel 3070:     if (length($id) > 65 
                   3071: 	&& length(&escape($id)) > 200) {
                   3072: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3073:     }
1.849     albertel 3074:     return &escape($name.':'.$id);
                   3075: }
                   3076: 
1.599     albertel 3077: sub devalidate_cache_new {
                   3078:     my ($name,$id,$debug) = @_;
                   3079:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3080:     my $remembered_id=$name.':'.$id;
1.849     albertel 3081:     $id=&make_key($name,$id);
1.599     albertel 3082:     $memcache->delete($id);
1.1319    damieng  3083:     delete($remembered{$remembered_id});
                   3084:     delete($accessed{$remembered_id});
1.599     albertel 3085: }
                   3086: 
                   3087: sub is_cached_new {
                   3088:     my ($name,$id,$debug) = @_;
1.1319    damieng  3089:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3090:     if (exists($remembered{$remembered_id})) {
                   3091: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3092: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3093: 	$hits++;
1.1319    damieng  3094: 	return ($remembered{$remembered_id},1);
1.599     albertel 3095:     }
1.1319    damieng  3096:     $id=&make_key($name,$id);
1.599     albertel 3097:     my $value = $memcache->get($id);
                   3098:     if (!(defined($value))) {
                   3099: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3100: 	return (undef,undef);
1.416     albertel 3101:     }
1.599     albertel 3102:     if ($value eq '__undef__') {
                   3103: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3104: 	$value=undef;
                   3105:     }
1.1319    damieng  3106:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3107:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3108:     return ($value,1);
                   3109: }
                   3110: 
                   3111: sub do_cache_new {
                   3112:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3113:     my $remembered_id=$name.':'.$id;
1.849     albertel 3114:     $id=&make_key($name,$id);
1.599     albertel 3115:     my $setvalue=$value;
                   3116:     if (!defined($setvalue)) {
                   3117: 	$setvalue='__undef__';
                   3118:     }
1.623     albertel 3119:     if (!defined($time) ) {
                   3120: 	$time=600;
                   3121:     }
1.599     albertel 3122:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3123:     my $result = $memcache->set($id,$setvalue,$time);
                   3124:     if (! $result) {
1.872     albertel 3125: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3126: 	$memcache->disconnect_all();
1.872     albertel 3127:     }
1.600     albertel 3128:     # need to make a copy of $value
1.1319    damieng  3129:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3130:     return $value;
                   3131: }
                   3132: 
                   3133: sub make_room {
1.1319    damieng  3134:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3135: 
1.1319    damieng  3136:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3137:                                     : $value;
1.599     albertel 3138:     if ($to_remember<0) { return; }
1.1319    damieng  3139:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3140:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3141:     my $to_kick;
                   3142:     my $max_time=0;
                   3143:     foreach my $other (keys(%accessed)) {
                   3144: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3145: 	    $to_kick=$other;
                   3146: 	    $max_time=&tv_interval($accessed{$other});
                   3147: 	}
                   3148:     }
                   3149:     delete($remembered{$to_kick});
                   3150:     delete($accessed{$to_kick});
                   3151:     $kicks++;
                   3152:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3153:     return;
                   3154: }
                   3155: 
1.599     albertel 3156: sub purge_remembered {
1.604     albertel 3157:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3158:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3159:     undef(%remembered);
                   3160:     undef(%accessed);
1.428     albertel 3161: }
1.70      www      3162: # ------------------------------------- Read an entry from a user's environment
                   3163: 
                   3164: sub userenvironment {
                   3165:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3166:     my $items;
                   3167:     foreach my $item (@what) {
                   3168:         $items.=&escape($item).'&';
                   3169:     }
                   3170:     $items=~s/\&$//;
1.70      www      3171:     my %returnhash=();
1.1009    raeburn  3172:     my $uhome = &homeserver($unam,$udom);
                   3173:     unless ($uhome eq 'no_host') {
                   3174:         my @answer=split(/\&/, 
                   3175:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3176:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3177:             return %returnhash;
                   3178:         }
1.1009    raeburn  3179:         my $i;
                   3180:         for ($i=0;$i<=$#what;$i++) {
                   3181: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3182:         }
1.70      www      3183:     }
                   3184:     return %returnhash;
1.1       albertel 3185: }
                   3186: 
1.617     albertel 3187: # ---------------------------------------------------------- Get a studentphoto
                   3188: sub studentphoto {
                   3189:     my ($udom,$unam,$ext) = @_;
                   3190:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3191:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3192:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3193:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3194:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3195:             } else {
                   3196:                 my ($result,$perm_reqd)=
1.707     albertel 3197: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3198:                 if ($result eq 'ok') {
                   3199:                     if (!($perm_reqd eq 'yes')) {
                   3200:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3201:                     }
                   3202:                 }
                   3203:             }
                   3204:         }
                   3205:     } else {
                   3206:         my ($result,$perm_reqd) = 
1.707     albertel 3207: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3208:         if ($result eq 'ok') {
                   3209:             if (!($perm_reqd eq 'yes')) {
                   3210:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3211:             }
                   3212:         }
                   3213:     }
                   3214:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3215: }
                   3216: 
                   3217: sub retrievestudentphoto {
                   3218:     my ($udom,$unam,$ext,$type) = @_;
                   3219:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3220:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3221:     if ($ret eq 'ok') {
                   3222:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3223:         if ($type eq 'thumbnail') {
                   3224:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3225:         }
                   3226:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3227:         return $tokenurl;
                   3228:     } else {
                   3229:         if ($type eq 'thumbnail') {
                   3230:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3231:         } else { 
                   3232:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3233:         }
1.617     albertel 3234:     }
                   3235: }
                   3236: 
1.263     www      3237: # -------------------------------------------------------------------- New chat
                   3238: 
                   3239: sub chatsend {
1.724     raeburn  3240:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3241:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3242:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3243:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3244:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3245: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3246: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3247: }
                   3248: 
                   3249: # ------------------------------------------ Find current version of a resource
                   3250: 
                   3251: sub getversion {
                   3252:     my $fname=&clutter(shift);
1.1189    raeburn  3253:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3254:     return &currentversion(&filelocation('',$fname));
                   3255: }
                   3256: 
                   3257: sub currentversion {
                   3258:     my $fname=shift;
                   3259:     my $author=$fname;
                   3260:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3261:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3262:     my $home=&homeserver($uname,$udom);
1.292     www      3263:     if ($home eq 'no_host') { 
                   3264:         return -1; 
                   3265:     }
1.1112    www      3266:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3267:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3268: 	return -1;
                   3269:     }
1.1112    www      3270:     return $answer;
1.263     www      3271: }
                   3272: 
1.1111    www      3273: #
                   3274: # Return special version number of resource if set by override, empty otherwise
                   3275: #
                   3276: sub usedversion {
                   3277:     my $fname=shift;
                   3278:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3279:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3280:     if ($urlversion) { return $urlversion; }
                   3281:     return '';
                   3282: }
                   3283: 
1.1       albertel 3284: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3285: 
1.1       albertel 3286: sub subscribe {
                   3287:     my $fname=shift;
1.761     raeburn  3288:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3289:     $fname=~s/[\n\r]//g;
1.1       albertel 3290:     my $author=$fname;
                   3291:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3292:     my ($udom,$uname)=split(/\//,$author);
                   3293:     my $home=homeserver($uname,$udom);
1.335     albertel 3294:     if ($home eq 'no_host') {
                   3295:         return 'not_found';
1.1       albertel 3296:     }
                   3297:     my $answer=reply("sub:$fname",$home);
1.64      www      3298:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3299: 	$answer.=' by '.$home;
                   3300:     }
1.1       albertel 3301:     return $answer;
                   3302: }
                   3303:     
1.8       www      3304: # -------------------------------------------------------------- Replicate file
                   3305: 
                   3306: sub repcopy {
                   3307:     my $filename=shift;
1.23      www      3308:     $filename=~s/\/+/\//g;
1.1142    raeburn  3309:     my $londocroot = $perlvar{'lonDocRoot'};
                   3310:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3311:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3312:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3313: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3314: 	return &repcopy_userfile($filename);
                   3315:     }
1.532     albertel 3316:     $filename=~s/[\n\r]//g;
1.8       www      3317:     my $transname="$filename.in.transfer";
1.828     www      3318: # FIXME: this should flock
1.607     raeburn  3319:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3320:     my $remoteurl=subscribe($filename);
1.64      www      3321:     if ($remoteurl =~ /^con_lost by/) {
                   3322: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3323:            return 'unavailable';
1.8       www      3324:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3325: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3326: 	   return 'not_found';
1.64      www      3327:     } elsif ($remoteurl =~ /^rejected by/) {
                   3328: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3329:            return 'forbidden';
1.20      www      3330:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3331:            return 'ok';
1.8       www      3332:     } else {
1.290     www      3333:         my $author=$filename;
                   3334:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3335:         my ($udom,$uname)=split(/\//,$author);
                   3336:         my $home=homeserver($uname,$udom);
                   3337:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3338:            my @parts=split(/\//,$filename);
                   3339:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3340:            if ($path ne "$londocroot/res") {
1.8       www      3341:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3342: 	       return 'bad_request';
1.8       www      3343:            }
                   3344:            my $count;
                   3345:            for ($count=5;$count<$#parts;$count++) {
                   3346:                $path.="/$parts[$count]";
                   3347:                if ((-e $path)!=1) {
                   3348: 		   mkdir($path,0777);
                   3349:                }
                   3350:            }
                   3351:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3352:            my $response;
                   3353:            if ($remoteurl =~ m{/raw/}) {
                   3354:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3355:            } else {
                   3356:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3357:            }
1.8       www      3358:            if ($response->is_error()) {
                   3359: 	       unlink($transname);
                   3360:                my $message=$response->status_line;
1.672     albertel 3361:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3362:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3363:                return 'unavailable';
1.8       www      3364:            } else {
1.16      www      3365: 	       if ($remoteurl!~/\.meta$/) {
                   3366:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3367:                   my $mresponse;
                   3368:                   if ($remoteurl =~ m{/raw/}) {
                   3369:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3370:                   } else {
                   3371:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3372:                   }
1.16      www      3373:                   if ($mresponse->is_error()) {
                   3374: 		      unlink($filename.'.meta');
                   3375:                       &logthis(
1.672     albertel 3376:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3377:                   }
                   3378: 	       }
1.8       www      3379:                rename($transname,$filename);
1.607     raeburn  3380:                return 'ok';
1.8       www      3381:            }
1.290     www      3382:        }
1.8       www      3383:     }
1.330     www      3384: }
                   3385: 
                   3386: # ------------------------------------------------ Get server side include body
                   3387: sub ssi_body {
1.381     albertel 3388:     my ($filelink,%form)=@_;
1.606     matthew  3389:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3390:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3391:     }
1.953     www      3392:     my $output='';
                   3393:     my $response;
1.980     raeburn  3394:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3395:        ($output,$response)=&externalssi($filelink);
1.953     www      3396:     } else {
1.1004    droeschl 3397:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3398:        $filelink .= 'inhibitmenu=yes';
1.953     www      3399:        ($output,$response)=&ssi($filelink,%form);
                   3400:     }
1.778     albertel 3401:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3402:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3403:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3404:     if (wantarray) {
                   3405:         return ($output, $response);
                   3406:     } else {
                   3407:         return $output;
                   3408:     }
1.8       www      3409: }
                   3410: 
1.15      www      3411: # --------------------------------------------------------- Server Side Include
                   3412: 
1.782     albertel 3413: sub absolute_url {
                   3414:     my ($host_name) = @_;
                   3415:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3416:     if ($host_name eq '') {
                   3417: 	$host_name = $ENV{'SERVER_NAME'};
                   3418:     }
                   3419:     return $protocol.$host_name;
                   3420: }
                   3421: 
1.942     foxr     3422: #
                   3423: #   Server side include.
                   3424: # Parameters:
                   3425: #  fn     Possibly encrypted resource name/id.
                   3426: #  form   Hash that describes how the rendering should be done
                   3427: #         and other things.
1.944     foxr     3428: # Returns:
1.950     raeburn  3429: #   Scalar context: The content of the response.
                   3430: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3431: #     
1.15      www      3432: sub ssi {
                   3433: 
1.944     foxr     3434:     my ($fn,%form)=@_;
1.23      www      3435:     my $request;
1.711     albertel 3436: 
                   3437:     $form{'no_update_last_known'}=1;
1.895     albertel 3438:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3439:     if (%form) {
1.782     albertel 3440:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3441:       $request->content(join('&',map { 
                   3442:             my $name = escape($_);
                   3443:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3444:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3445:             : &escape($form{$_}) );    
                   3446:         } keys(%form)));
1.23      www      3447:     } else {
1.782     albertel 3448:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3449:     }
                   3450: 
1.15      www      3451:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3452:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3453:     my $islocal;
                   3454:     if (($env{'request.course.id'}) &&
                   3455:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3456:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3457:         ($form{'grade_symb'} ne '') &&
                   3458:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3459:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3460:         $islocal = 1;
                   3461:     }
1.1384    raeburn  3462:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3463:                                                 '','','',$islocal);
1.1182    foxr     3464: 
1.944     foxr     3465:     if (wantarray) {
1.1345    raeburn  3466: 	return ($response->content, $response);
1.944     foxr     3467:     } else {
1.1345    raeburn  3468: 	return $response->content;
1.942     foxr     3469:     }
1.324     www      3470: }
                   3471: 
                   3472: sub externalssi {
                   3473:     my ($url)=@_;
                   3474:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3475:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3476:     if (wantarray) {
                   3477:         return ($response->content, $response);
                   3478:     } else {
                   3479:         return $response->content;
                   3480:     }
1.15      www      3481: }
1.254     www      3482: 
1.1354    raeburn  3483: 
                   3484: # If the local copy of a replicated resource is outdated, trigger a  
                   3485: # connection from the homeserver to flush the delayed queue. If no update 
                   3486: # happens, remove local copies of outdated resource (and corresponding
                   3487: # metadata file).
                   3488: 
1.1352    raeburn  3489: sub remove_stale_resfile {
                   3490:     my ($url) = @_;
1.1354    raeburn  3491:     my $removed;
1.1352    raeburn  3492:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3493:         my $audom = $1;
                   3494:         my $auname = $2;
1.1353    raeburn  3495:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3496:             my $homeserver = &homeserver($auname,$audom);
                   3497:             unless (($homeserver eq 'no_host') ||
                   3498:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3499:                 my $fname = &filelocation('',$url);
                   3500:                 if (-e $fname) {
                   3501:                     my $hostname = &hostname($homeserver);
                   3502:                     if ($hostname) {
1.1397    raeburn  3503:                         my $protocol = $protocol{$homeserver};
                   3504:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3505:                         my $uri = &declutter($url);
                   3506:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3507:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3508:                         if ($response->is_success()) {
                   3509:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3510:                             my $locmodtime = (stat($fname))[9];
                   3511:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3512:                                 my $stale;
                   3513:                                 my $answer = &reply('pong',$homeserver);
                   3514:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3515:                                     sleep(0.2);
                   3516:                                     $locmodtime = (stat($fname))[9];
                   3517:                                     if ($locmodtime < $remmodtime) {
                   3518:                                         my $posstransfer = $fname.'.in.transfer';
                   3519:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3520:                                             $removed = 1;
                   3521:                                         } else {
                   3522:                                             $stale = 1;
                   3523:                                         }
                   3524:                                     } else {
                   3525:                                         $removed = 1;
                   3526:                                     }
                   3527:                                 } else {
                   3528:                                     $stale = 1;
                   3529:                                 }
                   3530:                                 if ($stale) {
1.1421  ! raeburn  3531:                                     if (unlink($fname)) {
        !          3532:                                         if ($uri!~/\.meta$/) {
        !          3533:                                             if (-e $fname.'.meta') {
        !          3534:                                                 unlink($fname.'.meta');
        !          3535:                                             }
        !          3536:                                         }
        !          3537:                                         &reply("unsub:$fname",$homeserver);
        !          3538:                                         $removed = 1;
1.1354    raeburn  3539:                                     }
1.1352    raeburn  3540:                                 }
                   3541:                             }
                   3542:                         }
                   3543:                     }
                   3544:                 }
                   3545:             }
                   3546:         }
                   3547:     }
1.1354    raeburn  3548:     return $removed;
1.1352    raeburn  3549: }
                   3550: 
1.492     albertel 3551: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3552: 
                   3553: sub allowuploaded {
                   3554:     my ($srcurl,$url)=@_;
                   3555:     $url=&clutter(&declutter($url));
                   3556:     my $dir=$url;
                   3557:     $dir=~s/\/[^\/]+$//;
                   3558:     my %httpref=();
                   3559:     my $httpurl=&hreflocation('',$url);
                   3560:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3561:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3562: }
1.477     raeburn  3563: 
1.1193    raeburn  3564: #
                   3565: # Determine if the current user should be able to edit a particular resource,
                   3566: # when viewing in course context.
                   3567: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3568: #     Functions.
                   3569: # (b) When displaying folder contents in course editor, used to determine if
                   3570: #     "Edit" link will be displayed alongside resource.
                   3571: #
1.1196    raeburn  3572: #  input: six args -- filename (decluttered), course number, course domain,
                   3573: #                   url, symb (if registered) and group (if this is a group
                   3574: #                   item -- e.g., bulletin board, group page etc.).
                   3575: #  output: array of five scalars -- 
1.1193    raeburn  3576: #          $cfile -- url for file editing if editable on current server
                   3577: #          $home -- homeserver of resource (i.e., for author if published,
                   3578: #                                           or course if uploaded.).
                   3579: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3580: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3581: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3582: #
                   3583: 
                   3584: sub can_edit_resource {
1.1194    raeburn  3585:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3586:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3587: #
                   3588: # For aboutme pages user can only edit his/her own.
                   3589: #
1.1199    raeburn  3590:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3591:         my ($sdom,$sname) = ($1,$2);
                   3592:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3593:             $home = $env{'user.home'};
                   3594:             $cfile = $resurl;
                   3595:             if ($env{'form.forceedit'}) {
                   3596:                 $forceview = 1;
                   3597:             } else {
                   3598:                 $forceedit = 1;
                   3599:             }
                   3600:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3601:         } else {
                   3602:             return;
                   3603:         }
                   3604:     }
                   3605: 
                   3606:     if ($env{'request.course.id'}) {
                   3607:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3608:         if ($group ne '') {
                   3609: # if this is a group homepage or group bulletin board, check group privs
                   3610:             my $allowed = 0;
1.1197    raeburn  3611:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3612:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3613:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3614:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3615:                     $allowed = 1;
                   3616:                 }
1.1197    raeburn  3617:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3618:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3619:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3620:                     $allowed = 1;
                   3621:                 }
                   3622:             }
                   3623:             if ($allowed) {
                   3624:                 $home=&homeserver($cnum,$cdom);
                   3625:                 if ($env{'form.forceedit'}) {
                   3626:                     $forceview = 1;
                   3627:                 } else {
                   3628:                     $forceedit = 1;
                   3629:                 }
                   3630:                 $cfile = $resurl;
                   3631:             } else {
                   3632:                 return;
                   3633:             }
                   3634:         } else {
1.1208    raeburn  3635:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3636:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3637:                     return;
                   3638:                 }
                   3639:             } elsif (!$crsedit) {
1.1194    raeburn  3640: #
                   3641: # No edit allowed where CC has switched to student role.
                   3642: #
                   3643:                 return;
                   3644:             }
                   3645:         }
                   3646:     }
                   3647: 
1.1193    raeburn  3648:     if ($file ne '') {
                   3649:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3650:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3651:                 $uploaded = 1;
                   3652:                 $incourse = 1;
1.1193    raeburn  3653:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3654:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3655:                     if ($env{'form.forceedit'}) {
                   3656:                         $forceview = 1;
                   3657:                     } else {
                   3658:                         $forceedit = 1;
                   3659:                     }
1.1194    raeburn  3660:                 }
                   3661:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3662:                 $incourse = 1;
                   3663:                 if ($env{'form.forceedit'}) {
                   3664:                     $forceview = 1;
                   3665:                 } else {
                   3666:                     $forceedit = 1;
                   3667:                 }
                   3668:                 $cfile = $resurl;
                   3669:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3670:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3671:                     $incourse = 1;
                   3672:                     if ($env{'form.forceedit'}) {
                   3673:                         $forceview = 1;
                   3674:                     } else {
                   3675:                         $forceedit = 1;
                   3676:                     }
                   3677:                     $cfile = $resurl;
1.1199    raeburn  3678:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3679:                     $incourse = 1;
                   3680:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3681:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3682:                     $incourse = 1;
1.1199    raeburn  3683:                     if ($env{'form.forceedit'}) {
                   3684:                         $forceview = 1;
                   3685:                     } else {
                   3686:                         $forceedit = 1;
                   3687:                     }
                   3688:                     $cfile = $resurl;
1.1419    raeburn  3689:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3690:                     my ($map,$id,$res) = &decode_symb($symb);
                   3691:                     if ($map =~ /\.page$/) {
                   3692:                         $incourse = 1;
                   3693:                         if ($env{'form.forceedit'}) {
                   3694:                             $forceview = 1;
                   3695:                             $cfile = $map;
                   3696:                         } else {
                   3697:                             $forceedit = 1;
                   3698:                             $cfile =  '/adm/wrapper'.$resurl;
                   3699:                         }
                   3700:                     }
1.1343    raeburn  3701:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3702:                     $incourse = 1;
                   3703:                     if ($env{'form.forceedit'}) {
                   3704:                         $forceview = 1;
                   3705:                     } else {
                   3706:                         $forceedit = 1;
                   3707:                     }
                   3708:                     $cfile = $resurl;
1.1208    raeburn  3709:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3710:                     $incourse = 1;
                   3711:                     if ($env{'form.forceedit'}) {
                   3712:                         $forceview = 1;
                   3713:                     } else {
                   3714:                         $forceedit = 1;
                   3715:                     }
                   3716:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3717:                 }
                   3718:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3719:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3720:                 if (&is_on_map($template)) { 
                   3721:                     $incourse = 1;
                   3722:                     $forceview = 1;
                   3723:                     $cfile = $template;
1.1193    raeburn  3724:                 }
1.1199    raeburn  3725:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  3726:                 $incourse = 1;
                   3727:                 if ($env{'form.forceedit'}) {
                   3728:                     $forceview = 1;
                   3729:                 } else {
                   3730:                     $forceedit = 1;
                   3731:                 }
                   3732:                 $cfile = $resurl;
1.1343    raeburn  3733:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3734:                 $incourse = 1;
                   3735:                 if ($env{'form.forceedit'}) {
                   3736:                     $forceview = 1;
                   3737:                 } else {
                   3738:                     $forceedit = 1;
                   3739:                 }
                   3740:                 $cfile = $resurl;
1.1199    raeburn  3741:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3742:                 $incourse = 1;
                   3743:                 $forceview = 1;
                   3744:                 if ($symb) {
                   3745:                     my ($map,$id,$res)=&decode_symb($symb);
                   3746:                     $env{'request.symb'} = $symb;
                   3747:                     $cfile = &clutter($res);
                   3748:                 } else {
                   3749:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3750:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3751:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3752:                         $cfile = '/adm/wrapper'.$escfile;
                   3753:                     } else {
                   3754:                         $escfile =~ s{^http://}{};
                   3755:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3756:                     }
1.1199    raeburn  3757:                 }
1.1234    raeburn  3758:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3759:                 if ($env{'form.forceedit'}) {
                   3760:                     $forceview = 1;
                   3761:                 } else {
                   3762:                     $forceedit = 1;
                   3763:                 }
                   3764:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3765:             }
                   3766:         }
1.1194    raeburn  3767:         if ($uploaded || $incourse) {
                   3768:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3769:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3770:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3771:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3772:             # Check that the user has permission to edit this resource
                   3773:             my $setpriv = 1;
                   3774:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3775:             if (defined($cfudom)) {
                   3776:                 $home=&homeserver($cfuname,$cfudom);
                   3777:                 $cfile=$file;
                   3778:             }
                   3779:         }
1.1194    raeburn  3780:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3781:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3782:             my @ids=&current_machine_ids();
                   3783:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3784:                 $switchserver=1;
                   3785:             }
                   3786:         }
                   3787:     }
1.1194    raeburn  3788:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3789: }
                   3790: 
                   3791: sub is_course_upload {
                   3792:     my ($file,$cnum,$cdom) = @_;
                   3793:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3794:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3795:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3796:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3797:         return 1;
                   3798:     }
                   3799:     return;
                   3800: }
                   3801: 
1.1194    raeburn  3802: sub in_course {
1.1195    raeburn  3803:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3804:     if ($hideprivileged) {
                   3805:         my $skipuser;
1.1219    raeburn  3806:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3807:         my @possdoms = ($cdom);  
                   3808:         if ($coursehash{'checkforpriv'}) { 
                   3809:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3810:         }
                   3811:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3812:             $skipuser = 1;
                   3813:             if ($coursehash{'nothideprivileged'}) {
                   3814:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3815:                     my $user;
                   3816:                     if ($item =~ /:/) {
                   3817:                         $user = $item;
                   3818:                     } else {
                   3819:                         $user = join(':',split(/[\@]/,$item));
                   3820:                     }
                   3821:                     if ($user eq $uname.':'.$udom) {
                   3822:                         undef($skipuser);
                   3823:                         last;
                   3824:                     }
                   3825:                 }
                   3826:             }
                   3827:             if ($skipuser) {
                   3828:                 return 0;
                   3829:             }
                   3830:         }
                   3831:     }
1.1194    raeburn  3832:     $type ||= 'any';
                   3833:     if (!defined($cdom) || !defined($cnum)) {
                   3834:         my $cid  = $env{'request.course.id'};
                   3835:         $cdom = $env{'course.'.$cid.'.domain'};
                   3836:         $cnum = $env{'course.'.$cid.'.num'};
                   3837:     }
                   3838:     my $typesref;
1.1195    raeburn  3839:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3840:         $typesref = ['active','previous','future'];
                   3841:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3842:         $typesref = [$type];
                   3843:     }
                   3844:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3845:                               $typesref,undef,[$cdom]);
                   3846:     my ($tmp) = keys(%roles);
                   3847:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3848:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3849:     if (@course_roles > 0) {
                   3850:         return 1;
                   3851:     }
                   3852:     return 0;
                   3853: }
                   3854: 
1.478     albertel 3855: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3856: # input: action, courseID, current domain, intended
1.637     raeburn  3857: #        path to file, source of file, instruction to parse file for objects,
                   3858: #        ref to hash for embedded objects,
                   3859: #        ref to hash for codebase of java objects.
1.1095    raeburn  3860: #        reference to scalar to accommodate mime type determined
                   3861: #          from File::MMagic if $parser = parse.
1.637     raeburn  3862: #
1.485     raeburn  3863: # output: url to file (if action was uploaddoc), 
                   3864: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3865: #
1.478     albertel 3866: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3867: # course.
1.477     raeburn  3868: #
1.478     albertel 3869: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3870: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3871: #          course's home server.
1.477     raeburn  3872: #
1.478     albertel 3873: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3874: #          be copied from $source (current location) to 
                   3875: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3876: #         and will then be copied to
                   3877: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3878: #         course's home server.
1.485     raeburn  3879: #
1.481     raeburn  3880: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3881: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3882: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3883: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3884: #         in course's home server.
1.637     raeburn  3885: #
1.477     raeburn  3886: 
                   3887: sub process_coursefile {
1.1095    raeburn  3888:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3889:         $mimetype)=@_;
1.477     raeburn  3890:     my $fetchresult;
1.638     albertel 3891:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3892:     if ($action eq 'propagate') {
1.638     albertel 3893:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3894: 			     $home);
1.481     raeburn  3895:     } else {
1.477     raeburn  3896:         my $fpath = '';
                   3897:         my $fname = $file;
1.478     albertel 3898:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3899:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3900:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3901:         if ($action eq 'copy') {
                   3902:             if ($source eq '') {
                   3903:                 $fetchresult = 'no source file';
                   3904:                 return $fetchresult;
                   3905:             } else {
                   3906:                 my $destination = $filepath.'/'.$fname;
                   3907:                 rename($source,$destination);
                   3908:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3909:                                  $home);
1.481     raeburn  3910:             }
                   3911:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3912:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3913:             print $fh $env{'form.'.$source};
1.481     raeburn  3914:             close($fh);
1.637     raeburn  3915:             if ($parser eq 'parse') {
1.1024    raeburn  3916:                 my $mm = new File::MMagic;
1.1095    raeburn  3917:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3918:                 if ($type eq 'text/html') {
1.1024    raeburn  3919:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3920:                     unless ($parse_result eq 'ok') {
                   3921:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3922:                     }
1.637     raeburn  3923:                 }
1.1095    raeburn  3924:                 if (ref($mimetype)) {
                   3925:                     $$mimetype = $type;
                   3926:                 } 
1.637     raeburn  3927:             }
1.477     raeburn  3928:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3929:                                  $home);
1.481     raeburn  3930:             if ($fetchresult eq 'ok') {
                   3931:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3932:             } else {
                   3933:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3934:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3935:                 return '/adm/notfound.html';
                   3936:             }
1.477     raeburn  3937:         }
                   3938:     }
1.485     raeburn  3939:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3940:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3941:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3942:     }
                   3943:     return $fetchresult;
                   3944: }
                   3945: 
1.637     raeburn  3946: sub build_filepath {
                   3947:     my ($fpath) = @_;
                   3948:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3949:     unless ($fpath eq '') {
                   3950:         my @parts=split('/',$fpath);
                   3951:         foreach my $part (@parts) {
                   3952:             $filepath.= '/'.$part;
                   3953:             if ((-e $filepath)!=1) {
                   3954:                 mkdir($filepath,0777);
                   3955:             }
                   3956:         }
                   3957:     }
                   3958:     return $filepath;
                   3959: }
                   3960: 
                   3961: sub store_edited_file {
1.638     albertel 3962:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3963:     my $file = $primary_url;
                   3964:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3965:     my $fpath = '';
                   3966:     my $fname = $file;
                   3967:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3968:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3969:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3970:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3971:     print $fh $content;
                   3972:     close($fh);
1.638     albertel 3973:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3974:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3975: 			  $home);
1.637     raeburn  3976:     if ($$fetchresult eq 'ok') {
                   3977:         return '/uploaded/'.$fpath.'/'.$fname;
                   3978:     } else {
1.638     albertel 3979:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3980: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3981:         return '/adm/notfound.html';
                   3982:     }
                   3983: }
                   3984: 
1.531     albertel 3985: sub clean_filename {
1.831     albertel 3986:     my ($fname,$args)=@_;
1.315     www      3987: # Replace Windows backslashes by forward slashes
1.257     www      3988:     $fname=~s/\\/\//g;
1.831     albertel 3989:     if (!$args->{'keep_path'}) {
                   3990:         # Get rid of everything but the actual filename
                   3991: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3992:     }
1.315     www      3993: # Replace spaces by underscores
                   3994:     $fname=~s/\s+/\_/g;
1.1406    raeburn  3995: # Transliterate non-ascii text to ascii
                   3996:     my $lang = &Apache::lonlocal::current_language();
                   3997:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3998: # Replace all other weird characters by nothing
1.831     albertel 3999:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4000: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4001: # numbers
                   4002:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 4003:     return $fname;
                   4004: }
1.1406    raeburn  4005: 
1.1051    raeburn  4006: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4007: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4008: # image with the same aspect ratio as the original, but with dimensions which do 
                   4009: # not exceed $resizewidth and $resizeheight.
                   4010:  
1.984     neumanie 4011: sub resizeImage {
1.1051    raeburn  4012:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4013:     my $ima = Image::Magick->new;
                   4014:     my $resized;
                   4015:     if (-e $img_path) {
                   4016:         $ima->Read($img_path);
                   4017:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4018:             my $width = $ima->Get('width');
                   4019:             my $height = $ima->Get('height');
                   4020:             if ($width > $resizewidth) {
                   4021: 	        my $factor = $width/$resizewidth;
                   4022:                 my $newheight = $height/$factor;
                   4023:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4024:                 $resized = 1;
                   4025:             }
                   4026:         }
                   4027:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4028:             my $width = $ima->Get('width');
                   4029:             my $height = $ima->Get('height');
                   4030:             if ($height > $resizeheight) {
                   4031:                 my $factor = $height/$resizeheight;
                   4032:                 my $newwidth = $width/$factor;
                   4033:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4034:                 $resized = 1;
                   4035:             }
                   4036:         }
                   4037:         if ($resized) {
                   4038:             $ima->Write($img_path);
                   4039:         }
                   4040:     }
                   4041:     return;
1.977     amueller 4042: }
                   4043: 
1.608     albertel 4044: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4045: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4046: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4047: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4048: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4049: #                   if 'coursedoc': upload to the current course
                   4050: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4051: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4052: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4053: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4054: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4055: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4056: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4057: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4058: #        $allfiles - reference to hash for embedded objects
                   4059: #        $codebase - reference to hash for codebase of java objects
                   4060: #        $desuname - username for permanent storage of uploaded file
                   4061: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4062: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4063: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4064: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4065: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4066: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4067: #                    from File::MMagic.
1.858     raeburn  4068: # 
1.686     albertel 4069: # output: url of file in userspace, or error: <message> 
                   4070: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4071: 
1.531     albertel 4072: sub userfileupload {
1.1090    raeburn  4073:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4074:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4075:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4076:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4077:     $fname=&clean_filename($fname);
1.1090    raeburn  4078:     # See if there is anything left
1.257     www      4079:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4080:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4081:     if ($fname =~ /^\./) {
                   4082:         my ($s,$usec) = &gettimeofday();
                   4083:         while (length($usec) < 6) {
                   4084:             $usec = '0'.$usec;
                   4085:         }
                   4086:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4087:     }
1.1090    raeburn  4088:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4089:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4090:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4091:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4092:         my $now = time;
1.1090    raeburn  4093:         my $filepath;
1.1095    raeburn  4094:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4095:              $filepath = 'tmp/helprequests/'.$now;
                   4096:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4097:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4098:                          '_'.$env{'user.domain'}.'/pending';
                   4099:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4100:             my ($docuname,$docudom);
1.1350    raeburn  4101:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4102:                 $docudom = $destudom;
                   4103:             } else {
                   4104:                 $docudom = $env{'user.domain'};
                   4105:             }
1.1350    raeburn  4106:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4107:                 $docuname = $destuname;
                   4108:             } else {
                   4109:                 $docuname = $env{'user.name'};
                   4110:             }
                   4111:             if (exists($env{'form.group'})) {
                   4112:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4113:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4114:             }
                   4115:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4116:             if ($context eq 'canceloverwrite') {
                   4117:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4118:                 if (-e  $tempfile) {
                   4119:                     my @info = stat($tempfile);
                   4120:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4121:                         unlink($tempfile);
                   4122:                     }
                   4123:                 }
                   4124:                 return;
1.523     raeburn  4125:             }
                   4126:         }
1.1090    raeburn  4127:         # Create the directory if not present
1.741     raeburn  4128:         my @parts=split(/\//,$filepath);
                   4129:         my $fullpath = $perlvar{'lonDaemons'};
                   4130:         for (my $i=0;$i<@parts;$i++) {
                   4131:             $fullpath .= '/'.$parts[$i];
                   4132:             if ((-e $fullpath)!=1) {
                   4133:                 mkdir($fullpath,0777);
                   4134:             }
                   4135:         }
1.1359    raeburn  4136:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4137:         print $fh $env{'form.'.$formname};
                   4138:         close($fh);
1.1090    raeburn  4139:         if ($context eq 'existingfile') {
                   4140:             my @info = stat($fullpath.'/'.$fname);
                   4141:             return ($fullpath.'/'.$fname,$info[9]);
                   4142:         } else {
                   4143:             return $fullpath.'/'.$fname;
                   4144:         }
1.523     raeburn  4145:     }
1.995     raeburn  4146:     if ($subdir eq 'scantron') {
                   4147:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4148:     } else {
1.995     raeburn  4149:         $fname="$subdir/$fname";
                   4150:     }
1.1090    raeburn  4151:     if ($context eq 'coursedoc') {
1.638     albertel 4152: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4153: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4154:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4155:             return &finishuserfileupload($docuname,$docudom,
                   4156: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4157: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4158:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4159:         } else {
1.1218    raeburn  4160:             if ($env{'form.folder'}) {
                   4161:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4162:             }
1.638     albertel 4163:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4164: 				       $fname,$formname,$parser,
1.1095    raeburn  4165: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4166:         }
1.719     banghart 4167:     } elsif (defined($destuname)) {
                   4168:         my $docuname=$destuname;
                   4169:         my $docudom=$destudom;
1.860     raeburn  4170: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4171: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4172:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4173:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4174:     } else {
1.638     albertel 4175:         my $docuname=$env{'user.name'};
                   4176:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4177:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4178:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4179:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4180:         }
1.860     raeburn  4181: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4182: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4183:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4184:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4185:     }
1.271     www      4186: }
                   4187: 
                   4188: sub finishuserfileupload {
1.860     raeburn  4189:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4190:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4191:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4192:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4193:   
1.860     raeburn  4194:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4195:     $file=$fname;
                   4196:     if ($fname=~m|/|) {
                   4197:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4198: 	$path.=$fnamepath.'/';
                   4199:     }
1.259     www      4200:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4201:     my $count;
                   4202:     for ($count=4;$count<=$#parts;$count++) {
                   4203:         $filepath.="/$parts[$count]";
                   4204:         if ((-e $filepath)!=1) {
                   4205: 	    mkdir($filepath,0777);
                   4206:         }
                   4207:     }
1.984     neumanie 4208: 
1.258     www      4209: # Save the file
                   4210:     {
1.1359    raeburn  4211: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4212: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4213: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4214: 	    return '/adm/notfound.html';
                   4215: 	}
1.1090    raeburn  4216:         if ($context eq 'overwrite') {
1.1117    foxr     4217:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4218:             my $target = $filepath.'/'.$file;
                   4219:             if (-e $source) {
                   4220:                 my @info = stat($source);
                   4221:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4222:                     unless (&File::Copy::move($source,$target)) {
                   4223:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4224:                         return "Moving from $source failed";
                   4225:                     }
                   4226:                 } else {
                   4227:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4228:                 }
                   4229:             } else {
                   4230:                 return "Temporary file: $source missing";
                   4231:             }
                   4232:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4233: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4234: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4235: 	    return '/adm/notfound.html';
                   4236: 	}
1.570     albertel 4237: 	close(FH);
1.1051    raeburn  4238:         if ($resizewidth && $resizeheight) {
                   4239:             my $mm = new File::MMagic;
                   4240:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4241:             if ($mime_type =~ m{^image/}) {
                   4242: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4243:             }  
1.977     amueller 4244: 	}
1.258     www      4245:     }
1.1152    raeburn  4246:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4247:         if (ref($mimetype)) {
                   4248:             if ($$mimetype eq '') {
                   4249:                 my $mm = new File::MMagic;
                   4250:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4251:                 $$mimetype = $type;
                   4252:             }
                   4253:         }
                   4254:     }
1.1401    raeburn  4255:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4256:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4257:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4258:                                                        $allfiles,$codebase);
                   4259:             unless ($parse_result eq 'ok') {
                   4260:                 &logthis('Failed to parse '.$filepath.$file.
                   4261: 	   	         ' for embedded media: '.$parse_result); 
                   4262:             }
1.637     raeburn  4263:         }
1.1401    raeburn  4264:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4265:         my $format = $env{'form.scantron_format'};
                   4266:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4267:     }
1.860     raeburn  4268:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4269:         my $input = $filepath.'/'.$file;
                   4270:         my $output = $filepath.'/'.'tn-'.$file;
                   4271:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4272:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4273:         system({$args[0]} @args);
1.860     raeburn  4274:         if (-e $filepath.'/'.'tn-'.$file) {
                   4275:             $fetchthumb  = 1; 
                   4276:         }
                   4277:     }
1.858     raeburn  4278:  
1.259     www      4279: # Notify homeserver to grep it
                   4280: #
1.984     neumanie 4281:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4282:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4283:     if ($fetchresult eq 'ok') {
1.860     raeburn  4284:         if ($fetchthumb) {
                   4285:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4286:             if ($thumbresult ne 'ok') {
                   4287:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4288:                          $docuhome.': '.$thumbresult);
                   4289:             }
                   4290:         }
1.259     www      4291: #
1.258     www      4292: # Return the URL to it
1.494     albertel 4293:         return '/uploaded/'.$path.$file;
1.263     www      4294:     } else {
1.494     albertel 4295:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4296: 		 ': '.$fetchresult);
1.263     www      4297:         return '/adm/notfound.html';
1.858     raeburn  4298:     }
1.493     albertel 4299: }
                   4300: 
1.637     raeburn  4301: sub extract_embedded_items {
1.961     raeburn  4302:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4303:     my @state = ();
1.1164    raeburn  4304:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4305:     my %javafiles = (
                   4306:                       codebase => '',
                   4307:                       code => '',
                   4308:                       archive => ''
                   4309:                     );
                   4310:     my %mediafiles = (
                   4311:                       src => '',
                   4312:                       movie => '',
                   4313:                      );
1.648     raeburn  4314:     my $p;
                   4315:     if ($content) {
                   4316:         $p = HTML::LCParser->new($content);
                   4317:     } else {
1.961     raeburn  4318:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4319:     }
1.641     albertel 4320:     while (my $t=$p->get_token()) {
1.640     albertel 4321: 	if ($t->[0] eq 'S') {
                   4322: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4323: 	    push(@state, $tagname);
1.648     raeburn  4324:             if (lc($tagname) eq 'allow') {
                   4325:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4326:             }
1.640     albertel 4327: 	    if (lc($tagname) eq 'img') {
                   4328: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4329: 	    }
1.886     albertel 4330: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4331:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4332:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4333:                 }
1.886     albertel 4334: 	    }
1.645     raeburn  4335:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4336:                 my $src;
1.645     raeburn  4337:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4338:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4339:                 } else {
1.1164    raeburn  4340:                     if ($attr->{'src'} ne '') {
                   4341:                         $src = $attr->{'src'};
                   4342:                         &add_filetype($allfiles,$src,'src');
                   4343:                     }
                   4344:                 }
                   4345:                 my $text = $p->get_trimmed_text();
                   4346:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4347:                     my @swfargs = split(/,/,$1);
                   4348:                     foreach my $item (@swfargs) {
                   4349:                         $item =~ s/["']//g;
                   4350:                         $item =~ s/^\s+//;
                   4351:                         $item =~ s/\s+$//;
                   4352:                     }
                   4353:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4354:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4355:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4356:                         } else {
                   4357:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4358:                         }
                   4359:                     }
1.645     raeburn  4360:                 }
                   4361:             }
                   4362:             if (lc($tagname) eq 'link') {
                   4363:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4364:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4365:                 }
                   4366:             }
1.640     albertel 4367: 	    if (lc($tagname) eq 'object' ||
                   4368: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4369: 		foreach my $item (keys(%javafiles)) {
                   4370: 		    $javafiles{$item} = '';
                   4371: 		}
1.1164    raeburn  4372:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4373:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4374:                 }
1.640     albertel 4375: 	    }
                   4376: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4377: 		my $name = lc($attr->{'name'});
                   4378: 		foreach my $item (keys(%javafiles)) {
                   4379: 		    if ($name eq $item) {
                   4380: 			$javafiles{$item} = $attr->{'value'};
                   4381: 			last;
                   4382: 		    }
                   4383: 		}
1.1164    raeburn  4384:                 my $pathfrom;
1.640     albertel 4385: 		foreach my $item (keys(%mediafiles)) {
                   4386: 		    if ($name eq $item) {
1.1164    raeburn  4387:                         $pathfrom = $attr->{'value'};
                   4388:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4389: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4390: 			last;
                   4391: 		    }
                   4392: 		}
1.1164    raeburn  4393:                 if ($name eq 'flashvars') {
                   4394:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4395:                 }
                   4396:                 if ($pathfrom ne '') {
                   4397:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4398:                                          $pathfrom);
                   4399:                 }
1.640     albertel 4400: 	    }
                   4401: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4402: 		foreach my $item (keys(%javafiles)) {
                   4403: 		    if ($attr->{$item}) {
                   4404: 			$javafiles{$item} = $attr->{$item};
                   4405: 			last;
                   4406: 		    }
                   4407: 		}
                   4408: 		foreach my $item (keys(%mediafiles)) {
                   4409: 		    if ($attr->{$item}) {
                   4410: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4411: 			last;
                   4412: 		    }
                   4413: 		}
1.1164    raeburn  4414:                 if (lc($tagname) eq 'embed') {
                   4415:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4416:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4417:                                              $attr->{'src'});
                   4418:                     }
                   4419:                 }
1.640     albertel 4420: 	    }
1.1243    raeburn  4421:             if (lc($tagname) eq 'iframe') {
                   4422:                 my $src = $attr->{'src'} ;
                   4423:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4424:                     &add_filetype($allfiles,$src,'src');
                   4425:                 } elsif ($src =~ m{^/}) {
                   4426:                     if ($env{'request.course.id'}) {
                   4427:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4428:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4429:                         my $url = &hreflocation('',$fullpath);
                   4430:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4431:                             my $relpath = $1;
                   4432:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4433:                                 &add_filetype($allfiles,$1,'src');
                   4434:                             }
                   4435:                         }
                   4436:                     }
                   4437:                 }
                   4438:             }
1.1164    raeburn  4439:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4440:                 pop(@state);
1.1164    raeburn  4441:             }
1.640     albertel 4442: 	} elsif ($t->[0] eq 'E') {
                   4443: 	    my ($tagname) = ($t->[1]);
                   4444: 	    if ($javafiles{'codebase'} ne '') {
                   4445: 		$javafiles{'codebase'} .= '/';
                   4446: 	    }  
                   4447: 	    if (lc($tagname) eq 'applet' ||
                   4448: 		lc($tagname) eq 'object' ||
                   4449: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4450: 		) {
                   4451: 		foreach my $item (keys(%javafiles)) {
                   4452: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4453: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4454: 			&add_filetype($allfiles,$file,$item);
                   4455: 		    }
                   4456: 		}
                   4457: 	    } 
                   4458: 	    pop @state;
                   4459: 	}
                   4460:     }
1.1164    raeburn  4461:     foreach my $id (sort(keys(%flashvars))) {
                   4462:         if ($shockwave{$id} ne '') {
                   4463:             my @pairs = split(/\&/,$flashvars{$id});
                   4464:             foreach my $pair (@pairs) {
                   4465:                 my ($key,$value) = split(/\=/,$pair);
                   4466:                 if ($key eq 'thumb') {
                   4467:                     &add_filetype($allfiles,$value,$key);
                   4468:                 } elsif ($key eq 'content') {
                   4469:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4470:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4471:                     if ($ext ne '') {
                   4472:                         &add_filetype($allfiles,$path.$value,$ext);
                   4473:                     }
                   4474:                 }
                   4475:             }
                   4476:         }
                   4477:     }
1.637     raeburn  4478:     return 'ok';
                   4479: }
                   4480: 
1.639     albertel 4481: sub add_filetype {
                   4482:     my ($allfiles,$file,$type)=@_;
                   4483:     if (exists($allfiles->{$file})) {
                   4484: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4485: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4486: 	}
                   4487:     } else {
                   4488: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4489:     }
                   4490: }
                   4491: 
1.1164    raeburn  4492: sub embedded_dependency {
                   4493:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4494:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4495:         if (($identifier ne '') &&
                   4496:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4497:             ($pathfrom ne '')) {
                   4498:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4499:             foreach my $dep (@{$related->{$identifier}}) {
                   4500:                 &add_filetype($allfiles,$path.$dep,'object');
                   4501:             }
                   4502:         }
                   4503:     }
                   4504:     return;
                   4505: }
                   4506: 
1.1401    raeburn  4507: sub bubblesheet_converter {
                   4508:     my ($cdom,$fullpath,$config,$format) = @_;
                   4509:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4510:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4511:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4512:         my (%csvcols,%csvoptions);
                   4513:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4514:             %csvcols = %{$config->{'fields'}};
                   4515:         }
                   4516:         if (ref($config->{'options'}) eq 'HASH') {
                   4517:             %csvoptions = %{$config->{'options'}};
                   4518:         }
1.1401    raeburn  4519:         my %csvbynum = reverse(%csvcols);
                   4520:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4521:         if (keys(%scantronconf)) {
                   4522:             my %bynum = (
                   4523:                           $scantronconf{CODEstart} => 'CODEstart',
                   4524:                           $scantronconf{IDstart}   => 'IDstart',
                   4525:                           $scantronconf{PaperID}   => 'PaperID',
                   4526:                           $scantronconf{FirstName} => 'FirstName',
                   4527:                           $scantronconf{LastName}  => 'LastName',
                   4528:                           $scantronconf{Qstart}    => 'Qstart',
                   4529:                         );
                   4530:             my @ordered;
                   4531:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4532:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4533:             }
                   4534:             my %mapstart = (
                   4535:                               CODEstart => 'CODE',
                   4536:                               IDstart   => 'ID',
                   4537:                               PaperID   => 'PaperID',
                   4538:                               FirstName => 'FirstName',
                   4539:                               LastName  => 'LastName',
                   4540:                               Qstart    => 'FirstQuestion',
                   4541:                            );
                   4542:             my %maplength = (
                   4543:                               CODEstart => 'CODElength',
                   4544:                               IDstart   => 'IDlength',
                   4545:                               PaperID   => 'PaperIDlength',
                   4546:                               FirstName => 'FirstNamelength',
                   4547:                               LastName  => 'LastNamelength',
                   4548:             );
                   4549:             if (open(my $fh,'<',$fullpath)) {
                   4550:                 my $output;
1.1403    raeburn  4551:                 my %lettdig = &letter_to_digits();
                   4552:                 my %diglett = reverse(%lettdig);
                   4553:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4554:                 my $num = 0;
1.1401    raeburn  4555:                 while (my $line=<$fh>) {
1.1404    raeburn  4556:                     $num ++;
                   4557:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4558:                     $line =~ s{[\r\n]+$}{};
                   4559:                     my %found;
                   4560:                     my @values = split(/,/,$line);
                   4561:                     my ($qstart,$record);
                   4562:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4563:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4564:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4565:                             if ($values[$i] eq '') {
                   4566:                                 $values[$i] = $scantronconf{'Qoff'};
                   4567:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4568:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4569:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4570:                                 }
                   4571:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4572:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4573:                                     $values[$i] = $diglett{$values[$i]};
                   4574:                                 }
                   4575:                             } else {
                   4576:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4577:                                     my $digit;
                   4578:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4579:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4580:                                         if ($values[$i] eq 'J') {
                   4581:                                             $digit += $numletts;
                   4582:                                         }
                   4583:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4584:                                         $digit = $values[$i]-1;
                   4585:                                         if ($values[$i] eq '0') {
                   4586:                                             $digit += $numletts;
                   4587:                                         }
                   4588:                                     }
                   4589:                                     my $qval='';
                   4590:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4591:                                         if ($j == $digit) {
                   4592:                                             $qval .= $scantronconf{'Qon'};
                   4593:                                         } else {
                   4594:                                             $qval .= $scantronconf{'Qoff'};
                   4595:                                         }
                   4596:                                     }
                   4597:                                     $values[$i] = $qval;
                   4598:                                 }
                   4599:                             }
                   4600:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4601:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4602:                             }
                   4603:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4604:                             if ($numblank > 0) {
                   4605:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4606:                             }
1.1401    raeburn  4607:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4608:                                 $qstart = $i;
1.1403    raeburn  4609:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4610:                             } else {
1.1403    raeburn  4611:                                 $found{'FirstQuestion'} .= $values[$i];
                   4612:                             }
                   4613:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4614:                             if ($csvoptions{'rem'}) {
                   4615:                                 $values[$i] =~ s/^\s+//;
                   4616:                             }
                   4617:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4618:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4619:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4620:                                 }
                   4621:                             }
                   4622:                             $found{$csvbynum{$i}} = $values[$i];
                   4623:                         }
                   4624:                     }
                   4625:                     foreach my $item (@ordered) {
                   4626:                         my $currlength = 1+length($record);
                   4627:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4628:                         if ($numspaces > 0) {
                   4629:                             $record .= (' ' x $numspaces);
                   4630:                         }
                   4631:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4632:                             unless ($item eq 'Qstart') {
                   4633:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4634:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4635:                                 }
                   4636:                             }
                   4637:                             $record .= $found{$mapstart{$item}};
                   4638:                         }
                   4639:                     }
                   4640:                     $output .= "$record\n";
                   4641:                 }
                   4642:                 close($fh);
                   4643:                 if ($output) {
                   4644:                     if (open(my $fh,'>',$fullpath)) {
                   4645:                         print $fh $output;
                   4646:                         close($fh);
                   4647:                     }
                   4648:                 }
                   4649:             }
                   4650:         }
                   4651:         return;
                   4652:     }
                   4653: }
                   4654: 
1.1403    raeburn  4655: sub letter_to_digits {
                   4656:     my %lettdig = (
                   4657:                     A => 1,
                   4658:                     B => 2,
                   4659:                     C => 3,
                   4660:                     D => 4,
                   4661:                     E => 5,
                   4662:                     F => 6,
                   4663:                     G => 7,
                   4664:                     H => 8,
                   4665:                     I => 9,
                   4666:                     J => 0,
                   4667:                   );
                   4668:     return %lettdig;
                   4669: }
                   4670: 
1.1401    raeburn  4671: sub get_scantron_config {
                   4672:     my ($which,$cdom) = @_;
                   4673:     my @lines = &get_scantronformat_file($cdom);
                   4674:     my %config;
                   4675:     #FIXME probably should move to XML it has already gotten a bit much now
                   4676:     foreach my $line (@lines) {
                   4677:         my ($name,$descrip)=split(/:/,$line);
                   4678:         if ($name ne $which ) { next; }
                   4679:         chomp($line);
                   4680:         my @config=split(/:/,$line);
                   4681:         $config{'name'}=$config[0];
                   4682:         $config{'description'}=$config[1];
                   4683:         $config{'CODElocation'}=$config[2];
                   4684:         $config{'CODEstart'}=$config[3];
                   4685:         $config{'CODElength'}=$config[4];
                   4686:         $config{'IDstart'}=$config[5];
                   4687:         $config{'IDlength'}=$config[6];
                   4688:         $config{'Qstart'}=$config[7];
                   4689:         $config{'Qlength'}=$config[8];
                   4690:         $config{'Qoff'}=$config[9];
                   4691:         $config{'Qon'}=$config[10];
                   4692:         $config{'PaperID'}=$config[11];
                   4693:         $config{'PaperIDlength'}=$config[12];
                   4694:         $config{'FirstName'}=$config[13];
                   4695:         $config{'FirstNamelength'}=$config[14];
                   4696:         $config{'LastName'}=$config[15];
                   4697:         $config{'LastNamelength'}=$config[16];
                   4698:         $config{'BubblesPerRow'}=$config[17];
                   4699:         last;
                   4700:     }
                   4701:     return %config;
                   4702: }
                   4703: 
                   4704: sub get_scantronformat_file {
                   4705:     my ($cdom) = @_;
                   4706:     if ($cdom eq '') {
                   4707:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4708:     }
                   4709:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4710:     my $gottab = 0;
                   4711:     my @lines;
                   4712:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4713:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4714:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4715:             if ($formatfile ne '-1') {
                   4716:                 @lines = split("\n",$formatfile,-1);
                   4717:                 $gottab = 1;
                   4718:             }
                   4719:         }
                   4720:     }
                   4721:     if (!$gottab) {
                   4722:         my $confname = $cdom.'-domainconfig';
                   4723:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4724:         my $formatfile = &getfile($default);
                   4725:         if ($formatfile ne '-1') {
                   4726:             @lines = split("\n",$formatfile,-1);
                   4727:             $gottab = 1;
                   4728:         }
                   4729:     }
                   4730:     if (!$gottab) {
                   4731:         my @domains = &current_machine_domains();
                   4732:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4733:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4734:                 @lines = <$fh>;
                   4735:                 close($fh);
1.1403    raeburn  4736:             }
1.1401    raeburn  4737:         } else {
                   4738:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4739:                 @lines = <$fh>;
                   4740:                 close($fh);
                   4741:             }
                   4742:         }
                   4743:     }
                   4744:     return @lines;
                   4745: }
                   4746: 
1.493     albertel 4747: sub removeuploadedurl {
1.984     neumanie 4748:     my ($url)=@_;	
                   4749:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4750:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4751: }
                   4752: 
                   4753: sub removeuserfile {
                   4754:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4755:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4756:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4757:     if ($result eq 'ok') {	
1.798     raeburn  4758:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4759:             my $metafile = $fname.'.meta';
                   4760:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4761: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4762:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4763:             my $sqlresult = 
1.823     albertel 4764:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4765:                                         'portfolio_metadata',$group,
                   4766:                                         'delete');
1.798     raeburn  4767:         }
                   4768:     }
                   4769:     return $result;
1.257     www      4770: }
1.15      www      4771: 
1.530     albertel 4772: sub mkdiruserfile {
                   4773:     my ($docuname,$docudom,$dir)=@_;
                   4774:     my $home=&homeserver($docuname,$docudom);
                   4775:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4776: }
                   4777: 
1.531     albertel 4778: sub renameuserfile {
                   4779:     my ($docuname,$docudom,$old,$new)=@_;
                   4780:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4781:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4782:                         &escape("$old").':'.&escape("$new"),$home);
                   4783:     if ($result eq 'ok') {
                   4784:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4785:             my $oldmeta = $old.'.meta';
                   4786:             my $newmeta = $new.'.meta';
                   4787:             my $metaresult = 
                   4788:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4789: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4790:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4791:             my $sqlresult = 
1.823     albertel 4792:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4793:                                         'portfolio_metadata',$group,
                   4794:                                         'delete');
1.798     raeburn  4795:         }
                   4796:     }
                   4797:     return $result;
1.531     albertel 4798: }
                   4799: 
1.14      www      4800: # ------------------------------------------------------------------------- Log
                   4801: 
                   4802: sub log {
                   4803:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4804:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4805: }
                   4806: 
                   4807: # ------------------------------------------------------------------ Course Log
1.352     www      4808: #
                   4809: # This routine flushes several buffers of non-mission-critical nature
                   4810: #
1.157     www      4811: 
                   4812: sub flushcourselogs {
1.352     www      4813:     &logthis('Flushing log buffers');
                   4814: #
                   4815: # course logs
                   4816: # This is a log of all transactions in a course, which can be used
                   4817: # for data mining purposes
                   4818: #
                   4819: # It also collects the courseid database, which lists last transaction
                   4820: # times and course titles for all courseids
                   4821: #
                   4822:     my %courseidbuffer=();
1.921     raeburn  4823:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4824:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4825: 		          &escape($courselogs{$crsid}),
                   4826: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4827: 	    delete $courselogs{$crsid};
                   4828:         } else {
                   4829:             &logthis('Failed to flush log buffer for '.$crsid);
                   4830:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4831:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4832:                         " exceeded maximum size, deleting.</font>");
                   4833:                delete $courselogs{$crsid};
                   4834:             }
1.352     www      4835:         }
1.920     raeburn  4836:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4837:             'description' => $coursedescrbuf{$crsid},
                   4838:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4839:             'type'        => $coursetypebuf{$crsid},
                   4840:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4841:         };
1.191     harris41 4842:     }
1.352     www      4843: #
                   4844: # Write course id database (reverse lookup) to homeserver of courses 
                   4845: # Is used in pickcourse
                   4846: #
1.840     albertel 4847:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4848:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4849:                                     $courseidbuffer{$crs_home},
                   4850:                                     $crs_home,'timeonly');
1.352     www      4851:     }
                   4852: #
                   4853: # File accesses
                   4854: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4855: #
1.449     matthew  4856:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4857:         if ($entry =~ /___count$/) {
                   4858:             my ($dom,$name);
1.807     albertel 4859:             ($dom,$name,undef)=
1.811     albertel 4860: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4861:             if (! defined($dom) || $dom eq '' || 
                   4862:                 ! defined($name) || $name eq '') {
1.620     albertel 4863:                 my $cid = $env{'request.course.id'};
                   4864:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4865:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4866:             }
1.450     matthew  4867:             my $value = $accesshash{$entry};
                   4868:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4869:             my %temphash=($url => $value);
1.449     matthew  4870:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4871:             if ($result eq 'ok') {
                   4872:                 delete $accesshash{$entry};
                   4873:             }
                   4874:         } else {
1.811     albertel 4875:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4876:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4877:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4878:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4879:                 delete $accesshash{$entry};
                   4880:             }
1.185     www      4881:         }
1.191     harris41 4882:     }
1.352     www      4883: #
                   4884: # Roles
                   4885: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4886: #
1.800     albertel 4887:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4888:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4889: 	    split(/\:/,$entry);
                   4890:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4891:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4892:                 $rudom,$runame) eq 'ok') {
                   4893: 	    delete $userrolehash{$entry};
                   4894:         }
                   4895:     }
1.662     raeburn  4896: #
1.1334    raeburn  4897: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4898: #
                   4899:     my %domrolebuffer = ();
1.1000    raeburn  4900:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4901:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4902:         if ($domrolebuffer{$rudom}) {
                   4903:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4904:                       '='.&escape($domainrolehash{$entry});
                   4905:         } else {
                   4906:             $domrolebuffer{$rudom}.=&escape($entry).
                   4907:                       '='.&escape($domainrolehash{$entry});
                   4908:         }
                   4909:         delete $domainrolehash{$entry};
                   4910:     }
                   4911:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4912: 	my %servers;
                   4913: 	if (defined(&domain($dom,'primary'))) {
                   4914: 	    my $primary=&domain($dom,'primary');
                   4915: 	    my $hostname=&hostname($primary);
                   4916: 	    $servers{$primary} = $hostname;
                   4917: 	} else { 
                   4918: 	    %servers = &get_servers($dom,'library');
                   4919: 	}
1.841     albertel 4920: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4921: 	    if (&reply('domroleput:'.$dom.':'.
                   4922: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4923: 		last;
                   4924: 	    } else {  
1.841     albertel 4925: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4926: 	    }
1.662     raeburn  4927:         }
                   4928:     }
1.186     www      4929:     $dumpcount++;
1.157     www      4930: }
                   4931: 
                   4932: sub courselog {
                   4933:     my $what=shift;
1.158     www      4934:     $what=time.':'.$what;
1.620     albertel 4935:     unless ($env{'request.course.id'}) { return ''; }
                   4936:     $coursedombuf{$env{'request.course.id'}}=
                   4937:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4938:     $coursenumbuf{$env{'request.course.id'}}=
                   4939:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4940:     $coursehombuf{$env{'request.course.id'}}=
                   4941:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4942:     $coursedescrbuf{$env{'request.course.id'}}=
                   4943:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4944:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4945:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4946:     $courseownerbuf{$env{'request.course.id'}}=
                   4947:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4948:     $coursetypebuf{$env{'request.course.id'}}=
                   4949:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4950:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4951: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4952:     } else {
1.620     albertel 4953: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4954:     }
1.620     albertel 4955:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4956: 	&flushcourselogs();
                   4957:     }
1.158     www      4958: }
                   4959: 
                   4960: sub courseacclog {
                   4961:     my $fnsymb=shift;
1.620     albertel 4962:     unless ($env{'request.course.id'}) { return ''; }
                   4963:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4964:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4965:         $what.=':POST';
1.583     matthew  4966:         # FIXME: Probably ought to escape things....
1.800     albertel 4967: 	foreach my $key (keys(%env)) {
                   4968:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4969:                 my $formitem = $1;
                   4970:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4971:                     $what.=':'.$formitem.'='.$env{$key};
                   4972:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4973:                     $what.=':'.$formitem.'='.$env{$key};
                   4974:                 }
1.158     www      4975:             }
1.191     harris41 4976:         }
1.583     matthew  4977:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4978:         # FIXME: We should not be depending on a form parameter that someone
                   4979:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4980:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4981:             $what.= ':POST';
                   4982:             # FIXME: Probably ought to escape things....
                   4983:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4984:                                  'crsdiscuss') {
1.620     albertel 4985:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4986:             }
                   4987:         }
1.158     www      4988:     }
                   4989:     &courselog($what);
1.149     www      4990: }
                   4991: 
1.185     www      4992: sub countacc {
                   4993:     my $url=&declutter(shift);
1.458     matthew  4994:     return if (! defined($url) || $url eq '');
1.620     albertel 4995:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4996: #
                   4997: # Mark that this url was used in this course
                   4998: #
1.620     albertel 4999:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5000: #
                   5001: # Increase the access count for this resource in this child process
                   5002: #
1.281     www      5003:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5004:     $accesshash{$key}++;
1.185     www      5005: }
1.349     www      5006: 
1.361     www      5007: sub linklog {
                   5008:     my ($from,$to)=@_;
                   5009:     $from=&declutter($from);
                   5010:     $to=&declutter($to);
                   5011:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5012:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5013: }
1.1160    www      5014: 
                   5015: sub statslog {
                   5016:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5017:     if ($users<2) { return; }
                   5018:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5019:             'course'       => $env{'request.course.id'},
                   5020:             'sections'     => '"all"',
                   5021:             'num_students' => $users,
                   5022:             'part'         => $part,
                   5023:             'symb'         => $symb,
                   5024:             'mean_tries'   => $av_attempts,
                   5025:             'deg_of_diff'  => $degdiff});
                   5026:     foreach my $key (keys(%dynstore)) {
                   5027:         $accesshash{$key}=$dynstore{$key};
                   5028:     }
                   5029: }
1.361     www      5030:   
1.349     www      5031: sub userrolelog {
                   5032:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5033:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5034:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5035:        $userrolehash
                   5036:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5037:                     =$tend.':'.$tstart;
1.662     raeburn  5038:     }
1.1169    droeschl 5039:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5040:        $userrolehash
                   5041:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5042:                     =$tend.':'.$tstart;
                   5043:     }
1.1334    raeburn  5044:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5045:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5046:        $domainrolehash
                   5047:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5048:                     = $tend.':'.$tstart;
                   5049:     }
1.351     www      5050: }
                   5051: 
1.957     raeburn  5052: sub courserolelog {
                   5053:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5054:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5055:         my $cdom = $1;
                   5056:         my $cnum = $2;
                   5057:         my $sec = $3;
                   5058:         my $namespace = 'rolelog';
                   5059:         my %storehash = (
                   5060:                            role    => $trole,
                   5061:                            start   => $tstart,
                   5062:                            end     => $tend,
                   5063:                            selfenroll => $selfenroll,
                   5064:                            context    => $context,
                   5065:                         );
                   5066:         if ($trole eq 'gr') {
                   5067:             $namespace = 'groupslog';
                   5068:             $storehash{'group'} = $sec;
                   5069:         } else {
                   5070:             $storehash{'section'} = $sec;
                   5071:         }
1.1188    raeburn  5072:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5073:                    $domain,$cnum,$cdom);
1.1184    raeburn  5074:         if (($trole ne 'st') || ($sec ne '')) {
                   5075:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5076:         }
                   5077:     }
                   5078:     return;
                   5079: }
                   5080: 
1.1184    raeburn  5081: sub domainrolelog {
                   5082:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5083:     if ($area =~ m{^/($match_domain)/$}) {
                   5084:         my $cdom = $1;
                   5085:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5086:         my $namespace = 'rolelog';
                   5087:         my %storehash = (
                   5088:                            role    => $trole,
                   5089:                            start   => $tstart,
                   5090:                            end     => $tend,
                   5091:                            context => $context,
                   5092:                         );
1.1188    raeburn  5093:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5094:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5095:     }
                   5096:     return;
                   5097: 
                   5098: }
                   5099: 
                   5100: sub coauthorrolelog {
                   5101:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5102:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5103:         my $audom = $1;
                   5104:         my $auname = $2;
                   5105:         my $namespace = 'rolelog';
                   5106:         my %storehash = (
                   5107:                            role    => $trole,
                   5108:                            start   => $tstart,
                   5109:                            end     => $tend,
                   5110:                            context => $context,
                   5111:                         );
1.1188    raeburn  5112:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5113:                    $domain,$auname,$audom);
1.1184    raeburn  5114:     }
                   5115:     return;
                   5116: }
                   5117: 
1.351     www      5118: sub get_course_adv_roles {
1.948     raeburn  5119:     my ($cid,$codes) = @_;
1.620     albertel 5120:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5121:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5122:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5123:     my %nothide=();
1.800     albertel 5124:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5125:         if ($user !~ /:/) {
                   5126: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5127:         } else {
                   5128:             $nothide{$user}=1;
                   5129:         }
1.470     www      5130:     }
1.1219    raeburn  5131:     my @possdoms = ($coursehash{'domain'});
                   5132:     if ($coursehash{'checkforpriv'}) {
                   5133:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5134:     }
1.351     www      5135:     my %returnhash=();
                   5136:     my %dumphash=
                   5137:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5138:     my $now=time;
1.997     raeburn  5139:     my %privileged;
1.1000    raeburn  5140:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5141: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5142:         if (($tstart) && ($tstart<0)) { next; }
                   5143:         if (($tend) && ($tend<$now)) { next; }
                   5144:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5145:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5146: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5147:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5148:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5149: 	if ($role eq 'cr') { next; }
1.948     raeburn  5150:         if ($codes) {
                   5151:             if ($section) { $role .= ':'.$section; }
                   5152:             if ($returnhash{$role}) {
                   5153:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5154:             } else {
                   5155:                 $returnhash{$role}=$username.':'.$domain;
                   5156:             }
1.351     www      5157:         } else {
1.988     raeburn  5158:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5159:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5160:             if ($returnhash{$key}) {
                   5161: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5162:             } else {
                   5163:                 $returnhash{$key}=$username.':'.$domain;
                   5164:             }
1.351     www      5165:         }
1.948     raeburn  5166:     }
1.400     www      5167:     return %returnhash;
                   5168: }
                   5169: 
                   5170: sub get_my_roles {
1.937     raeburn  5171:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5172:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5173:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5174:     my (%dumphash,%nothide);
1.1086    raeburn  5175:     if ($context eq 'userroles') {
1.1166    raeburn  5176:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5177:     } else {
1.1219    raeburn  5178:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5179:         if ($hidepriv) {
                   5180:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5181:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5182:                 if ($user !~ /:/) {
                   5183:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5184:                 } else {
                   5185:                     $nothide{$user} = 1;
                   5186:                 }
                   5187:             }
                   5188:         }
1.858     raeburn  5189:     }
1.400     www      5190:     my %returnhash=();
                   5191:     my $now=time;
1.999     raeburn  5192:     my %privileged;
1.800     albertel 5193:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5194:         my ($role,$tend,$tstart);
                   5195:         if ($context eq 'userroles') {
1.1149    raeburn  5196:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5197: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5198:         } else {
                   5199:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5200:         }
1.400     www      5201:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5202:         my $status = 'active';
1.939     raeburn  5203:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5204:             $status = 'previous';
                   5205:         } 
                   5206:         if (($tstart) && ($now<$tstart)) {
                   5207:             $status = 'future';
                   5208:         }
                   5209:         if (ref($types) eq 'ARRAY') {
                   5210:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5211:                 next;
                   5212:             } 
                   5213:         } else {
                   5214:             if ($status ne 'active') {
                   5215:                 next;
                   5216:             }
                   5217:         }
1.867     raeburn  5218:         my ($rolecode,$username,$domain,$section,$area);
                   5219:         if ($context eq 'userroles') {
1.1186    raeburn  5220:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5221:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5222:         } else {
                   5223:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5224:         }
1.832     raeburn  5225:         if (ref($roledoms) eq 'ARRAY') {
                   5226:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5227:                 next;
                   5228:             }
                   5229:         }
                   5230:         if (ref($roles) eq 'ARRAY') {
                   5231:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5232:                 if ($role =~ /^cr\//) {
                   5233:                     if (!grep(/^cr$/,@{$roles})) {
                   5234:                         next;
                   5235:                     }
1.1104    raeburn  5236:                 } elsif ($role =~ /^gr\//) {
                   5237:                     if (!grep(/^gr$/,@{$roles})) {
                   5238:                         next;
                   5239:                     }
1.922     raeburn  5240:                 } else {
                   5241:                     next;
                   5242:                 }
1.832     raeburn  5243:             }
1.867     raeburn  5244:         }
1.937     raeburn  5245:         if ($hidepriv) {
1.1219    raeburn  5246:             my @privroles = ('dc','su');
1.999     raeburn  5247:             if ($context eq 'userroles') {
1.1219    raeburn  5248:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5249:             } else {
1.1219    raeburn  5250:                 my $possdoms = [$domain];
                   5251:                 if (ref($roledoms) eq 'ARRAY') {
                   5252:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5253:                 }
1.1219    raeburn  5254:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5255:                     if (!$nothide{$username.':'.$domain}) {
                   5256:                         next;
                   5257:                     }
                   5258:                 }
1.937     raeburn  5259:             }
                   5260:         }
1.933     raeburn  5261:         if ($withsec) {
                   5262:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5263:                 $tstart.':'.$tend;
                   5264:         } else {
                   5265:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5266:         }
1.832     raeburn  5267:     }
1.373     www      5268:     return %returnhash;
1.399     www      5269: }
                   5270: 
1.1333    raeburn  5271: sub get_all_adhocroles {
                   5272:     my ($dom) = @_;
                   5273:     my @roles_by_num = ();
                   5274:     my %domdefaults = &get_domain_defaults($dom);
                   5275:     my (%description,%access_in_dom,%access_info);
                   5276:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5277:         my $count = 0;
                   5278:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5279:         my %ordered;
                   5280:         foreach my $role (sort(keys(%domcurrent))) {
                   5281:             my ($order,$desc,$access_in_dom);
                   5282:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5283:                 $order = $domcurrent{$role}{'order'};
                   5284:                 $desc = $domcurrent{$role}{'desc'};
                   5285:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5286:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5287:             }
                   5288:             if ($order eq '') {
                   5289:                 $order = $count;
                   5290:             }
                   5291:             $ordered{$order} = $role;
                   5292:             if ($desc ne '') {
                   5293:                 $description{$role} = $desc;
                   5294:             } else {
                   5295:                 $description{$role}= $role;
                   5296:             }
                   5297:             $count++;
                   5298:         }
                   5299:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5300:             push(@roles_by_num,$ordered{$item});
                   5301:         }
                   5302:     }
                   5303:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5304: }
                   5305: 
1.1332    raeburn  5306: sub get_my_adhocroles {
1.1333    raeburn  5307:     my ($cid,$checkreg) = @_;
                   5308:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5309:     if ($env{'request.course.id'} eq $cid) {
                   5310:         $cdom = $env{'course.'.$cid.'.domain'};
                   5311:         $cnum = $env{'course.'.$cid.'.num'};
                   5312:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5313:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5314:         $cdom = $1;
                   5315:         $cnum = $2;
                   5316:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5317:                                      $cdom,$cnum);
                   5318:     }
                   5319:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5320:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5321:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5322:         if ($rosterhash{$user} ne '') {
                   5323:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5324:             return ([],{}) if ($type eq 'auto');
                   5325:         }
                   5326:     }
                   5327:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5328:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5329:             my $then=$env{'user.login.time'};
                   5330:             my $update=$env{'user.update.time'};
1.1335    raeburn  5331:             if (!$update) {
                   5332:                 $update = $then;
                   5333:             }
                   5334:             my @liveroles;
1.1334    raeburn  5335:             foreach my $role ('dh','da') {
                   5336:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5337:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5338:                     my $limit = $update;
                   5339:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5340:                         $limit = $then;
                   5341:                     }
1.1335    raeburn  5342:                     my $activerole = 1;
                   5343:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5344:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5345:                     if ($activerole) {
                   5346:                         push(@liveroles,$role);
                   5347:                     }
1.1334    raeburn  5348:                 }
1.1332    raeburn  5349:             }
1.1335    raeburn  5350:             if (@liveroles) {
1.1332    raeburn  5351:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5352:                     my ($accessref,$accessinfo,%access_in_dom);
                   5353:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5354:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5355:                         if (@{$roles_by_num}) {
1.1332    raeburn  5356:                             my %settings;
                   5357:                             if ($env{'request.course.id'} eq $cid) {
                   5358:                                 foreach my $envkey (keys(%env)) {
                   5359:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5360:                                         $settings{$1} = $env{$envkey};
                   5361:                                     }
                   5362:                                 }
                   5363:                             } else {
                   5364:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5365:                             }
                   5366:                             my %setincrs;
                   5367:                             if ($settings{'internal.adhocaccess'}) {
                   5368:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5369:                             }
                   5370:                             my @statuses;
                   5371:                             if ($env{'environment.inststatus'}) {
                   5372:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5373:                             }
                   5374:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5375:                             if (ref($accessref) eq 'HASH') {
                   5376:                                 %access_in_dom = %{$accessref};
                   5377:                             }
                   5378:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5379:                                 my ($curraccess,@okstatus,@personnel);
                   5380:                                 if ($setincrs{$role}) {
                   5381:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5382:                                     if ($curraccess eq 'status') {
                   5383:                                         @okstatus = split(/\&/,$rest);
                   5384:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5385:                                         @personnel = split(/\&/,$rest);
                   5386:                                     }
                   5387:                                 } else {
                   5388:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5389:                                     if (ref($accessinfo) eq 'HASH') {
                   5390:                                         if ($curraccess eq 'status') {
                   5391:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5392:                                                 @okstatus = @{$accessinfo->{$role}};
                   5393:                                             }
                   5394:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5395:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5396:                                                 @personnel = @{$accessinfo->{$role}};
                   5397:                                             }
1.1332    raeburn  5398:                                         }
                   5399:                                     }
                   5400:                                 }
                   5401:                                 if ($curraccess eq 'none') {
                   5402:                                     next;
                   5403:                                 } elsif ($curraccess eq 'all') {
                   5404:                                     push(@possroles,$role);
1.1336    raeburn  5405:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5406:                                     if (grep(/^dh$/,@liveroles)) {
                   5407:                                         push(@possroles,$role);
                   5408:                                     } else {
                   5409:                                         next;
                   5410:                                     }
1.1336    raeburn  5411:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5412:                                     if (grep(/^da$/,@liveroles)) {
                   5413:                                         push(@possroles,$role);
                   5414:                                     } else {
                   5415:                                         next;
                   5416:                                     }
1.1332    raeburn  5417:                                 } elsif ($curraccess eq 'status') {
                   5418:                                     if (@okstatus) {
                   5419:                                         if (!@statuses) {
                   5420:                                             if (grep(/^default$/,@okstatus)) {
                   5421:                                                 push(@possroles,$role);
                   5422:                                             }
                   5423:                                         } else {
                   5424:                                             foreach my $status (@okstatus) {
                   5425:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5426:                                                     push(@possroles,$role);
                   5427:                                                     last;
                   5428:                                                 }
                   5429:                                             }
                   5430:                                         }
                   5431:                                     }
                   5432:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5433:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5434:                                         if ($curraccess eq 'exc') {
                   5435:                                             push(@possroles,$role);
                   5436:                                         }
                   5437:                                     } elsif ($curraccess eq 'inc') {
                   5438:                                         push(@possroles,$role);
                   5439:                                     }
                   5440:                                 }
                   5441:                             }
                   5442:                         }
                   5443:                     }
                   5444:                 }
                   5445:             }
                   5446:         }
                   5447:     }
1.1333    raeburn  5448:     unless (ref($description) eq 'HASH') {
                   5449:         if (ref($roles_by_num) eq 'ARRAY') {
                   5450:             my %desc;
                   5451:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5452:             $description = \%desc;
                   5453:         } else {
                   5454:             $description = {};
                   5455:         }
                   5456:     }
                   5457:     return (\@possroles,$description);
1.1332    raeburn  5458: }
                   5459: 
1.399     www      5460: # ----------------------------------------------------- Frontpage Announcements
                   5461: #
                   5462: #
                   5463: 
                   5464: sub postannounce {
                   5465:     my ($server,$text)=@_;
1.844     albertel 5466:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5467:     unless ($text=~/\w/) { $text=''; }
                   5468:     return &reply('setannounce:'.&escape($text),$server);
                   5469: }
                   5470: 
                   5471: sub getannounce {
1.448     albertel 5472: 
1.1359    raeburn  5473:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5474: 	my $announcement='';
1.800     albertel 5475: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5476: 	close($fh);
1.399     www      5477: 	if ($announcement=~/\w/) { 
                   5478: 	    return 
                   5479:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5480:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5481: 	} else {
                   5482: 	    return '';
                   5483: 	}
                   5484:     } else {
                   5485: 	return '';
                   5486:     }
1.351     www      5487: }
1.353     www      5488: 
                   5489: # ---------------------------------------------------------- Course ID routines
                   5490: # Deal with domain's nohist_courseid.db files
                   5491: #
                   5492: 
                   5493: sub courseidput {
1.921     raeburn  5494:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5495:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5496:     my $outcome;
                   5497:     if ($caller eq 'timeonly') {
                   5498:         my $cids = '';
                   5499:         foreach my $item (keys(%$storehash)) {
                   5500:             $cids.=&escape($item).'&';
                   5501:         }
                   5502:         $cids=~s/\&$//;
                   5503:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5504:                           $coursehome);       
                   5505:     } else {
                   5506:         my $items = '';
                   5507:         foreach my $item (keys(%$storehash)) {
                   5508:             $items.= &escape($item).'='.
                   5509:                      &freeze_escape($$storehash{$item}).'&';
                   5510:         }
                   5511:         $items=~s/\&$//;
                   5512:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5513:                           $coursehome);
1.918     raeburn  5514:     }
                   5515:     if ($outcome eq 'unknown_cmd') {
                   5516:         my $what;
                   5517:         foreach my $cid (keys(%$storehash)) {
                   5518:             $what .= &escape($cid).'=';
1.921     raeburn  5519:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5520:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5521:             }
                   5522:             $what =~ s/\:$/&/;
                   5523:         }
                   5524:         $what =~ s/\&$//;  
                   5525:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5526:     } else {
                   5527:         return $outcome;
                   5528:     }
1.353     www      5529: }
                   5530: 
                   5531: sub courseiddump {
1.921     raeburn  5532:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5533:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5534:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5535:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5536:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5537:     my $as_hash = 1;
                   5538:     my %returnhash;
                   5539:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5540:     my %libserv = &all_library();
                   5541:     foreach my $tryserver (keys(%libserv)) {
                   5542:         if ( (  $hostidflag == 1 
                   5543: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5544: 	     || (!defined($hostidflag)) ) {
                   5545: 
1.918     raeburn  5546: 	    if (($domfilter eq '') ||
                   5547: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5548:                 my $rep;
                   5549:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5550:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5551:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5552:                                 &escape($descfilter), &escape($instcodefilter), 
                   5553:                                 &escape($ownerfilter), &escape($coursefilter),
                   5554:                                 &escape($typefilter), &escape($regexp_ok), 
                   5555:                                 $as_hash, &escape($selfenrollonly), 
                   5556:                                 &escape($catfilter), $showhidden, $caller, 
                   5557:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5558:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5559:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5560:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5561:                 } else {
                   5562:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5563:                              $sincefilter.':'.&escape($descfilter).':'.
                   5564:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5565:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5566:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5567:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5568:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5569:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5570:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5571:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5572:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5573:                 }
                   5574:                      
1.918     raeburn  5575:                 my @pairs=split(/\&/,$rep);
                   5576:                 foreach my $item (@pairs) {
                   5577:                     my ($key,$value)=split(/\=/,$item,2);
                   5578:                     $key = &unescape($key);
                   5579:                     next if ($key =~ /^error: 2 /);
                   5580:                     my $result = &thaw_unescape($value);
                   5581:                     if (ref($result) eq 'HASH') {
                   5582:                         $returnhash{$key}=$result;
                   5583:                     } else {
1.921     raeburn  5584:                         my @responses = split(/:/,$value);
                   5585:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5586:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5587:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5588:                         }
1.1008    raeburn  5589:                     }
1.353     www      5590:                 }
                   5591:             }
                   5592:         }
                   5593:     }
                   5594:     return %returnhash;
                   5595: }
                   5596: 
1.1055    raeburn  5597: sub courselastaccess {
                   5598:     my ($cdom,$cnum,$hostidref) = @_;
                   5599:     my %returnhash;
                   5600:     if ($cdom && $cnum) {
                   5601:         my $chome = &homeserver($cnum,$cdom);
                   5602:         if ($chome ne 'no_host') {
                   5603:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5604:             &extract_lastaccess(\%returnhash,$rep);
                   5605:         }
                   5606:     } else {
                   5607:         if (!$cdom) { $cdom=''; }
                   5608:         my %libserv = &all_library();
                   5609:         foreach my $tryserver (keys(%libserv)) {
                   5610:             if (ref($hostidref) eq 'ARRAY') {
                   5611:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5612:             } 
                   5613:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5614:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5615:                 &extract_lastaccess(\%returnhash,$rep);
                   5616:             }
                   5617:         }
                   5618:     }
                   5619:     return %returnhash;
                   5620: }
                   5621: 
                   5622: sub extract_lastaccess {
                   5623:     my ($returnhash,$rep) = @_;
                   5624:     if (ref($returnhash) eq 'HASH') {
                   5625:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5626:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5627:                  $rep eq '') {
                   5628:             my @pairs=split(/\&/,$rep);
                   5629:             foreach my $item (@pairs) {
                   5630:                 my ($key,$value)=split(/\=/,$item,2);
                   5631:                 $key = &unescape($key);
                   5632:                 next if ($key =~ /^error: 2 /);
                   5633:                 $returnhash->{$key} = &thaw_unescape($value);
                   5634:             }
                   5635:         }
                   5636:     }
                   5637:     return;
                   5638: }
                   5639: 
1.658     raeburn  5640: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5641: 
                   5642: sub dcmailput {
1.685     raeburn  5643:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5644:     my $status = &Apache::lonnet::critical(
1.740     www      5645:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5646:        &escape($message),$server);
1.662     raeburn  5647:     return $status;
                   5648: }
                   5649: 
1.658     raeburn  5650: sub dcmaildump {
                   5651:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5652:     my %returnhash=();
1.846     albertel 5653: 
                   5654:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5655:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5656:                                                          &escape($enddate).':';
                   5657: 	my @esc_senders=map { &escape($_)} @$senders;
                   5658: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5659: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5660:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5661:             if (($key) && ($value)) {
                   5662:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5663:             }
                   5664:         }
                   5665:     }
                   5666:     return %returnhash;
                   5667: }
1.662     raeburn  5668: # ---------------------------------------------------------- Domain roles
                   5669: 
                   5670: sub get_domain_roles {
                   5671:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5672:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5673:         $startdate = '.';
                   5674:     }
1.1018    raeburn  5675:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5676:         $enddate = '.';
                   5677:     }
1.922     raeburn  5678:     my $rolelist;
                   5679:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5680:         $rolelist = join('&',@{$roles});
1.922     raeburn  5681:     }
1.662     raeburn  5682:     my %personnel = ();
1.841     albertel 5683: 
                   5684:     my %servers = &get_servers($dom,'library');
                   5685:     foreach my $tryserver (keys(%servers)) {
                   5686: 	%{$personnel{$tryserver}}=();
                   5687: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5688: 					    &escape($startdate).':'.
                   5689: 					    &escape($enddate).':'.
                   5690: 					    &escape($rolelist), $tryserver))) {
                   5691: 	    my ($key,$value) = split(/\=/,$line,2);
                   5692: 	    if (($key) && ($value)) {
                   5693: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5694: 	    }
                   5695: 	}
1.662     raeburn  5696:     }
                   5697:     return %personnel;
                   5698: }
1.658     raeburn  5699: 
1.1332    raeburn  5700: sub get_active_domroles {
                   5701:     my ($dom,$roles) = @_;
                   5702:     return () unless (ref($roles) eq 'ARRAY');
                   5703:     my $now = time;
                   5704:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5705:     my %domroles;
                   5706:     foreach my $server (keys(%dompersonnel)) {
                   5707:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5708:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5709:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5710:         }
                   5711:     }
                   5712:     return %domroles;
                   5713: }
                   5714: 
1.1057    www      5715: # ----------------------------------------------------------- Interval timing 
1.149     www      5716: 
1.1153    www      5717: {
                   5718: # Caches needed for speedup of navmaps
                   5719: # We don't want to cache this for very long at all (5 seconds at most)
                   5720: # 
                   5721: # The user for whom we cache
                   5722: my $cachedkey='';
                   5723: # The cached times for this user
                   5724: my %cachedtimes=();
                   5725: # When this was last done
1.1282    raeburn  5726: my $cachedtime='';
1.1153    www      5727: 
                   5728: sub load_all_first_access {
1.1308    raeburn  5729:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5730:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5731:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5732:         (!$ignorecache)) {
1.1154    raeburn  5733:         return;
                   5734:     }
                   5735:     $cachedtime=time;
                   5736:     $cachedkey=$uname.':'.$udom;
                   5737:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5738: }
                   5739: 
1.504     albertel 5740: sub get_first_access {
1.1308    raeburn  5741:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5742:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5743:     if ($argsymb) { $symb=$argsymb; }
                   5744:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5745:     if ($argmap) { $map = $argmap; }
1.926     albertel 5746:     if ($type eq 'course') {
                   5747: 	$res='course';
                   5748:     } elsif ($type eq 'map') {
1.588     albertel 5749: 	$res=&symbread($map);
                   5750:     } else {
                   5751: 	$res=$symb;
                   5752:     }
1.1308    raeburn  5753:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5754:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5755: }
                   5756: 
                   5757: sub set_first_access {
1.1162    raeburn  5758:     my ($type,$interval)=@_;
1.790     albertel 5759:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5760:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5761:     if ($type eq 'course') {
                   5762: 	$res='course';
                   5763:     } elsif ($type eq 'map') {
1.588     albertel 5764: 	$res=&symbread($map);
                   5765:     } else {
                   5766: 	$res=$symb;
                   5767:     }
1.1153    www      5768:     $cachedkey='';
1.1162    raeburn  5769:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5770:     if ($firstaccess) {
                   5771:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5772:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5773:                  "in $courseid");
1.1386    raeburn  5774:         return 'already_set';
                   5775:     } else {
1.1162    raeburn  5776:         my $start = time;
                   5777: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5778:                           $udom,$uname);
                   5779:         if ($putres eq 'ok') {
                   5780:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5781:                  $udom,$uname); 
                   5782:             &appenv(
                   5783:                      {
                   5784:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5785:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5786:                      }
                   5787:                   );
1.1365    raeburn  5788:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5789:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5790:             }
1.1386    raeburn  5791:         } elsif ($putres ne 'refused') {
                   5792:             &logthis("Result: $putres when attempting to set first access time ".
                   5793:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5794:         }
                   5795:         return $putres;
1.505     albertel 5796:     }
                   5797:     return 'already_set';
1.504     albertel 5798: }
1.1153    www      5799: }
1.1282    raeburn  5800: 
1.110     www      5801: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5802: 
                   5803: sub expirespread {
                   5804:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5805:     my $cid=$env{'request.course.id'}; 
1.110     www      5806:     if ($cid) {
                   5807:        my $now=time;
                   5808:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5809:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5810:                             $env{'course.'.$cid.'.num'}.
1.110     www      5811: 	        	    ':nohist_expirationdates:'.
                   5812:                             &escape($key).'='.$now,
1.620     albertel 5813:                             $env{'course.'.$cid.'.home'})
1.110     www      5814:     }
                   5815:     return 'ok';
1.14      www      5816: }
                   5817: 
1.109     www      5818: # ----------------------------------------------------- Devalidate Spreadsheets
                   5819: 
                   5820: sub devalidate {
1.325     www      5821:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5822:     my $cid=$env{'request.course.id'}; 
1.109     www      5823:     if ($cid) {
1.391     matthew  5824:         # delete the stored spreadsheets for
                   5825:         # - the student level sheet of this user in course's homespace
                   5826:         # - the assessment level sheet for this resource 
                   5827:         #   for this user in user's homespace
1.553     albertel 5828: 	# - current conditional state info
1.325     www      5829: 	my $key=$uname.':'.$udom.':';
1.109     www      5830:         my $status=
1.299     matthew  5831: 	    &del('nohist_calculatedsheets',
1.391     matthew  5832: 		 [$key.'studentcalc:'],
1.620     albertel 5833: 		 $env{'course.'.$cid.'.domain'},
                   5834: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5835: 		.' '.
                   5836: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5837: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5838:         unless ($status eq 'ok ok') {
                   5839:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5840:                     $uname.' at '.$udom.' for '.
1.109     www      5841: 		    $symb.': '.$status);
1.133     albertel 5842:         }
1.553     albertel 5843: 	&delenv('user.state.'.$cid);
1.109     www      5844:     }
                   5845: }
                   5846: 
1.265     albertel 5847: sub get_scalar {
                   5848:     my ($string,$end) = @_;
                   5849:     my $value;
                   5850:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5851: 	$value = $1;
                   5852:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5853: 	$value = $1;
                   5854:     }
                   5855:     return &unescape($value);
                   5856: }
                   5857: 
                   5858: sub array2str {
                   5859:   my (@array) = @_;
                   5860:   my $result=&arrayref2str(\@array);
                   5861:   $result=~s/^__ARRAY_REF__//;
                   5862:   $result=~s/__END_ARRAY_REF__$//;
                   5863:   return $result;
                   5864: }
                   5865: 
1.204     albertel 5866: sub arrayref2str {
                   5867:   my ($arrayref) = @_;
1.265     albertel 5868:   my $result='__ARRAY_REF__';
1.204     albertel 5869:   foreach my $elem (@$arrayref) {
1.265     albertel 5870:     if(ref($elem) eq 'ARRAY') {
                   5871:       $result.=&arrayref2str($elem).'&';
                   5872:     } elsif(ref($elem) eq 'HASH') {
                   5873:       $result.=&hashref2str($elem).'&';
                   5874:     } elsif(ref($elem)) {
                   5875:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5876:     } else {
                   5877:       $result.=&escape($elem).'&';
                   5878:     }
                   5879:   }
                   5880:   $result=~s/\&$//;
1.265     albertel 5881:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5882:   return $result;
                   5883: }
                   5884: 
1.168     albertel 5885: sub hash2str {
1.204     albertel 5886:   my (%hash) = @_;
                   5887:   my $result=&hashref2str(\%hash);
1.265     albertel 5888:   $result=~s/^__HASH_REF__//;
                   5889:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5890:   return $result;
                   5891: }
                   5892: 
                   5893: sub hashref2str {
                   5894:   my ($hashref)=@_;
1.265     albertel 5895:   my $result='__HASH_REF__';
1.800     albertel 5896:   foreach my $key (sort(keys(%$hashref))) {
                   5897:     if (ref($key) eq 'ARRAY') {
                   5898:       $result.=&arrayref2str($key).'=';
                   5899:     } elsif (ref($key) eq 'HASH') {
                   5900:       $result.=&hashref2str($key).'=';
                   5901:     } elsif (ref($key)) {
1.265     albertel 5902:       $result.='=';
1.800     albertel 5903:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5904:     } else {
1.1132    raeburn  5905: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5906:     }
                   5907: 
1.800     albertel 5908:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5909:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5910:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5911:       $result.=&hashref2str($hashref->{$key}).'&';
                   5912:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5913:        $result.='&';
1.800     albertel 5914:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5915:     } else {
1.800     albertel 5916:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5917:     }
                   5918:   }
1.168     albertel 5919:   $result=~s/\&$//;
1.265     albertel 5920:   $result .= '__END_HASH_REF__';
1.168     albertel 5921:   return $result;
                   5922: }
                   5923: 
                   5924: sub str2hash {
1.265     albertel 5925:     my ($string)=@_;
                   5926:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5927:     return %$hash;
                   5928: }
                   5929: 
                   5930: sub str2hashref {
1.168     albertel 5931:   my ($string) = @_;
1.265     albertel 5932: 
                   5933:   my %hash;
                   5934: 
                   5935:   if($string !~ /^__HASH_REF__/) {
                   5936:       if (! ($string eq '' || !defined($string))) {
                   5937: 	  $hash{'error'}='Not hash reference';
                   5938:       }
                   5939:       return (\%hash, $string);
                   5940:   }
                   5941: 
                   5942:   $string =~ s/^__HASH_REF__//;
                   5943: 
                   5944:   while($string !~ /^__END_HASH_REF__/) {
                   5945:       #key
                   5946:       my $key='';
                   5947:       if($string =~ /^__HASH_REF__/) {
                   5948:           ($key, $string)=&str2hashref($string);
                   5949:           if(defined($key->{'error'})) {
                   5950:               $hash{'error'}='Bad data';
                   5951:               return (\%hash, $string);
                   5952:           }
                   5953:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5954:           ($key, $string)=&str2arrayref($string);
                   5955:           if($key->[0] eq 'Array reference error') {
                   5956:               $hash{'error'}='Bad data';
                   5957:               return (\%hash, $string);
                   5958:           }
                   5959:       } else {
                   5960:           $string =~ s/^(.*?)=//;
1.267     albertel 5961: 	  $key=&unescape($1);
1.265     albertel 5962:       }
                   5963:       $string =~ s/^=//;
                   5964: 
                   5965:       #value
                   5966:       my $value='';
                   5967:       if($string =~ /^__HASH_REF__/) {
                   5968:           ($value, $string)=&str2hashref($string);
                   5969:           if(defined($value->{'error'})) {
                   5970:               $hash{'error'}='Bad data';
                   5971:               return (\%hash, $string);
                   5972:           }
                   5973:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5974:           ($value, $string)=&str2arrayref($string);
                   5975:           if($value->[0] eq 'Array reference error') {
                   5976:               $hash{'error'}='Bad data';
                   5977:               return (\%hash, $string);
                   5978:           }
                   5979:       } else {
                   5980: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5981:       }
                   5982:       $string =~ s/^&//;
                   5983: 
                   5984:       $hash{$key}=$value;
1.204     albertel 5985:   }
1.265     albertel 5986: 
                   5987:   $string =~ s/^__END_HASH_REF__//;
                   5988: 
                   5989:   return (\%hash, $string);
1.204     albertel 5990: }
                   5991: 
                   5992: sub str2array {
1.265     albertel 5993:     my ($string)=@_;
                   5994:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5995:     return @$array;
                   5996: }
                   5997: 
                   5998: sub str2arrayref {
1.204     albertel 5999:   my ($string) = @_;
1.265     albertel 6000:   my @array;
                   6001: 
                   6002:   if($string !~ /^__ARRAY_REF__/) {
                   6003:       if (! ($string eq '' || !defined($string))) {
                   6004: 	  $array[0]='Array reference error';
                   6005:       }
                   6006:       return (\@array, $string);
                   6007:   }
                   6008: 
                   6009:   $string =~ s/^__ARRAY_REF__//;
                   6010: 
                   6011:   while($string !~ /^__END_ARRAY_REF__/) {
                   6012:       my $value='';
                   6013:       if($string =~ /^__HASH_REF__/) {
                   6014:           ($value, $string)=&str2hashref($string);
                   6015:           if(defined($value->{'error'})) {
                   6016:               $array[0] ='Array reference error';
                   6017:               return (\@array, $string);
                   6018:           }
                   6019:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6020:           ($value, $string)=&str2arrayref($string);
                   6021:           if($value->[0] eq 'Array reference error') {
                   6022:               $array[0] ='Array reference error';
                   6023:               return (\@array, $string);
                   6024:           }
                   6025:       } else {
                   6026: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6027:       }
                   6028:       $string =~ s/^&//;
                   6029: 
                   6030:       push(@array, $value);
1.191     harris41 6031:   }
1.265     albertel 6032: 
                   6033:   $string =~ s/^__END_ARRAY_REF__//;
                   6034: 
                   6035:   return (\@array, $string);
1.168     albertel 6036: }
                   6037: 
1.167     albertel 6038: # -------------------------------------------------------------------Temp Store
                   6039: 
1.168     albertel 6040: sub tmpreset {
                   6041:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6042:   if (!$symb) {
                   6043:     $symb=&symbread();
1.620     albertel 6044:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6045:   }
                   6046:   $symb=escape($symb);
                   6047: 
1.620     albertel 6048:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6049:   $namespace=~s/\//\_/g;
                   6050:   $namespace=~s/\W//g;
                   6051: 
1.620     albertel 6052:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6053:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6054:   if ($domain eq 'public' && $stuname eq 'public') {
                   6055:       $stuname=$ENV{'REMOTE_ADDR'};
                   6056:   }
1.1117    foxr     6057:   my $path=LONCAPA::tempdir();
1.168     albertel 6058:   my %hash;
                   6059:   if (tie(%hash,'GDBM_File',
                   6060: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6061: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6062:     foreach my $key (keys(%hash)) {
1.180     albertel 6063:       if ($key=~ /:$symb/) {
1.168     albertel 6064: 	delete($hash{$key});
                   6065:       }
                   6066:     }
                   6067:   }
                   6068: }
                   6069: 
1.167     albertel 6070: sub tmpstore {
1.168     albertel 6071:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6072: 
                   6073:   if (!$symb) {
                   6074:     $symb=&symbread();
1.620     albertel 6075:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6076:   }
                   6077:   $symb=escape($symb);
                   6078: 
                   6079:   if (!$namespace) {
                   6080:     # I don't think we would ever want to store this for a course.
                   6081:     # it seems this will only be used if we don't have a course.
1.620     albertel 6082:     #$namespace=$env{'request.course.id'};
1.168     albertel 6083:     #if (!$namespace) {
1.620     albertel 6084:       $namespace=$env{'request.state'};
1.168     albertel 6085:     #}
                   6086:   }
                   6087:   $namespace=~s/\//\_/g;
                   6088:   $namespace=~s/\W//g;
1.620     albertel 6089:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6090:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6091:   if ($domain eq 'public' && $stuname eq 'public') {
                   6092:       $stuname=$ENV{'REMOTE_ADDR'};
                   6093:   }
1.168     albertel 6094:   my $now=time;
                   6095:   my %hash;
1.1117    foxr     6096:   my $path=LONCAPA::tempdir();
1.168     albertel 6097:   if (tie(%hash,'GDBM_File',
                   6098: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6099: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6100:     $hash{"version:$symb"}++;
                   6101:     my $version=$hash{"version:$symb"};
                   6102:     my $allkeys=''; 
                   6103:     foreach my $key (keys(%$storehash)) {
                   6104:       $allkeys.=$key.':';
1.591     albertel 6105:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6106:     }
                   6107:     $hash{"$version:$symb:timestamp"}=$now;
                   6108:     $allkeys.='timestamp';
                   6109:     $hash{"$version:keys:$symb"}=$allkeys;
                   6110:     if (untie(%hash)) {
                   6111:       return 'ok';
                   6112:     } else {
                   6113:       return "error:$!";
                   6114:     }
                   6115:   } else {
                   6116:     return "error:$!";
                   6117:   }
                   6118: }
1.167     albertel 6119: 
1.168     albertel 6120: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6121: 
1.168     albertel 6122: sub tmprestore {
                   6123:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6124: 
1.168     albertel 6125:   if (!$symb) {
                   6126:     $symb=&symbread();
1.620     albertel 6127:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6128:   }
                   6129:   $symb=escape($symb);
                   6130: 
1.620     albertel 6131:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6132: 
1.620     albertel 6133:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6134:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6135:   if ($domain eq 'public' && $stuname eq 'public') {
                   6136:       $stuname=$ENV{'REMOTE_ADDR'};
                   6137:   }
1.168     albertel 6138:   my %returnhash;
                   6139:   $namespace=~s/\//\_/g;
                   6140:   $namespace=~s/\W//g;
                   6141:   my %hash;
1.1117    foxr     6142:   my $path=LONCAPA::tempdir();
1.168     albertel 6143:   if (tie(%hash,'GDBM_File',
                   6144: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6145: 	  &GDBM_READER(),0640)) {
1.168     albertel 6146:     my $version=$hash{"version:$symb"};
                   6147:     $returnhash{'version'}=$version;
                   6148:     my $scope;
                   6149:     for ($scope=1;$scope<=$version;$scope++) {
                   6150:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6151:       my @keys=split(/:/,$vkeys);
                   6152:       my $key;
                   6153:       $returnhash{"$scope:keys"}=$vkeys;
                   6154:       foreach $key (@keys) {
1.591     albertel 6155: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6156: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6157:       }
                   6158:     }
1.168     albertel 6159:     if (!(untie(%hash))) {
                   6160:       return "error:$!";
                   6161:     }
                   6162:   } else {
                   6163:     return "error:$!";
                   6164:   }
                   6165:   return %returnhash;
1.167     albertel 6166: }
                   6167: 
1.9       www      6168: # ----------------------------------------------------------------------- Store
                   6169: 
                   6170: sub store {
1.1269    raeburn  6171:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6172:     my $home='';
                   6173: 
1.168     albertel 6174:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6175: 
1.213     www      6176:     $symb=&symbclean($symb);
1.122     albertel 6177:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6178: 
1.620     albertel 6179:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6180:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6181: 
                   6182:     &devalidate($symb,$stuname,$domain);
1.109     www      6183: 
                   6184:     $symb=escape($symb);
1.187     www      6185:     if (!$namespace) { 
1.620     albertel 6186:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6187:           return ''; 
                   6188:        } 
                   6189:     }
1.620     albertel 6190:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6191: 
                   6192:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6193:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6194: 
1.12      www      6195:     my $namevalue='';
1.800     albertel 6196:     foreach my $key (keys(%$storehash)) {
                   6197:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6198:     }
1.12      www      6199:     $namevalue=~s/\&$//;
1.187     www      6200:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6201:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6202: }
                   6203: 
1.47      www      6204: # -------------------------------------------------------------- Critical Store
                   6205: 
                   6206: sub cstore {
1.1269    raeburn  6207:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6208:     my $home='';
                   6209: 
1.168     albertel 6210:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6211: 
1.213     www      6212:     $symb=&symbclean($symb);
1.122     albertel 6213:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6214: 
1.620     albertel 6215:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6216:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6217: 
                   6218:     &devalidate($symb,$stuname,$domain);
1.109     www      6219: 
                   6220:     $symb=escape($symb);
1.187     www      6221:     if (!$namespace) { 
1.620     albertel 6222:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6223:           return ''; 
                   6224:        } 
                   6225:     }
1.620     albertel 6226:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6227: 
                   6228:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6229:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6230: 
1.47      www      6231:     my $namevalue='';
1.800     albertel 6232:     foreach my $key (keys(%$storehash)) {
                   6233:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6234:     }
1.47      www      6235:     $namevalue=~s/\&$//;
1.187     www      6236:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6237:     return critical
1.1269    raeburn  6238:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6239: }
                   6240: 
1.9       www      6241: # --------------------------------------------------------------------- Restore
                   6242: 
                   6243: sub restore {
1.124     www      6244:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6245:     my $home='';
                   6246: 
1.168     albertel 6247:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6248: 
1.122     albertel 6249:     if (!$symb) {
1.1224    raeburn  6250:         return if ($namespace eq 'courserequests');
                   6251:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6252:     } else {
1.1224    raeburn  6253:         unless ($namespace eq 'courserequests') {
                   6254:             $symb=&escape(&symbclean($symb));
                   6255:         }
1.122     albertel 6256:     }
1.188     www      6257:     if (!$namespace) { 
1.620     albertel 6258:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6259:           return ''; 
                   6260:        } 
                   6261:     }
1.620     albertel 6262:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6263:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6264:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6265:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6266: 
1.12      www      6267:     my %returnhash=();
1.800     albertel 6268:     foreach my $line (split(/\&/,$answer)) {
                   6269: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6270:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6271:     }
1.75      www      6272:     my $version;
                   6273:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6274:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6275:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6276:        }
1.75      www      6277:     }
1.13      www      6278:     return %returnhash;
1.34      www      6279: }
                   6280: 
                   6281: # ---------------------------------------------------------- Course Description
1.1118    foxr     6282: #
                   6283: #  
1.34      www      6284: 
                   6285: sub coursedescription {
1.731     albertel 6286:     my ($courseid,$args)=@_;
1.34      www      6287:     $courseid=~s/^\///;
1.49      www      6288:     $courseid=~s/\_/\//g;
1.34      www      6289:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6290:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6291:     my $normalid=$cdomain.'_'.$cnum;
                   6292:     # need to always cache even if we get errors otherwise we keep 
                   6293:     # trying and trying and trying to get the course description.
                   6294:     my %envhash=();
                   6295:     my %returnhash=();
1.731     albertel 6296:     
                   6297:     my $expiretime=600;
                   6298:     if ($env{'request.course.id'} eq $normalid) {
                   6299: 	$expiretime=120;
                   6300:     }
                   6301: 
                   6302:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6303:     if (!$args->{'freshen_cache'}
                   6304: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6305: 	foreach my $key (keys(%env)) {
                   6306: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6307: 	    my ($setting) = $1;
                   6308: 	    $returnhash{$setting} = $env{$key};
                   6309: 	}
                   6310: 	return %returnhash;
                   6311:     }
                   6312: 
1.1118    foxr     6313:     # get the data again
                   6314: 
1.731     albertel 6315:     if (!$args->{'one_time'}) {
                   6316: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6317:     }
1.811     albertel 6318: 
1.34      www      6319:     if ($chome ne 'no_host') {
1.302     albertel 6320:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6321:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6322: 	   my $username = $env{'user.name'}; # Defult username
                   6323: 	   if(defined $args->{'user'}) {
                   6324: 	       $username = $args->{'user'};
                   6325: 	   }
1.129     albertel 6326:            $returnhash{'home'}= $chome;
                   6327: 	   $returnhash{'domain'} = $cdomain;
                   6328: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6329:            if (!defined($returnhash{'type'})) {
                   6330:                $returnhash{'type'} = 'Course';
                   6331:            }
1.130     albertel 6332:            while (my ($name,$value) = each %returnhash) {
1.53      www      6333:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6334:            }
1.270     www      6335:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6336:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6337: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6338:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6339:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6340:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6341:        }
                   6342:     }
1.731     albertel 6343:     if (!$args->{'one_time'}) {
1.949     raeburn  6344: 	&appenv(\%envhash);
1.731     albertel 6345:     }
1.302     albertel 6346:     return %returnhash;
1.461     www      6347: }
                   6348: 
1.1080    raeburn  6349: sub update_released_required {
                   6350:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6351:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6352:         $cid = $env{'request.course.id'};
                   6353:         $cdom = $env{'course.'.$cid.'.domain'};
                   6354:         $cnum = $env{'course.'.$cid.'.num'};
                   6355:         $chome = $env{'course.'.$cid.'.home'};
                   6356:     }
                   6357:     if ($needsrelease) {
                   6358:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6359:         my $needsupdate;
                   6360:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6361:             $needsupdate = 1;
                   6362:         } else {
                   6363:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6364:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6365:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6366:                 $needsupdate = 1;
                   6367:             }
                   6368:         }
                   6369:         if ($needsupdate) {
                   6370:             my %needshash = (
                   6371:                              'internal.releaserequired' => $needsrelease,
                   6372:                             );
                   6373:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6374:             if ($putresult eq 'ok') {
                   6375:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6376:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6377:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6378:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6379:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6380:                 }
                   6381:             }
                   6382:         }
                   6383:     }
                   6384:     return;
                   6385: }
                   6386: 
1.461     www      6387: # -------------------------------------------------See if a user is privileged
                   6388: 
                   6389: sub privileged {
1.1219    raeburn  6390:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6391:     my $now = time;
1.1219    raeburn  6392:     my $roles;
                   6393:     if (ref($possroles) eq 'ARRAY') {
                   6394:         $roles = $possroles; 
                   6395:     } else {
                   6396:         $roles = ['dc','su'];
                   6397:     }
                   6398:     if (ref($possdomains) eq 'ARRAY') {
                   6399:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6400:         foreach my $dom (@{$possdomains}) {
                   6401:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6402:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6403:                 foreach my $role (@{$roles}) {
                   6404:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6405:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6406:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6407:                             return 1 unless (($end && $end < $now) ||
                   6408:                                              ($start && $start > $now));
                   6409:                         }
                   6410:                     }
                   6411:                 }
                   6412:             }
                   6413:         }
                   6414:     } else {
                   6415:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6416:         my $now = time;
1.1170    droeschl 6417: 
1.1275    musolffc 6418:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6419:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6420:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6421:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6422:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6423:             }
1.1219    raeburn  6424:         }
                   6425:     }
                   6426:     return 0;
                   6427: }
1.1170    droeschl 6428: 
1.1219    raeburn  6429: sub privileged_by_domain {
                   6430:     my ($domains,$roles) = @_;
                   6431:     my %privileged = ();
                   6432:     my $cachetime = 60*60*24;
                   6433:     my $now = time;
                   6434:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6435:         return %privileged;
                   6436:     }
                   6437:     foreach my $dom (@{$domains}) {
                   6438:         next if (ref($privileged{$dom}) eq 'HASH');
                   6439:         my $needroles;
                   6440:         foreach my $role (@{$roles}) {
                   6441:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6442:             if (defined($cached)) {
                   6443:                 if (ref($result) eq 'HASH') {
                   6444:                     $privileged{$dom}{$role} = $result;
                   6445:                 }
                   6446:             } else {
                   6447:                 $needroles = 1;
                   6448:             }
                   6449:         }
                   6450:         if ($needroles) {
                   6451:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6452:             $privileged{$dom} = {};
                   6453:             foreach my $server (keys(%dompersonnel)) {
                   6454:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6455:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6456:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6457:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6458:                         next if ($end && $end < $now);
                   6459:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6460:                             $dompersonnel{$server}{$item};
                   6461:                     }
                   6462:                 }
                   6463:             }
                   6464:             if (ref($privileged{$dom}) eq 'HASH') {
                   6465:                 foreach my $role (@{$roles}) {
                   6466:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6467:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6468:                     } else {
                   6469:                         my %hash = ();
                   6470:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6471:                     }
                   6472:                 }
                   6473:             }
                   6474:         }
                   6475:     }
                   6476:     return %privileged;
1.9       www      6477: }
1.1       albertel 6478: 
1.103     harris41 6479: # -------------------------------------------------------- Get user privileges
1.11      www      6480: 
                   6481: sub rolesinit {
1.1169    droeschl 6482:     my ($domain, $username) = @_;
                   6483:     my %userroles = ('user.login.time' => time);
                   6484:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6485: 
                   6486:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6487:     # also, blocking can be triggered by an activating timer
                   6488:     # it's saved in the user's %env.
                   6489:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6490:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6491:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6492:         %timerintchk, %timerintenv);
                   6493: 
1.1162    raeburn  6494:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6495:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6496:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6497:     }
1.1169    droeschl 6498: 
1.1162    raeburn  6499:     foreach my $key (keys(%timerinterval)) {
                   6500:         my ($cid,$rest) = split(/\0/,$key);
                   6501:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6502:     }
1.1169    droeschl 6503: 
1.11      www      6504:     my %allroles=();
1.1162    raeburn  6505:     my %allgroups=();
1.11      www      6506: 
1.1274    raeburn  6507:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6508:         my $role = $rolesdump{$area};
                   6509:         $area =~ s/\_\w\w$//;
                   6510: 
                   6511:         my ($trole, $tend, $tstart, $group_privs);
                   6512: 
                   6513:         if ($role =~ /^cr/) {
                   6514:         # Custom role, defined by a user 
                   6515:         # e.g., user.role.cr/msu/smith/mynewrole
                   6516:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6517:                 $trole = $1;
                   6518:                 ($tend, $tstart) = split('_', $2);
                   6519:             } else {
                   6520:                 $trole = $role;
                   6521:             }
                   6522:         } elsif ($role =~ m|^gr/|) {
                   6523:         # Role of member in a group, defined within a course/community
                   6524:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6525:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6526:             next if $tstart eq '-1';
                   6527:             ($trole, $group_privs) = split(/\//, $trole);
                   6528:             $group_privs = &unescape($group_privs);
                   6529:         } else {
                   6530:         # Just a normal role, defined in roles.tab
                   6531:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6532:         }
                   6533: 
                   6534:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6535:                  $username);
                   6536:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6537: 
                   6538:         # role expired or not available yet?
                   6539:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6540:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6541: 
                   6542:         next if $area eq '' or $trole eq '';
                   6543: 
                   6544:         my $spec = "$trole.$area";
                   6545:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6546: 
                   6547:         if ($trole =~ /^cr\//) {
                   6548:         # Custom role, defined by a user
                   6549:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6550:         } elsif ($trole eq 'gr') {
                   6551:         # Role of a member in a group, defined within a course/community
                   6552:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6553:             next;
                   6554:         } else {
                   6555:         # Normal role, defined in roles.tab
                   6556:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6557:         }
                   6558: 
                   6559:         my $cid = $tdomain.'_'.$trest;
                   6560:         unless ($firstaccchk{$cid}) {
                   6561:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6562:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6563:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6564:                         $coursetimerstarts{$cid}{$item}; 
                   6565:                 }
                   6566:             }
                   6567:             $firstaccchk{$cid} = 1;
                   6568:         }
                   6569:         unless ($timerintchk{$cid}) {
                   6570:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6571:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6572:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6573:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6574:                 }
1.12      www      6575:             }
1.1169    droeschl 6576:             $timerintchk{$cid} = 1;
1.191     harris41 6577:         }
1.11      www      6578:     }
1.1169    droeschl 6579: 
1.1341    raeburn  6580:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6581:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6582:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6583:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6584: 
1.1162    raeburn  6585:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6586: }
                   6587: 
1.567     raeburn  6588: sub set_arearole {
1.1215    raeburn  6589:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6590:     unless ($nolog) {
1.567     raeburn  6591: # log the associated role with the area
1.1215    raeburn  6592:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6593:     }
1.743     albertel 6594:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6595: }
                   6596: 
                   6597: sub custom_roleprivs {
                   6598:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6599:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6600:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6601:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6602:         my ($rdummy,$roledef)=
                   6603:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6604:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6605:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6606:             if (defined($syspriv)) {
1.1043    raeburn  6607:                 if ($trest =~ /^$match_community$/) {
                   6608:                     $syspriv =~ s/bre\&S//; 
                   6609:                 }
1.567     raeburn  6610:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6611:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6612:             }
                   6613:             if ($tdomain ne '') {
                   6614:                 if (defined($dompriv)) {
                   6615:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6616:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6617:                 }
                   6618:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6619:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6620:                         my $rolename = $1;
                   6621:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6622:                     }
1.567     raeburn  6623:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6624:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6625:                 }
                   6626:             }
                   6627:         }
                   6628:     }
                   6629: }
                   6630: 
1.1332    raeburn  6631: sub course_adhocrole_privs {
                   6632:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6633:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6634:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6635:         my (%currprivs,%storeprivs);
                   6636:         foreach my $item (split(/:/,$coursepriv)) {
                   6637:             my ($priv,$restrict) = split(/\&/,$item);
                   6638:             $currprivs{$priv} = $restrict;
                   6639:         }
                   6640:         my (%possadd,%possremove,%full);
                   6641:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6642:             my ($priv,$restrict)=split(/\&/,$item);
                   6643:             $full{$priv} = $restrict;
                   6644:         }
                   6645:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6646:              next if ($item eq '');
                   6647:              my ($rule,$rest) = split(/=/,$item);
                   6648:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6649:              foreach my $priv (split(/:/,$rest)) {
                   6650:                  if ($priv ne '') {
                   6651:                      if ($rule eq 'off') {
                   6652:                          $possremove{$priv} = 1;
                   6653:                      } else {
                   6654:                          $possadd{$priv} = 1;
                   6655:                      }
                   6656:                  }
                   6657:              }
                   6658:          }
                   6659:          foreach my $priv (sort(keys(%full))) {
                   6660:              if (exists($currprivs{$priv})) {
                   6661:                  unless (exists($possremove{$priv})) {
                   6662:                      $storeprivs{$priv} = $currprivs{$priv};
                   6663:                  }
                   6664:              } elsif (exists($possadd{$priv})) {
                   6665:                  $storeprivs{$priv} = $full{$priv};
                   6666:              }
                   6667:          }
                   6668:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6669:      }
                   6670:      return $coursepriv;
                   6671: }
                   6672: 
1.678     raeburn  6673: sub group_roleprivs {
                   6674:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6675:     my $access = 1;
                   6676:     my $now = time;
                   6677:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6678:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6679:     if ($access) {
1.811     albertel 6680:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6681:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6682:     }
                   6683: }
1.567     raeburn  6684: 
                   6685: sub standard_roleprivs {
                   6686:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6687:     if (defined($pr{$trole.':s'})) {
                   6688:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6689:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6690:     }
                   6691:     if ($tdomain ne '') {
                   6692:         if (defined($pr{$trole.':d'})) {
                   6693:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6694:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6695:         }
                   6696:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6697:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6698:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6699:         }
                   6700:     }
                   6701: }
                   6702: 
                   6703: sub set_userprivs {
1.1064    raeburn  6704:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6705:     my $author=0;
                   6706:     my $adv=0;
1.1341    raeburn  6707:     my $rar=0;
1.678     raeburn  6708:     my %grouproles = ();
                   6709:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6710:         my @groupkeys; 
1.1000    raeburn  6711:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6712:             push(@groupkeys,$role);
                   6713:         }
                   6714:         if (ref($groups_roles) eq 'HASH') {
                   6715:             foreach my $key (keys(%{$groups_roles})) {
                   6716:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6717:                     push(@groupkeys,$key);
                   6718:                 }
                   6719:             }
                   6720:         }
                   6721:         if (@groupkeys > 0) {
                   6722:             foreach my $role (@groupkeys) {
                   6723:                 my ($trole,$area,$sec,$extendedarea);
                   6724:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6725:                     $trole = $1;
                   6726:                     $area = $2;
                   6727:                     $sec = $3;
                   6728:                     $extendedarea = $area.$sec;
                   6729:                     if (exists($$allgroups{$area})) {
                   6730:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6731:                             my $spec = $trole.'.'.$extendedarea;
                   6732:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6733:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6734:                         }
1.678     raeburn  6735:                     }
                   6736:                 }
                   6737:             }
                   6738:         }
                   6739:     }
1.800     albertel 6740:     foreach my $group (keys(%grouproles)) {
                   6741:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6742:     }
1.800     albertel 6743:     foreach my $role (keys(%{$allroles})) {
                   6744:         my %thesepriv;
1.941     raeburn  6745:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6746:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6747:             if ($item ne '') {
                   6748:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6749:                 if ($restrictions eq '') {
                   6750:                     $thesepriv{$privilege}='F';
                   6751:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6752:                     $thesepriv{$privilege}.=$restrictions;
                   6753:                 }
                   6754:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6755:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6756:             }
                   6757:         }
                   6758:         my $thesestr='';
1.1104    raeburn  6759:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6760: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6761: 	}
                   6762:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6763:     }
1.1341    raeburn  6764:     return ($author,$adv,$rar);
1.567     raeburn  6765: }
                   6766: 
1.994     raeburn  6767: sub role_status {
1.1104    raeburn  6768:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6769:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6770:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6771:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6772:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6773:             $$where = '/'.$two;
1.994     raeburn  6774:             $$trolecode=$$role.'.'.$$where;
                   6775:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6776:             $$tstatus='is';
1.1104    raeburn  6777:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6778:                 $$tstatus='future';
1.1034    raeburn  6779:                 if ($$tstart<$now) {
                   6780:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6781:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6782:                             my (%allroles,%allgroups,$group_privs,
                   6783:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6784:                             my %userroles = (
                   6785:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6786:                             );
1.1064    raeburn  6787:                             @rolecodes = ('cm'); 
1.1002    raeburn  6788:                             my $spec=$$role.'.'.$$where;
                   6789:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6790:                             if ($$role =~ /^cr\//) {
                   6791:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6792:                                 push(@rolecodes,'cr');
1.1002    raeburn  6793:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6794:                                 push(@rolecodes,$$role);
1.1002    raeburn  6795:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6796:                                                     $env{'user.name'});
1.1064    raeburn  6797:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6798:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6799:                                 $group_privs = &unescape($group_privs);
                   6800:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6801:                                 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  6802:                                 &get_groups_roles($tdomain,$trest,
                   6803:                                                   \%course_roles,\@rolecodes,
                   6804:                                                   \%groups_roles);
1.1002    raeburn  6805:                             } else {
1.1064    raeburn  6806:                                 push(@rolecodes,$$role);
1.1002    raeburn  6807:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6808:                             }
1.1341    raeburn  6809:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6810:                                                                    \%groups_roles);
1.1064    raeburn  6811:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6812:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6813:                         }
                   6814:                     }
1.1034    raeburn  6815:                     $$tstatus = 'is';
1.1002    raeburn  6816:                 }
1.994     raeburn  6817:             }
                   6818:             if ($$tend) {
1.1104    raeburn  6819:                 if ($$tend<$update) {
1.994     raeburn  6820:                     $$tstatus='expired';
                   6821:                 } elsif ($$tend<$now) {
                   6822:                     $$tstatus='will_not';
                   6823:                 }
                   6824:             }
                   6825:         }
                   6826:     }
                   6827: }
                   6828: 
1.1104    raeburn  6829: sub get_groups_roles {
                   6830:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6831:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6832:                   (ref($rolecodes) eq 'ARRAY') && 
                   6833:                   (ref($groups_roles) eq 'HASH')); 
                   6834:     if (keys(%{$cdom_courseroles}) > 0) {
                   6835:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6836:         if ($cdom ne '' && $cnum ne '') {
                   6837:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6838:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6839:                     my $crsrole = $1;
                   6840:                     my $crssec = $2;
                   6841:                     if ($crsrole =~ /^cr/) {
                   6842:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6843:                             push(@{$rolecodes},'cr');
                   6844:                         }
                   6845:                     } else {
                   6846:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6847:                             push(@{$rolecodes},$crsrole);
                   6848:                         }
                   6849:                     }
                   6850:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6851:                     if ($crssec ne '') {
                   6852:                         $rolekey .= "/$crssec";
                   6853:                     }
                   6854:                     $rolekey .= './';
                   6855:                     $groups_roles->{$rolekey} = $rolecodes;
                   6856:                 }
                   6857:             }
                   6858:         }
                   6859:     }
                   6860:     return;
                   6861: }
                   6862: 
                   6863: sub delete_env_groupprivs {
                   6864:     my ($where,$courseroles,$possroles) = @_;
                   6865:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6866:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6867:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6868:         %{$courseroles->{$udom}} =
                   6869:             &get_my_roles('','','userroles',['active'],
                   6870:                           $possroles,[$udom],1);
                   6871:     }
                   6872:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6873:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6874:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6875:             my $area = '/'.$cdom.'/'.$cnum;
                   6876:             my $privkey = "user.priv.$crsrole.$area";
                   6877:             if ($crssec ne '') {
                   6878:                 $privkey .= '/'.$crssec;
                   6879:             }
                   6880:             $privkey .= ".$area/$group";
                   6881:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6882:         }
                   6883:     }
                   6884:     return;
                   6885: }
                   6886: 
1.994     raeburn  6887: sub check_adhoc_privs {
1.1329    raeburn  6888:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6889:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6890:     if ($sec) {
                   6891:         $cckey .= '/'.$sec;
                   6892:     } 
1.1185    raeburn  6893:     my $setprivs;
1.994     raeburn  6894:     if ($env{$cckey}) {
                   6895:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6896:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6897:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6898:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6899:             $setprivs = 1;
1.994     raeburn  6900:         }
                   6901:     } else {
1.1330    raeburn  6902:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6903:         $setprivs = 1;
1.994     raeburn  6904:     }
1.1185    raeburn  6905:     return $setprivs;
1.994     raeburn  6906: }
                   6907: 
                   6908: sub set_adhoc_privileges {
1.1326    raeburn  6909: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6910:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6911:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6912:     if ($sec ne '') {
                   6913:         $area .= '/'.$sec;
                   6914:     }
1.994     raeburn  6915:     my $spec = $role.'.'.$area;
                   6916:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6917:                                   $env{'user.name'},1);
1.1326    raeburn  6918:     my %rolehash = ();
1.1332    raeburn  6919:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6920:         my $rolename = $1;
1.1326    raeburn  6921:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6922:         my %domdef = &get_domain_defaults($dcdom);
                   6923:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6924:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6925:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6926:             }
                   6927:         }
1.1326    raeburn  6928:     } else {
                   6929:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6930:     }
1.1341    raeburn  6931:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6932:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6933:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  6934:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6935:             ($caller eq 'tiny')) {
1.1088    raeburn  6936:         &appenv( {'request.role'        => $spec,
                   6937:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6938:                   'request.course.sec'  => $sec,
1.1088    raeburn  6939:                  }
                   6940:                );
                   6941:         my $tadv=0;
                   6942:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6943:         &appenv({'request.role.adv'    => $tadv});
                   6944:     }
1.994     raeburn  6945: }
                   6946: 
1.12      www      6947: # --------------------------------------------------------------- get interface
                   6948: 
                   6949: sub get {
1.131     albertel 6950:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6951:    my $items='';
1.800     albertel 6952:    foreach my $item (@$storearr) {
                   6953:        $items.=&escape($item).'&';
1.191     harris41 6954:    }
1.12      www      6955:    $items=~s/\&$//;
1.620     albertel 6956:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6957:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6958:    my $uhome=&homeserver($uname,$udomain);
                   6959: 
1.133     albertel 6960:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6961:    my @pairs=split(/\&/,$rep);
1.273     albertel 6962:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6963:      return @pairs;
                   6964:    }
1.15      www      6965:    my %returnhash=();
1.42      www      6966:    my $i=0;
1.800     albertel 6967:    foreach my $item (@$storearr) {
                   6968:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6969:       $i++;
1.191     harris41 6970:    }
1.15      www      6971:    return %returnhash;
1.27      www      6972: }
                   6973: 
                   6974: # --------------------------------------------------------------- del interface
                   6975: 
                   6976: sub del {
1.133     albertel 6977:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6978:    my $items='';
1.800     albertel 6979:    foreach my $item (@$storearr) {
                   6980:        $items.=&escape($item).'&';
1.191     harris41 6981:    }
1.984     neumanie 6982: 
1.27      www      6983:    $items=~s/\&$//;
1.620     albertel 6984:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6985:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6986:    my $uhome=&homeserver($uname,$udomain);
                   6987:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6988: }
                   6989: 
                   6990: # -------------------------------------------------------------- dump interface
                   6991: 
1.1180    droeschl 6992: sub unserialize {
                   6993:     my ($rep, $escapedkeys) = @_;
                   6994: 
                   6995:     return {} if $rep =~ /^error/;
                   6996: 
                   6997:     my %returnhash=();
1.1252    raeburn  6998: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6999: 	    my ($key, $value) = split(/=/, $item, 2);
                   7000: 	    $key = unescape($key) unless $escapedkeys;
                   7001: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7002: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7003: 	}
                   7004:     #return %returnhash;
                   7005:     return \%returnhash;
                   7006: }        
                   7007: 
                   7008: # see Lond::dump_with_regexp
                   7009: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7010: sub dump {
1.1180    droeschl 7011:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 7012:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7013:     if (!$uname) { $uname=$env{'user.name'}; }
                   7014:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7015: 
1.1266    raeburn  7016:     if ($regexp) {
                   7017:         $regexp=&escape($regexp);
                   7018:     } else {
                   7019:         $regexp='.';
                   7020:     }
1.1180    droeschl 7021:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7022:         # user is hosted on this machine
1.1266    raeburn  7023:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7024:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7025:         return %{unserialize($reply, $escapedkeys)};
                   7026:     }
1.1166    raeburn  7027:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 7028:     my @pairs=split(/\&/,$rep);
                   7029:     my %returnhash=();
1.1098    foxr     7030:     if (!($rep =~ /^error/ )) {
                   7031: 	foreach my $item (@pairs) {
                   7032: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7033:         $key = unescape($key) unless $escapedkeys;
                   7034:         #$key = &unescape($key);
1.1098    foxr     7035: 	    next if ($key =~ /^error: 2 /);
                   7036: 	    $returnhash{$key}=&thaw_unescape($value);
                   7037: 	}
1.755     albertel 7038:     }
                   7039:     return %returnhash;
1.407     www      7040: }
                   7041: 
1.1098    foxr     7042: 
1.717     albertel 7043: # --------------------------------------------------------- dumpstore interface
                   7044: 
                   7045: sub dumpstore {
                   7046:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7047:    # same as dump but keys must be escaped. They may contain colon separated
                   7048:    # lists of values that may themself contain colons (e.g. symbs).
                   7049:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7050: }
                   7051: 
1.407     www      7052: # -------------------------------------------------------------- keys interface
                   7053: 
                   7054: sub getkeys {
                   7055:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7056:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7057:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7058:    my $uhome=&homeserver($uname,$udomain);
                   7059:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7060:    my @keyarray=();
1.800     albertel 7061:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7062:       next if ($key =~ /^error: 2 /);
1.800     albertel 7063:       push(@keyarray,&unescape($key));
1.407     www      7064:    }
                   7065:    return @keyarray;
1.318     matthew  7066: }
                   7067: 
1.319     matthew  7068: # --------------------------------------------------------------- currentdump
                   7069: sub currentdump {
1.328     matthew  7070:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7071:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7072:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7073:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7074:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7075:    my $rep;
                   7076: 
                   7077:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7078:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7079:                    $courseid)));
                   7080:    } else {
                   7081:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7082:    }
                   7083: 
1.318     matthew  7084:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7085:    #
1.318     matthew  7086:    my %returnhash=();
1.319     matthew  7087:    #
1.1343    raeburn  7088:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7089:        # an old lond will not know currentdump
                   7090:        # Do a dump and make it look like a currentdump
1.822     albertel 7091:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7092:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7093:        my %hash = @tmp;
                   7094:        @tmp=();
1.424     matthew  7095:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7096:    } else {
                   7097:        my @pairs=split(/\&/,$rep);
1.800     albertel 7098:        foreach my $pair (@pairs) {
                   7099:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7100:            my ($symb,$param) = split(/:/,$key);
                   7101:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7102:                                                         &thaw_unescape($value);
1.319     matthew  7103:        }
1.191     harris41 7104:    }
1.12      www      7105:    return %returnhash;
1.424     matthew  7106: }
                   7107: 
                   7108: sub convert_dump_to_currentdump{
                   7109:     my %hash = %{shift()};
                   7110:     my %returnhash;
                   7111:     # Code ripped from lond, essentially.  The only difference
                   7112:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7113:     # we might run in to problems with parameter names =~ /^v\./
                   7114:     while (my ($key,$value) = each(%hash)) {
                   7115:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7116: 	$symb  = &unescape($symb);
                   7117: 	$param = &unescape($param);
1.424     matthew  7118:         next if ($v eq 'version' || $symb eq 'keys');
                   7119:         next if (exists($returnhash{$symb}) &&
                   7120:                  exists($returnhash{$symb}->{$param}) &&
                   7121:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7122:         $returnhash{$symb}->{$param}=$value;
                   7123:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7124:     }
                   7125:     #
                   7126:     # Remove all of the keys in the hashes which keep track of
                   7127:     # the version of the parameter.
                   7128:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7129:         # use a foreach because we are going to delete from the hash.
                   7130:         foreach my $key (keys(%$param_hash)) {
                   7131:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7132:         }
                   7133:     }
                   7134:     return \%returnhash;
1.12      www      7135: }
                   7136: 
1.627     albertel 7137: # ------------------------------------------------------ critical inc interface
                   7138: 
                   7139: sub cinc {
                   7140:     return &inc(@_,'critical');
                   7141: }
                   7142: 
1.449     matthew  7143: # --------------------------------------------------------------- inc interface
                   7144: 
                   7145: sub inc {
1.627     albertel 7146:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7147:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7148:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7149:     my $uhome=&homeserver($uname,$udomain);
                   7150:     my $items='';
                   7151:     if (! ref($store)) {
                   7152:         # got a single value, so use that instead
                   7153:         $items = &escape($store).'=&';
                   7154:     } elsif (ref($store) eq 'SCALAR') {
                   7155:         $items = &escape($$store).'=&';        
                   7156:     } elsif (ref($store) eq 'ARRAY') {
                   7157:         $items = join('=&',map {&escape($_);} @{$store});
                   7158:     } elsif (ref($store) eq 'HASH') {
                   7159:         while (my($key,$value) = each(%{$store})) {
                   7160:             $items.= &escape($key).'='.&escape($value).'&';
                   7161:         }
                   7162:     }
                   7163:     $items=~s/\&$//;
1.627     albertel 7164:     if ($critical) {
                   7165: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7166:     } else {
                   7167: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7168:     }
1.449     matthew  7169: }
                   7170: 
1.12      www      7171: # --------------------------------------------------------------- put interface
                   7172: 
                   7173: sub put {
1.134     albertel 7174:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7175:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7176:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7177:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7178:    my $items='';
1.800     albertel 7179:    foreach my $item (keys(%$storehash)) {
                   7180:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7181:    }
1.12      www      7182:    $items=~s/\&$//;
1.134     albertel 7183:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7184: }
                   7185: 
1.631     albertel 7186: # ------------------------------------------------------------ newput interface
                   7187: 
                   7188: sub newput {
                   7189:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7190:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7191:    if (!$uname) { $uname=$env{'user.name'}; }
                   7192:    my $uhome=&homeserver($uname,$udomain);
                   7193:    my $items='';
                   7194:    foreach my $key (keys(%$storehash)) {
                   7195:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7196:    }
                   7197:    $items=~s/\&$//;
                   7198:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7199: }
                   7200: 
                   7201: # ---------------------------------------------------------  putstore interface
                   7202: 
1.524     raeburn  7203: sub putstore {
1.1269    raeburn  7204:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7205:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7206:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7207:    my $uhome=&homeserver($uname,$udomain);
                   7208:    my $items='';
1.715     albertel 7209:    foreach my $key (keys(%$storehash)) {
                   7210:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7211:    }
1.715     albertel 7212:    $items=~s/\&$//;
1.716     albertel 7213:    my $esc_symb=&escape($symb);
                   7214:    my $esc_v=&escape($version);
1.715     albertel 7215:    my $reply =
1.716     albertel 7216:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7217: 	      $uhome);
1.1269    raeburn  7218:    if (($tolog) && ($reply eq 'ok')) {
                   7219:        my $namevalue='';
                   7220:        foreach my $key (keys(%{$storehash})) {
                   7221:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7222:        }
                   7223:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7224:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7225:                      '&version='.$esc_v.
                   7226:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7227:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7228:    }
1.715     albertel 7229:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7230:        # gfall back to way things use to be done
1.715     albertel 7231:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7232: 			    $uname);
1.524     raeburn  7233:    }
1.715     albertel 7234:    return $reply;
                   7235: }
                   7236: 
                   7237: sub old_putstore {
1.716     albertel 7238:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7239:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7240:     if (!$uname) { $uname=$env{'user.name'}; }
                   7241:     my $uhome=&homeserver($uname,$udomain);
                   7242:     my %newstorehash;
1.800     albertel 7243:     foreach my $item (keys(%$storehash)) {
                   7244: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7245: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7246:     }
                   7247:     my $items='';
                   7248:     my %allitems = ();
1.800     albertel 7249:     foreach my $item (keys(%newstorehash)) {
                   7250: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7251: 	    my $key = $1.':keys:'.$2;
                   7252: 	    $allitems{$key} .= $3.':';
                   7253: 	}
1.800     albertel 7254: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7255:     }
1.800     albertel 7256:     foreach my $item (keys(%allitems)) {
                   7257: 	$allitems{$item} =~ s/\:$//;
                   7258: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7259:     }
                   7260:     $items=~s/\&$//;
                   7261:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7262: }
                   7263: 
1.47      www      7264: # ------------------------------------------------------ critical put interface
                   7265: 
                   7266: sub cput {
1.134     albertel 7267:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7268:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7269:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7270:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7271:    my $items='';
1.800     albertel 7272:    foreach my $item (keys(%$storehash)) {
                   7273:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7274:    }
1.47      www      7275:    $items=~s/\&$//;
1.134     albertel 7276:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7277: }
                   7278: 
                   7279: # -------------------------------------------------------------- eget interface
                   7280: 
                   7281: sub eget {
1.133     albertel 7282:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7283:    my $items='';
1.800     albertel 7284:    foreach my $item (@$storearr) {
                   7285:        $items.=&escape($item).'&';
1.191     harris41 7286:    }
1.12      www      7287:    $items=~s/\&$//;
1.620     albertel 7288:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7289:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7290:    my $uhome=&homeserver($uname,$udomain);
                   7291:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7292:    my @pairs=split(/\&/,$rep);
                   7293:    my %returnhash=();
1.42      www      7294:    my $i=0;
1.800     albertel 7295:    foreach my $item (@$storearr) {
                   7296:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7297:       $i++;
1.191     harris41 7298:    }
1.12      www      7299:    return %returnhash;
                   7300: }
                   7301: 
1.667     albertel 7302: # ------------------------------------------------------------ tmpput interface
                   7303: sub tmpput {
1.802     raeburn  7304:     my ($storehash,$server,$context)=@_;
1.667     albertel 7305:     my $items='';
1.800     albertel 7306:     foreach my $item (keys(%$storehash)) {
                   7307: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7308:     }
                   7309:     $items=~s/\&$//;
1.802     raeburn  7310:     if (defined($context)) {
                   7311:         $items .= ':'.&escape($context);
                   7312:     }
1.667     albertel 7313:     return &reply("tmpput:$items",$server);
                   7314: }
                   7315: 
                   7316: # ------------------------------------------------------------ tmpget interface
                   7317: sub tmpget {
1.688     albertel 7318:     my ($token,$server)=@_;
                   7319:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7320:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7321:     my %returnhash;
1.1328    raeburn  7322:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7323:         return %returnhash;
                   7324:     }
1.667     albertel 7325:     foreach my $item (split(/\&/,$rep)) {
                   7326: 	my ($key,$value)=split(/=/,$item);
                   7327: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7328:     }
                   7329:     return %returnhash;
                   7330: }
                   7331: 
1.1113    raeburn  7332: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7333: sub tmpdel {
                   7334:     my ($token,$server)=@_;
                   7335:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7336:     return &reply("tmpdel:$token",$server);
                   7337: }
                   7338: 
1.1198    raeburn  7339: # ------------------------------------------------------------ get_timebased_id 
                   7340: 
                   7341: sub get_timebased_id {
                   7342:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7343:         $maxtries) = @_;
                   7344:     my ($newid,$error,$dellock);
                   7345:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7346:         return ('','ok','invalid call to get suffix');
                   7347:     }
                   7348: 
                   7349: # set defaults for any optional args for which values were not supplied
                   7350:     if ($who eq '') {
                   7351:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7352:     }
                   7353:     if (!$locktries) {
                   7354:         $locktries = 3;
                   7355:     }
                   7356:     if (!$maxtries) {
                   7357:         $maxtries = 10;
                   7358:     }
                   7359:     
                   7360:     if (($cdom eq '') || ($cnum eq '')) {
                   7361:         if ($env{'request.course.id'}) {
                   7362:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7363:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7364:         }
                   7365:         if (($cdom eq '') || ($cnum eq '')) {
                   7366:             return ('','ok','call to get suffix not in course context');
                   7367:         }
                   7368:     }
                   7369: 
                   7370: # construct locking item
                   7371:     my $lockhash = {
                   7372:                       $prefix."\0".'locked_'.$keyid => $who,
                   7373:                    };
                   7374:     my $tries = 0;
                   7375: 
                   7376: # attempt to get lock on nohist_$namespace file
                   7377:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7378:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7379:         $tries ++;
                   7380:         sleep 1;
                   7381:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7382:     }
                   7383: 
                   7384: # attempt to get unique identifier, based on current timestamp
                   7385:     if ($gotlock eq 'ok') {
                   7386:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7387:         my $id = time;
                   7388:         $newid = $id;
1.1268    raeburn  7389:         if ($idtype eq 'addcode') {
                   7390:             $newid .= &sixnum_code();
                   7391:         }
1.1198    raeburn  7392:         my $idtries = 0;
                   7393:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7394:             if ($idtype eq 'concat') {
                   7395:                 $newid = $id.$idtries;
1.1268    raeburn  7396:             } elsif ($idtype eq 'addcode') {
                   7397:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7398:             } else {
                   7399:                 $newid ++;
                   7400:             }
                   7401:             $idtries ++;
                   7402:         }
                   7403:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7404:             my %new_item =  (
                   7405:                               $prefix."\0".$newid => $who,
                   7406:                             );
                   7407:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7408:                                                  $cdom,$cnum);
                   7409:             if ($putresult ne 'ok') {
                   7410:                 undef($newid);
                   7411:                 $error = 'error saving new item: '.$putresult;
                   7412:             }
                   7413:         } else {
1.1268    raeburn  7414:              undef($newid);
1.1198    raeburn  7415:              $error = ('error: no unique suffix available for the new item ');
                   7416:         }
                   7417: #  remove lock
                   7418:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7419:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7420:     } else {
                   7421:         $error = "error: could not obtain lockfile\n";
                   7422:         $dellock = 'ok';
1.1276    raeburn  7423:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7424:             $dellock = 'nolock';
                   7425:         }
1.1198    raeburn  7426:     }
                   7427:     return ($newid,$dellock,$error);
                   7428: }
                   7429: 
1.1268    raeburn  7430: sub sixnum_code {
                   7431:     my $code;
                   7432:     for (0..6) {
                   7433:         $code .= int( rand(9) );
                   7434:     }
                   7435:     return $code;
                   7436: }
                   7437: 
1.765     albertel 7438: # -------------------------------------------------- portfolio access checking
                   7439: 
                   7440: sub portfolio_access {
1.1270    raeburn  7441:     my ($requrl,$clientip) = @_;
1.765     albertel 7442:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7443:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7444:     if ($result) {
                   7445:         my %setters;
                   7446:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7447:             my ($startblock,$endblock) =
                   7448:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7449:             if ($startblock && $endblock) {
                   7450:                 return 'B';
                   7451:             }
                   7452:         } else {
                   7453:             my ($startblock,$endblock) =
                   7454:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7455:             if ($startblock && $endblock) {
                   7456:                 return 'B';
                   7457:             }
                   7458:         }
                   7459:     }
1.765     albertel 7460:     if ($result eq 'ok') {
1.766     albertel 7461:        return 'F';
1.765     albertel 7462:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7463:        return 'A';
1.765     albertel 7464:     }
1.766     albertel 7465:     return '';
1.765     albertel 7466: }
                   7467: 
                   7468: sub get_portfolio_access {
1.1270    raeburn  7469:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7470: 
                   7471:     if (!ref($access_hash)) {
                   7472: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7473: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7474: 						   $file_name);
                   7475: 	$access_hash = $access_controls{$file_name};
                   7476:     }
                   7477: 
1.1270    raeburn  7478:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7479:     my $now = time;
                   7480:     if (ref($access_hash) eq 'HASH') {
                   7481:         foreach my $key (keys(%{$access_hash})) {
                   7482:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7483:             if ($start > $now) {
                   7484:                 next;
                   7485:             }
                   7486:             if ($end && $end<$now) {
                   7487:                 next;
                   7488:             }
                   7489:             if ($scope eq 'public') {
                   7490:                 $public = $key;
                   7491:                 last;
                   7492:             } elsif ($scope eq 'guest') {
                   7493:                 $guest = $key;
                   7494:             } elsif ($scope eq 'domains') {
                   7495:                 push(@domains,$key);
                   7496:             } elsif ($scope eq 'users') {
                   7497:                 push(@users,$key);
                   7498:             } elsif ($scope eq 'course') {
                   7499:                 push(@courses,$key);
                   7500:             } elsif ($scope eq 'group') {
                   7501:                 push(@groups,$key);
1.1270    raeburn  7502:             } elsif ($scope eq 'ip') {
                   7503:                 push(@ips,$key);
1.765     albertel 7504:             }
                   7505:         }
                   7506:         if ($public) {
                   7507:             return 'ok';
1.1270    raeburn  7508:         } elsif (@ips > 0) {
                   7509:             my $allowed;
                   7510:             foreach my $ipkey (@ips) {
                   7511:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7512:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7513:                         $allowed = 1;
                   7514:                         last; 
                   7515:                     }
                   7516:                 }
                   7517:             }
                   7518:             if ($allowed) {
                   7519:                 return 'ok';
                   7520:             }
1.765     albertel 7521:         }
                   7522:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7523:             if ($guest) {
                   7524:                 return $guest;
                   7525:             }
                   7526:         } else {
                   7527:             if (@domains > 0) {
                   7528:                 foreach my $domkey (@domains) {
                   7529:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7530:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7531:                             return 'ok';
                   7532:                         }
                   7533:                     }
                   7534:                 }
                   7535:             }
                   7536:             if (@users > 0) {
                   7537:                 foreach my $userkey (@users) {
1.865     raeburn  7538:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7539:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7540:                             if (ref($item) eq 'HASH') {
                   7541:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7542:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7543:                                     return 'ok';
                   7544:                                 }
                   7545:                             }
                   7546:                         }
                   7547:                     } 
1.765     albertel 7548:                 }
                   7549:             }
                   7550:             my %roleshash;
                   7551:             my @courses_and_groups = @courses;
                   7552:             push(@courses_and_groups,@groups); 
                   7553:             if (@courses_and_groups > 0) {
                   7554:                 my (%allgroups,%allroles); 
                   7555:                 my ($start,$end,$role,$sec,$group);
                   7556:                 foreach my $envkey (%env) {
1.1060    raeburn  7557:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7558:                         my $cid = $2.'_'.$3; 
                   7559:                         if ($1 eq 'gr') {
                   7560:                             $group = $4;
                   7561:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7562:                         } else {
                   7563:                             if ($4 eq '') {
                   7564:                                 $sec = 'none';
                   7565:                             } else {
                   7566:                                 $sec = $4;
                   7567:                             }
                   7568:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7569:                         }
1.811     albertel 7570:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7571:                         my $cid = $2.'_'.$3;
                   7572:                         if ($4 eq '') {
                   7573:                             $sec = 'none';
                   7574:                         } else {
                   7575:                             $sec = $4;
                   7576:                         }
                   7577:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7578:                     }
                   7579:                 }
                   7580:                 if (keys(%allroles) == 0) {
                   7581:                     return;
                   7582:                 }
                   7583:                 foreach my $key (@courses_and_groups) {
                   7584:                     my %content = %{$$access_hash{$key}};
                   7585:                     my $cnum = $content{'number'};
                   7586:                     my $cdom = $content{'domain'};
                   7587:                     my $cid = $cdom.'_'.$cnum;
                   7588:                     if (!exists($allroles{$cid})) {
                   7589:                         next;
                   7590:                     }    
                   7591:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7592:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7593:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7594:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7595:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7596:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7597:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7598:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7599:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7600:                                         if (grep/^all$/,@sections) {
                   7601:                                             return 'ok';
                   7602:                                         } else {
                   7603:                                             if (grep/^$sec$/,@sections) {
                   7604:                                                 return 'ok';
                   7605:                                             }
                   7606:                                         }
                   7607:                                     }
                   7608:                                 }
                   7609:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7610:                                     if (grep/^none$/,@groups) {
                   7611:                                         return 'ok';
                   7612:                                     }
                   7613:                                 } else {
                   7614:                                     if (grep/^all$/,@groups) {
                   7615:                                         return 'ok';
                   7616:                                     } 
                   7617:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7618:                                         if (grep/^$group$/,@groups) {
                   7619:                                             return 'ok';
                   7620:                                         }
                   7621:                                     }
                   7622:                                 } 
                   7623:                             }
                   7624:                         }
                   7625:                     }
                   7626:                 }
                   7627:             }
                   7628:             if ($guest) {
                   7629:                 return $guest;
                   7630:             }
                   7631:         }
                   7632:     }
                   7633:     return;
                   7634: }
                   7635: 
                   7636: sub course_group_datechecker {
                   7637:     my ($dates,$now,$status) = @_;
                   7638:     my ($start,$end) = split(/\./,$dates);
                   7639:     if (!$start && !$end) {
                   7640:         return 'ok';
                   7641:     }
                   7642:     if (grep/^active$/,@{$status}) {
                   7643:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7644:             return 'ok';
                   7645:         }
                   7646:     }
                   7647:     if (grep/^previous$/,@{$status}) {
                   7648:         if ($end > $now ) {
                   7649:             return 'ok';
                   7650:         }
                   7651:     }
                   7652:     if (grep/^future$/,@{$status}) {
                   7653:         if ($start > $now) {
                   7654:             return 'ok';
                   7655:         }
                   7656:     }
                   7657:     return; 
                   7658: }
                   7659: 
                   7660: sub parse_portfolio_url {
                   7661:     my ($url) = @_;
                   7662: 
                   7663:     my ($type,$udom,$unum,$group,$file_name);
                   7664:     
1.823     albertel 7665:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7666: 	$type = 1;
                   7667:         $udom = $1;
                   7668:         $unum = $2;
                   7669:         $file_name = $3;
1.823     albertel 7670:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7671: 	$type = 2;
                   7672:         $udom = $1;
                   7673:         $unum = $2;
                   7674:         $group = $3;
                   7675:         $file_name = $3.'/'.$4;
                   7676:     }
                   7677:     if (wantarray) {
                   7678: 	return ($type,$udom,$unum,$file_name,$group);
                   7679:     }
                   7680:     return $type;
                   7681: }
                   7682: 
                   7683: sub is_portfolio_url {
                   7684:     my ($url) = @_;
                   7685:     return scalar(&parse_portfolio_url($url));
                   7686: }
                   7687: 
1.798     raeburn  7688: sub is_portfolio_file {
                   7689:     my ($file) = @_;
1.820     raeburn  7690:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7691:         return 1;
                   7692:     }
                   7693:     return;
                   7694: }
                   7695: 
1.976     raeburn  7696: sub usertools_access {
1.1084    raeburn  7697:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7698:     my ($access,%tools);
                   7699:     if ($context eq '') {
                   7700:         $context = 'tools';
                   7701:     }
                   7702:     if ($context eq 'requestcourses') {
                   7703:         %tools = (
                   7704:                       official   => 1,
                   7705:                       unofficial => 1,
1.1006    raeburn  7706:                       community  => 1,
1.1246    raeburn  7707:                       textbook   => 1,
1.1305    raeburn  7708:                       placement  => 1,
1.1368    raeburn  7709:                       lti        => 1,
1.985     raeburn  7710:                  );
1.1183    raeburn  7711:     } elsif ($context eq 'requestauthor') {
                   7712:         %tools = (
                   7713:                       requestauthor => 1,
                   7714:                  );
1.985     raeburn  7715:     } else {
                   7716:         %tools = (
                   7717:                       aboutme   => 1,
                   7718:                       blog      => 1,
1.1177    raeburn  7719:                       webdav    => 1,
1.985     raeburn  7720:                       portfolio => 1,
                   7721:                  );
                   7722:     }
1.976     raeburn  7723:     return if (!defined($tools{$tool}));
                   7724: 
1.1242    raeburn  7725:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7726:         $udom = $env{'user.domain'};
                   7727:         $uname = $env{'user.name'};
                   7728:     }
                   7729: 
1.978     raeburn  7730:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7731:         if ($action ne 'reload') {
1.985     raeburn  7732:             if ($context eq 'requestcourses') {
                   7733:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7734:             } elsif ($context eq 'requestauthor') {
                   7735:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7736:             } else {
                   7737:                 return $env{'environment.availabletools.'.$tool};
                   7738:             }
                   7739:         }
1.976     raeburn  7740:     }
                   7741: 
1.1183    raeburn  7742:     my ($toolstatus,$inststatus,$envkey);
                   7743:     if ($context eq 'requestauthor') {
                   7744:         $envkey = $context; 
                   7745:     } else {
                   7746:         $envkey = $context.'.'.$tool;
                   7747:     }
1.976     raeburn  7748: 
1.985     raeburn  7749:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7750:          ($action ne 'reload')) {
1.1183    raeburn  7751:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7752:         $inststatus = $env{'environment.inststatus'};
                   7753:     } else {
1.1084    raeburn  7754:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7755:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7756:             $inststatus = $userenvref->{'inststatus'};
                   7757:         } else {
1.1183    raeburn  7758:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7759:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7760:             $inststatus = $userenv{'inststatus'};
                   7761:         }
1.976     raeburn  7762:     }
                   7763: 
                   7764:     if ($toolstatus ne '') {
                   7765:         if ($toolstatus) {
                   7766:             $access = 1;
                   7767:         } else {
                   7768:             $access = 0;
                   7769:         }
                   7770:         return $access;
                   7771:     }
                   7772: 
1.1084    raeburn  7773:     my ($is_adv,%domdef);
                   7774:     if (ref($is_advref) eq 'HASH') {
                   7775:         $is_adv = $is_advref->{'is_adv'};
                   7776:     } else {
                   7777:         $is_adv = &is_advanced_user($udom,$uname);
                   7778:     }
                   7779:     if (ref($domdefref) eq 'HASH') {
                   7780:         %domdef = %{$domdefref};
                   7781:     } else {
                   7782:         %domdef = &get_domain_defaults($udom);
                   7783:     }
1.976     raeburn  7784:     if (ref($domdef{$tool}) eq 'HASH') {
                   7785:         if ($is_adv) {
                   7786:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7787:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7788:                     $access = 1;
                   7789:                 } else {
                   7790:                     $access = 0;
                   7791:                 }
                   7792:                 return $access;
                   7793:             }
                   7794:         }
                   7795:         if ($inststatus ne '') {
                   7796:             my ($hasaccess,$hasnoaccess);
                   7797:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7798:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7799:                     if ($domdef{$tool}{$affiliation}) {
                   7800:                         $hasaccess = 1;
                   7801:                     } else {
                   7802:                         $hasnoaccess = 1;
                   7803:                     }
                   7804:                 }
                   7805:             }
                   7806:             if ($hasaccess || $hasnoaccess) {
                   7807:                 if ($hasaccess) {
                   7808:                     $access = 1;
                   7809:                 } elsif ($hasnoaccess) {
                   7810:                     $access = 0; 
                   7811:                 }
                   7812:                 return $access;
                   7813:             }
                   7814:         } else {
                   7815:             if ($domdef{$tool}{'default'} ne '') {
                   7816:                 if ($domdef{$tool}{'default'}) {
                   7817:                     $access = 1;
                   7818:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7819:                     $access = 0;
                   7820:                 }
                   7821:                 return $access;
                   7822:             }
                   7823:         }
                   7824:     } else {
1.1177    raeburn  7825:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7826:             $access = 1;
                   7827:         } else {
                   7828:             $access = 0;
                   7829:         }
1.976     raeburn  7830:         return $access;
                   7831:     }
                   7832: }
                   7833: 
1.1050    raeburn  7834: sub is_course_owner {
                   7835:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7836:     if (($udom eq '') || ($uname eq '')) {
                   7837:         $udom = $env{'user.domain'};
                   7838:         $uname = $env{'user.name'};
                   7839:     }
                   7840:     unless (($udom eq '') || ($uname eq '')) {
                   7841:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7842:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7843:                 return 1;
                   7844:             } else {
                   7845:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7846:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7847:                     return 1;
                   7848:                 }
                   7849:             }
                   7850:         }
                   7851:     }
                   7852:     return;
                   7853: }
                   7854: 
1.976     raeburn  7855: sub is_advanced_user {
                   7856:     my ($udom,$uname) = @_;
1.1085    raeburn  7857:     if ($udom ne '' && $uname ne '') {
                   7858:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7859:             if (wantarray) {
                   7860:                 return ($env{'user.adv'},$env{'user.author'});
                   7861:             } else {
                   7862:                 return $env{'user.adv'};
                   7863:             }
1.1085    raeburn  7864:         }
                   7865:     }
1.976     raeburn  7866:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7867:     my %allroles;
1.1128    raeburn  7868:     my ($is_adv,$is_author);
1.976     raeburn  7869:     foreach my $role (keys(%roleshash)) {
                   7870:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7871:         my $area = '/'.$tdomain.'/'.$trest;
                   7872:         if ($sec ne '') {
                   7873:             $area .= '/'.$sec;
                   7874:         }
                   7875:         if (($area ne '') && ($trole ne '')) {
                   7876:             my $spec=$trole.'.'.$area;
                   7877:             if ($trole =~ /^cr\//) {
                   7878:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7879:             } elsif ($trole ne 'gr') {
                   7880:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7881:             }
1.1128    raeburn  7882:             if ($trole eq 'au') {
                   7883:                 $is_author = 1;
                   7884:             }
1.976     raeburn  7885:         }
                   7886:     }
                   7887:     foreach my $role (keys(%allroles)) {
                   7888:         last if ($is_adv);
                   7889:         foreach my $item (split(/:/,$allroles{$role})) {
                   7890:             if ($item ne '') {
                   7891:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7892:                 if ($privilege eq 'adv') {
                   7893:                     $is_adv = 1;
                   7894:                     last;
                   7895:                 }
                   7896:             }
                   7897:         }
                   7898:     }
1.1128    raeburn  7899:     if (wantarray) {
                   7900:         return ($is_adv,$is_author);
                   7901:     }
1.976     raeburn  7902:     return $is_adv;
                   7903: }
1.798     raeburn  7904: 
1.1035    raeburn  7905: sub check_can_request {
1.1368    raeburn  7906:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7907:     my $canreq = 0;
1.1368    raeburn  7908:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7909:         $uname = $env{'user.name'};
                   7910:         $udom = $env{'user.domain'};
                   7911:     }
1.1035    raeburn  7912:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7913:     my @options = ('approval','validate','autolimit');
                   7914:     my $optregex = join('|',@options);
                   7915:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7916:         foreach my $type (@{$types}) {
1.1368    raeburn  7917:             if (&usertools_access($uname,$udom,$type,undef,
                   7918:                                   'requestcourses')) {
1.1035    raeburn  7919:                 $canreq ++;
1.1036    raeburn  7920:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7921:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7922:                 }
1.1368    raeburn  7923:                 if ($dom eq $udom) {
1.1035    raeburn  7924:                     $can_request->{$type} = 1;
                   7925:                 }
                   7926:             }
1.1368    raeburn  7927:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7928:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7929:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7930:                 if (@curr > 0) {
1.1036    raeburn  7931:                     foreach my $item (@curr) {
                   7932:                         if (ref($request_domains) eq 'HASH') {
                   7933:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7934:                             if ($otherdom ne '') {
                   7935:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7936:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7937:                                         push(@{$request_domains->{$type}},$otherdom);
                   7938:                                     }
                   7939:                                 } else {
                   7940:                                     push(@{$request_domains->{$type}},$otherdom);
                   7941:                                 }
                   7942:                             }
                   7943:                         }
                   7944:                     }
1.1368    raeburn  7945:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7946:                         $canreq ++;
1.1035    raeburn  7947:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7948:                             $can_request->{$type} = 1;
                   7949:                         }
                   7950:                     }
                   7951:                 }
                   7952:             }
                   7953:         }
                   7954:     }
                   7955:     return $canreq;
                   7956: }
                   7957: 
1.341     www      7958: # ---------------------------------------------- Custom access rule evaluation
                   7959: 
                   7960: sub customaccess {
                   7961:     my ($priv,$uri)=@_;
1.807     albertel 7962:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7963:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7964:     $udom = &LONCAPA::clean_domain($udom);
                   7965:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7966:     my $access=0;
1.800     albertel 7967:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7968: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7969: 	if ($type eq 'user') {
                   7970: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7971: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7972: 		if ($tdom) {
                   7973: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7974: 		}
1.896     albertel 7975: 		if ($tuname) {
                   7976: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7977: 		}
                   7978: 		$access=($effect eq 'allow');
                   7979: 		last;
                   7980: 	    }
                   7981: 	} else {
                   7982: 	    if ($role) {
                   7983: 		if ($role ne $urole) { next; }
                   7984: 	    }
                   7985: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7986: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7987: 		if ($tdom) {
                   7988: 		    if ($tdom ne $udom) { next; }
                   7989: 		}
                   7990: 		if ($tcrs) {
                   7991: 		    if ($tcrs ne $ucrs) { next; }
                   7992: 		}
                   7993: 		if ($tsec) {
                   7994: 		    if ($tsec ne $usec) { next; }
                   7995: 		}
                   7996: 		$access=($effect eq 'allow');
                   7997: 		last;
                   7998: 	    }
                   7999: 	    if ($realm eq '' && $role eq '') {
                   8000: 		$access=($effect eq 'allow');
                   8001: 	    }
1.402     bowersj2 8002: 	}
1.341     www      8003:     }
                   8004:     return $access;
                   8005: }
                   8006: 
1.103     harris41 8007: # ------------------------------------------------- Check for a user privilege
1.12      www      8008: 
                   8009: sub allowed {
1.1281    raeburn  8010:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 8011:     my $ver_orguri=$uri;
1.439     www      8012:     $uri=&deversion($uri);
1.152     www      8013:     my $orguri=$uri;
1.52      www      8014:     $uri=&declutter($uri);
1.809     raeburn  8015: 
1.810     raeburn  8016:     if ($priv eq 'evb') {
                   8017: # Evade communication block restrictions for specified role in a course
                   8018:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8019:             return $1;
                   8020:         } else {
                   8021:             return;
                   8022:         }
                   8023:     }
                   8024: 
1.620     albertel 8025:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8026: # Free bre access to adm and meta resources
1.1343    raeburn  8027:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 8028: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8029: 	&& ($priv eq 'bre')) {
1.14      www      8030: 	return 'F';
1.159     www      8031:     }
                   8032: 
1.545     banghart 8033: # Free bre access to user's own portfolio contents
1.714     raeburn  8034:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8035:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8036: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8037:         my %setters;
                   8038:         my ($startblock,$endblock) = 
                   8039:             &Apache::loncommon::blockcheck(\%setters,'port');
                   8040:         if ($startblock && $endblock) {
                   8041:             return 'B';
                   8042:         } else {
                   8043:             return 'F';
                   8044:         }
1.545     banghart 8045:     }
                   8046: 
1.762     raeburn  8047: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8048:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8049:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8050:         if (exists($env{'request.course.id'})) {
                   8051:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8052:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8053:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8054:                 my $courseprivid=$env{'request.course.id'};
                   8055:                 $courseprivid=~s/\_/\//;
                   8056:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8057:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8058:                     return $1; 
1.762     raeburn  8059:                 } else {
                   8060:                     if ($env{'request.course.sec'}) {
                   8061:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8062:                     }
                   8063:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8064:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8065:                         return $2;
                   8066:                     }
1.714     raeburn  8067:                 }
                   8068:             }
                   8069:         }
                   8070:     }
                   8071: 
1.159     www      8072: # Free bre to public access
                   8073: 
                   8074:     if ($priv eq 'bre') {
1.1362    raeburn  8075:         my $copyright;
                   8076:         unless ($uri =~ /ext\.tool/) {
                   8077:             $copyright=&metadata($uri,'copyright');
                   8078:         }
1.620     albertel 8079: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8080:            return 'F'; 
                   8081:         }
1.238     www      8082:         if ($copyright eq 'priv') {
                   8083:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8084: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8085: 		return '';
                   8086:             }
                   8087:         }
                   8088:         if ($copyright eq 'domain') {
                   8089:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8090: 	    unless (($env{'user.domain'} eq $1) ||
                   8091:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8092: 		return '';
                   8093:             }
1.262     matthew  8094:         }
1.620     albertel 8095:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8096:             # Library role, so allow browsing of resources in this domain.
                   8097:             return 'F';
1.238     www      8098:         }
1.341     www      8099:         if ($copyright eq 'custom') {
                   8100: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8101:         }
1.14      www      8102:     }
1.264     matthew  8103:     # Domain coordinator is trying to create a course
1.620     albertel 8104:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8105:         # uri is the requested domain in this case.
                   8106:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8107:         # a role of dc for the domain in question.
1.620     albertel 8108:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8109:     }
1.29      www      8110: 
1.52      www      8111:     my $thisallowed='';
                   8112:     my $statecond=0;
                   8113:     my $courseprivid='';
                   8114: 
1.1039    raeburn  8115:     my $ownaccess;
1.1043    raeburn  8116:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8117:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8118:         if ($uri eq '') {
                   8119:             $ownaccess = 1;
                   8120:         } else {
                   8121:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8122:                 my $udom = $env{'user.domain'};
                   8123:                 my $uname = $env{'user.name'};
                   8124:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8125:                     $ownaccess = 1;
1.1040    raeburn  8126:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8127:                     unless ($uri =~ m{\.\./}) {
                   8128:                         $ownaccess = 1;
                   8129:                     }
                   8130:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8131:                     my $now = time;
                   8132:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8133:                         my $adom = $1;
                   8134:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8135:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  8136:                                 my ($start,$end) = split('.',$env{$key});
                   8137:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8138:                                     $ownaccess = 1;
                   8139:                                     last;
                   8140:                                 }
                   8141:                             }
                   8142:                         }
                   8143:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8144:                         my $adom = $1;
                   8145:                         my $aname = $2;
1.1042    raeburn  8146:                         foreach my $role ('ca','aa') { 
                   8147:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8148:                                 my ($start,$end) =
                   8149:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   8150:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8151:                                     $ownaccess = 1;
                   8152:                                     last;
                   8153:                                 }
1.1039    raeburn  8154:                             }
                   8155:                         }
                   8156:                     }
                   8157:                 }
                   8158:             }
                   8159:         }
                   8160:     }
                   8161: 
1.52      www      8162: # Course
                   8163: 
1.620     albertel 8164:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8165:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8166:             $thisallowed.=$1;
                   8167:         }
1.52      www      8168:     }
1.29      www      8169: 
1.52      www      8170: # Domain
                   8171: 
1.620     albertel 8172:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8173:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8174:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8175:             $thisallowed.=$1;
                   8176:         }
1.12      www      8177:     }
1.52      www      8178: 
1.1141    raeburn  8179: # User who is not author or co-author might still be able to edit
                   8180: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8181:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8182:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8183:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8184:             $thisallowed.=$1;
                   8185:         }
                   8186:     }
                   8187: 
1.52      www      8188: # Course: uri itself is a course
1.66      www      8189:     my $courseuri=$uri;
                   8190:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8191:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8192: 
1.620     albertel 8193:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8194:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8195:         if ($priv eq 'mip') {
                   8196:             my $rem = $1;
                   8197:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8198:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8199:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8200:                 if ($cdom ne '') {
1.1410    raeburn  8201:                     my %passwdconf = &get_passwdconf($cdom);
                   8202:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8203:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8204:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8205:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8206:                                 unless (@inststatuses) {
                   8207:                                     @inststatuses = ('default');
                   8208:                                 }
                   8209:                                 foreach my $status (@inststatuses) {
                   8210:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8211:                                         $thisallowed.=$rem;
                   8212:                                     }
                   8213:                                 }
                   8214:                             }
                   8215:                         }
1.1409    raeburn  8216:                     }
                   8217:                 }
                   8218:             }
                   8219:         } else {
                   8220:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8221:                 $thisallowed.=$1;
                   8222:             }
1.1039    raeburn  8223:         }
1.12      www      8224:     }
1.29      www      8225: 
1.665     albertel 8226: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8227: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8228:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8229: 	$thisallowed='';
1.671     raeburn  8230:         my ($match)=&is_on_map($uri);
                   8231:         if ($match) {
                   8232:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8233:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8234:                 my $value = $1;
1.1402    raeburn  8235:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8236:                 if ($deeplinkblock) {
                   8237:                     $thisallowed='D';
                   8238:                 } elsif ($noblockcheck) {
1.1281    raeburn  8239:                     $thisallowed.=$value;
1.1162    raeburn  8240:                 } else {
1.1281    raeburn  8241:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8242:                     if (@blockers > 0) {
                   8243:                         $thisallowed = 'B';
                   8244:                     } else {
                   8245:                         $thisallowed.=$value;
                   8246:                     }
1.1162    raeburn  8247:                 }
1.671     raeburn  8248:             }
                   8249:         } else {
1.705     albertel 8250:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8251:             if ($refuri) {
                   8252:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8253:                     $thisallowed='F';
1.671     raeburn  8254:                 } else {
                   8255:                     $refuri=&declutter($refuri);
                   8256:                     my ($match) = &is_on_map($refuri);
                   8257:                     if ($match) {
1.1402    raeburn  8258:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8259:                         if ($deeplinkblock) {
                   8260:                             $thisallowed='D';
                   8261:                         } elsif ($noblockcheck) {
1.1281    raeburn  8262:                             $thisallowed='F';
1.1162    raeburn  8263:                         } else {
1.1281    raeburn  8264:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8265:                             if (@blockers > 0) {
                   8266:                                 $thisallowed = 'B';
                   8267:                             } else {
                   8268:                                 $thisallowed='F';
                   8269:                             }
1.1162    raeburn  8270:                         }
1.671     raeburn  8271:                     }
1.669     raeburn  8272:                 }
1.671     raeburn  8273:             }
                   8274:         }
1.314     www      8275:     }
1.492     albertel 8276: 
1.766     albertel 8277:     if ($priv eq 'bre'
                   8278: 	&& $thisallowed ne 'F' 
                   8279: 	&& $thisallowed ne '2'
                   8280: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8281: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8282:     }
1.1250    raeburn  8283: 
1.52      www      8284: # Full access at system, domain or course-wide level? Exit.
1.29      www      8285:     if ($thisallowed=~/F/) {
                   8286: 	return 'F';
                   8287:     }
                   8288: 
1.52      www      8289: # If this is generating or modifying users, exit with special codes
1.29      www      8290: 
1.643     www      8291:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8292: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8293: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8294: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8295: 	    unless ($auname) { return $thisallowed; }
                   8296: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8297: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8298: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8299: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8300: 	}
1.52      www      8301: 	return $thisallowed;
                   8302:     }
                   8303: #
1.103     harris41 8304: # Gathered so far: system, domain and course wide privileges
1.52      www      8305: #
                   8306: # Course: See if uri or referer is an individual resource that is part of 
                   8307: # the course
                   8308: 
1.620     albertel 8309:     if ($env{'request.course.id'}) {
1.232     www      8310: 
1.1409    raeburn  8311: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8312: 
                   8313:         if ($priv eq 'mip') {
                   8314:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8315:                 return $thisallowed;
                   8316:             } else {
                   8317:                 return '';
                   8318:             }
                   8319:         }
                   8320: 
1.620     albertel 8321:        $courseprivid=$env{'request.course.id'};
                   8322:        if ($env{'request.course.sec'}) {
                   8323:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8324:        }
                   8325:        $courseprivid=~s/\_/\//;
                   8326:        my $checkreferer=1;
1.232     www      8327:        my ($match,$cond)=&is_on_map($uri);
                   8328:        if ($match) {
                   8329:            $statecond=$cond;
1.620     albertel 8330:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8331:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8332:                my $value = $1;
                   8333:                if ($priv eq 'bre') {
1.1281    raeburn  8334:                    if ($noblockcheck) {
                   8335:                        $thisallowed.=$value;
1.1162    raeburn  8336:                    } else {
1.1281    raeburn  8337:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8338:                        if (@blockers > 0) {
                   8339:                            $thisallowed = 'B';
                   8340:                        } else {
                   8341:                            $thisallowed.=$value;
                   8342:                        }
1.1162    raeburn  8343:                    }
                   8344:                } else {
                   8345:                    $thisallowed.=$value;
                   8346:                }
1.52      www      8347:                $checkreferer=0;
                   8348:            }
1.29      www      8349:        }
1.83      www      8350:        
1.148     www      8351:        if ($checkreferer) {
1.620     albertel 8352: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8353:             unless ($refuri) {
1.800     albertel 8354:                 foreach my $key (keys(%env)) {
                   8355: 		    if ($key=~/^httpref\..*\*/) {
                   8356: 			my $pattern=$key;
1.156     www      8357:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8358:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8359:                         $pattern=~s/\//\\\//g;
1.152     www      8360:                         if ($orguri=~/$pattern/) {
1.800     albertel 8361: 			    $refuri=$env{$key};
1.148     www      8362:                         }
                   8363:                     }
1.191     harris41 8364:                 }
1.148     www      8365:             }
1.232     www      8366: 
1.148     www      8367:          if ($refuri) { 
1.152     www      8368: 	  $refuri=&declutter($refuri);
1.232     www      8369:           my ($match,$cond)=&is_on_map($refuri);
                   8370:             if ($match) {
                   8371:               my $refstatecond=$cond;
1.620     albertel 8372:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8373:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8374:                   my $value = $1;
                   8375:                   if ($priv eq 'bre') {
1.1402    raeburn  8376:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8377:                       if ($deeplinkblock) {
                   8378:                           $thisallowed = 'D';
                   8379:                       } elsif ($noblockcheck) {
1.1281    raeburn  8380:                           $thisallowed.=$value;
1.1162    raeburn  8381:                       } else {
1.1281    raeburn  8382:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8383:                           if (@blockers > 0) {
                   8384:                               $thisallowed = 'B';
                   8385:                           } else {
                   8386:                               $thisallowed.=$value;
                   8387:                           }
1.1162    raeburn  8388:                       }
                   8389:                   } else {
                   8390:                       $thisallowed.=$value;
                   8391:                   }
1.53      www      8392:                   $uri=$refuri;
                   8393:                   $statecond=$refstatecond;
1.52      www      8394:               }
                   8395:           }
1.148     www      8396:         }
1.29      www      8397:        }
1.52      www      8398:    }
1.29      www      8399: 
1.52      www      8400: #
1.103     harris41 8401: # Gathered now: all privileges that could apply, and condition number
1.52      www      8402: # 
                   8403: #
                   8404: # Full or no access?
                   8405: #
1.29      www      8406: 
1.52      www      8407:     if ($thisallowed=~/F/) {
                   8408: 	return 'F';
                   8409:     }
1.29      www      8410: 
1.52      www      8411:     unless ($thisallowed) {
                   8412:         return '';
                   8413:     }
1.29      www      8414: 
1.52      www      8415: # Restrictions exist, deal with them
                   8416: #
                   8417: #   C:according to course preferences
                   8418: #   R:according to resource settings
                   8419: #   L:unless locked
                   8420: #   X:according to user session state
                   8421: #
                   8422: 
                   8423: # Possibly locked functionality, check all courses
1.54      www      8424: # Locks might take effect only after 10 minutes cache expiration for other
                   8425: # courses, and 2 minutes for current course
1.52      www      8426: 
                   8427:     my $envkey;
                   8428:     if ($thisallowed=~/L/) {
1.1000    raeburn  8429:         foreach $envkey (keys(%env)) {
1.54      www      8430:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8431:                my $courseid=$2;
                   8432:                my $roleid=$1.'.'.$2;
1.92      www      8433:                $courseid=~s/^\///;
1.54      www      8434:                my $expiretime=600;
1.620     albertel 8435:                if ($env{'request.role'} eq $roleid) {
1.54      www      8436: 		  $expiretime=120;
                   8437:                }
                   8438: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8439:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8440:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8441: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8442:                }
1.620     albertel 8443:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8444:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8445: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8446:                        &log($env{'user.domain'},$env{'user.name'},
                   8447:                             $env{'user.home'},
1.57      www      8448:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8449:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8450:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8451: 		       return '';
                   8452:                    }
                   8453:                }
1.620     albertel 8454:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8455:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8456: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8457:                        &log($env{'user.domain'},$env{'user.name'},
                   8458:                             $env{'user.home'},
1.57      www      8459:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8460:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8461:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8462: 		       return '';
                   8463:                    }
                   8464:                }
                   8465: 	   }
1.29      www      8466:        }
1.52      www      8467:     }
                   8468:    
                   8469: #
                   8470: # Rest of the restrictions depend on selected course
                   8471: #
                   8472: 
1.620     albertel 8473:     unless ($env{'request.course.id'}) {
1.766     albertel 8474: 	if ($thisallowed eq 'A') {
                   8475: 	    return 'A';
1.814     raeburn  8476:         } elsif ($thisallowed eq 'B') {
                   8477:             return 'B';
1.766     albertel 8478: 	} else {
                   8479: 	    return '1';
                   8480: 	}
1.52      www      8481:     }
1.29      www      8482: 
1.52      www      8483: #
                   8484: # Now user is definitely in a course
                   8485: #
1.53      www      8486: 
                   8487: 
                   8488: # Course preferences
                   8489: 
                   8490:    if ($thisallowed=~/C/) {
1.620     albertel 8491:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8492:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8493:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8494: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8495: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8496: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8497: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8498: 			$env{'request.course.id'});
                   8499: 	   }
1.237     www      8500:            return '';
                   8501:        }
                   8502: 
1.620     albertel 8503:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8504: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8505: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8506: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8507: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8508: 			$env{'request.course.id'});
                   8509: 	   }
1.54      www      8510:            return '';
                   8511:        }
1.53      www      8512:    }
                   8513: 
                   8514: # Resource preferences
                   8515: 
                   8516:    if ($thisallowed=~/R/) {
1.620     albertel 8517:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8518:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8519: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8520: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8521: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8522: 	   }
                   8523: 	   return '';
1.54      www      8524:        }
1.53      www      8525:    }
1.30      www      8526: 
1.246     www      8527: # Restricted by state or randomout?
1.30      www      8528: 
1.52      www      8529:    if ($thisallowed=~/X/) {
1.620     albertel 8530:       if ($env{'acc.randomout'}) {
1.579     albertel 8531: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8532:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8533:             return ''; 
                   8534:          }
1.247     www      8535:       }
                   8536:       if (&condval($statecond)) {
1.52      www      8537: 	 return '2';
                   8538:       } else {
                   8539:          return '';
                   8540:       }
                   8541:    }
1.30      www      8542: 
1.766     albertel 8543:     if ($thisallowed eq 'A') {
                   8544: 	return 'A';
1.814     raeburn  8545:     } elsif ($thisallowed eq 'B') {
                   8546:         return 'B';
1.1402    raeburn  8547:     } elsif ($thisallowed eq 'D') {
                   8548:         return 'D';
1.766     albertel 8549:     }
1.52      www      8550:    return 'F';
1.232     www      8551: }
1.1162    raeburn  8552: 
1.1192    raeburn  8553: # ------------------------------------------- Check construction space access
                   8554: 
                   8555: sub constructaccess {
                   8556:     my ($url,$setpriv)=@_;
                   8557: 
                   8558: # We do not allow editing of previous versions of files
                   8559:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8560: 
                   8561: # Get username and domain from URL
                   8562:     my ($ownername,$ownerdomain,$ownerhome);
                   8563: 
                   8564:     ($ownerdomain,$ownername) =
1.1325    raeburn  8565:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8566: 
                   8567: # The URL does not really point to any authorspace, forget it
                   8568:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8569: 
                   8570: # Now we need to see if the user has access to the authorspace of
                   8571: # $ownername at $ownerdomain
                   8572: 
                   8573:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8574: # Real author for this?
                   8575:        $ownerhome = $env{'user.home'};
                   8576:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8577:           return ($ownername,$ownerdomain,$ownerhome);
                   8578:        }
                   8579:     } else {
                   8580: # Co-author for this?
                   8581:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8582:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8583:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8584:             return ($ownername,$ownerdomain,$ownerhome);
                   8585:         }
1.1312    raeburn  8586:         if ($env{'request.course.id'}) {
                   8587:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8588:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8589:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8590:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8591:                     return ($ownername,$ownerdomain,$ownerhome);
                   8592:                 }
                   8593:             }
                   8594:         }
1.1192    raeburn  8595:     }
                   8596: 
                   8597: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8598: # we might as well leave
                   8599:    unless ($setpriv) { return ''; }
                   8600: 
                   8601: # Backdoor access?
                   8602:     my $allowed=&allowed('eco',$ownerdomain);
                   8603: # Nope
                   8604:     unless ($allowed) { return ''; }
                   8605: # Looks like we may have access, but could be locked by the owner of the construction space
                   8606:     if ($allowed eq 'U') {
                   8607:         my %blocked=&get('environment',['domcoord.author'],
                   8608:                          $ownerdomain,$ownername);
                   8609: # Is blocked by owner
                   8610:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8611:     }
                   8612:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8613: # Grant temporary access
                   8614:         my $then=$env{'user.login.time'};
1.1209    raeburn  8615:         my $update=$env{'user.update.time'};
1.1192    raeburn  8616:         if (!$update) { $update = $then; }
                   8617:         my $refresh=$env{'user.refresh.time'};
                   8618:         if (!$refresh) { $refresh = $update; }
                   8619:         my $now = time;
                   8620:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8621:                            $now,'ca','constructaccess');
                   8622:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8623:         return($ownername,$ownerdomain,$ownerhome);
                   8624:     }
                   8625: # No business here
                   8626:     return '';
                   8627: }
                   8628: 
1.1282    raeburn  8629: # ----------------------------------------------------------- Content Blocking
                   8630: 
                   8631: {
                   8632: # Caches for faster Course Contents display where content blocking
                   8633: # is in operation (i.e., interval param set) for timed quiz.
                   8634: #
                   8635: # User for whom data are being temporarily cached.
                   8636: my $cacheduser='';
                   8637: # Cached blockers for this user (a hash of blocking items). 
                   8638: my %cachedblockers=();
                   8639: # When the data were last cached.
                   8640: my $cachedlast='';
                   8641: 
                   8642: sub load_all_blockers {
                   8643:     my ($uname,$udom,$blocks)=@_;
                   8644:     if (($uname ne '') && ($udom ne '')) { 
                   8645:         if (($cacheduser eq $uname.':'.$udom) &&
                   8646:             (abs($cachedlast-time)<5)) {
                   8647:             return;
                   8648:         }
                   8649:     }
                   8650:     $cachedlast=time;
                   8651:     $cacheduser=$uname.':'.$udom;
                   8652:     %cachedblockers = &get_commblock_resources($blocks);
                   8653: }
                   8654: 
1.1162    raeburn  8655: sub get_comm_blocks {
                   8656:     my ($cdom,$cnum) = @_;
                   8657:     if ($cdom eq '' || $cnum eq '') {
                   8658:         return unless ($env{'request.course.id'});
                   8659:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8660:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8661:     }
                   8662:     my %commblocks;
                   8663:     my $hashid=$cdom.'_'.$cnum;
                   8664:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8665:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8666:         %commblocks = %{$blocksref};
                   8667:     } else {
                   8668:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8669:         my $cachetime = 600;
                   8670:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8671:     }
                   8672:     return %commblocks;
                   8673: }
                   8674: 
1.1282    raeburn  8675: sub get_commblock_resources {
                   8676:     my ($blocks) = @_;
                   8677:     my %blockers = ();
                   8678:     return %blockers unless ($env{'request.course.id'});
                   8679:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8680:     my %commblocks;
                   8681:     if (ref($blocks) eq 'HASH') {
                   8682:         %commblocks = %{$blocks};
                   8683:     } else {
                   8684:         %commblocks = &get_comm_blocks();
                   8685:     }
1.1282    raeburn  8686:     return %blockers unless (keys(%commblocks) > 0); 
                   8687:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8688:     return %blockers unless (ref($navmap));
1.1162    raeburn  8689:     my $now = time;
                   8690:     foreach my $block (keys(%commblocks)) {
                   8691:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8692:             my ($start,$end) = ($1,$2);
                   8693:             if ($start <= $now && $end >= $now) {
                   8694:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8695:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8696:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8697:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8698:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8699:                             }
                   8700:                         }
                   8701:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8702:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8703:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8704:                             }
                   8705:                         }
                   8706:                     }
                   8707:                 }
                   8708:             }
                   8709:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8710:             my $item = $1;
1.1163    raeburn  8711:             my @to_test;
1.1162    raeburn  8712:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8713:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8714:                     my @interval;
                   8715:                     my $type = 'map';
                   8716:                     if ($item eq 'course') {
                   8717:                         $type = 'course';
                   8718:                         @interval=&EXT("resource.0.interval");
                   8719:                     } else {
                   8720:                         if ($item =~ /___\d+___/) {
                   8721:                             $type = 'resource';
                   8722:                             @interval=&EXT("resource.0.interval",$item);
                   8723:                             if (ref($navmap)) {                        
                   8724:                                 my $res = $navmap->getBySymb($item); 
                   8725:                                 push(@to_test,$res);
                   8726:                             }
1.1162    raeburn  8727:                         } else {
1.1282    raeburn  8728:                             my $mapsymb = &symbread($item,1);
                   8729:                             if ($mapsymb) {
                   8730:                                 if (ref($navmap)) {
                   8731:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8732:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8733:                                     foreach my $res (@to_test) {
                   8734:                                         my $symb = $res->symb();
                   8735:                                         next if ($symb eq $mapsymb);
                   8736:                                         if ($symb ne '') {
                   8737:                                             @interval=&EXT("resource.0.interval",$symb);
                   8738:                                             if ($interval[1] eq 'map') {
                   8739:                                                 last;
1.1162    raeburn  8740:                                             }
                   8741:                                         }
                   8742:                                     }
                   8743:                                 }
                   8744:                             }
                   8745:                         }
1.1282    raeburn  8746:                     }
1.1310    raeburn  8747:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8748:                         my $timelimit = $1; 
1.1282    raeburn  8749:                         my $first_access;
                   8750:                         if ($type eq 'resource') {
                   8751:                             $first_access=&get_first_access($interval[1],$item);
                   8752:                         } elsif ($type eq 'map') {
                   8753:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8754:                         } else {
                   8755:                             $first_access=&get_first_access($interval[1]);
                   8756:                         }
                   8757:                         if ($first_access) {
1.1292    raeburn  8758:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8759:                             if ($timesup > $now) {
                   8760:                                 my $activeblock;
                   8761:                                 foreach my $res (@to_test) {
1.1283    raeburn  8762:                                     if ($res->answerable()) {
1.1282    raeburn  8763:                                         $activeblock = 1;
                   8764:                                         last;
                   8765:                                     }
                   8766:                                 }
                   8767:                                 if ($activeblock) {
                   8768:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8769:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8770:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8771:                                          }
                   8772:                                     }
                   8773:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8774:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8775:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8776:                                         }
1.1162    raeburn  8777:                                     }
                   8778:                                 }
                   8779:                             }
                   8780:                         }
                   8781:                     }
                   8782:                 }
                   8783:             }
                   8784:         }
                   8785:     }
1.1282    raeburn  8786:     return %blockers;
1.1162    raeburn  8787: }
                   8788: 
1.1282    raeburn  8789: sub has_comm_blocking {
                   8790:     my ($priv,$symb,$uri,$blocks) = @_;
                   8791:     my @blockers;
                   8792:     return unless ($env{'request.course.id'});
                   8793:     return unless ($priv eq 'bre');
                   8794:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8795:     return if ($env{'request.state'} eq 'construct');
                   8796:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8797:     return unless (keys(%cachedblockers) > 0);
                   8798:     my (%possibles,@symbs);
                   8799:     if (!$symb) {
                   8800:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8801:     }
1.1282    raeburn  8802:     if ($symb) {
                   8803:         @symbs = ($symb);
                   8804:     } elsif (keys(%possibles)) { 
                   8805:         @symbs = keys(%possibles);
                   8806:     }
                   8807:     my $noblock;
                   8808:     foreach my $symb (@symbs) {
                   8809:         last if ($noblock);
                   8810:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8811:         foreach my $block (keys(%cachedblockers)) {
                   8812:             if ($block =~ /^firstaccess____(.+)$/) {
                   8813:                 my $item = $1;
                   8814:                 if (($item eq $map) || ($item eq $symb)) {
                   8815:                     $noblock = 1;
                   8816:                     last;
                   8817:                 }
                   8818:             }
                   8819:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8820:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8821:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8822:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8823:                             push(@blockers,$block);
                   8824:                         }
                   8825:                     }
                   8826:                 }
1.1162    raeburn  8827:             }
1.1282    raeburn  8828:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8829:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8830:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8831:                         push(@blockers,$block);
                   8832:                     }
                   8833:                 }
1.1162    raeburn  8834:             }
                   8835:         }
                   8836:     }
1.1282    raeburn  8837:     return if ($noblock);
                   8838:     return @blockers;
                   8839: }
1.1162    raeburn  8840: }
                   8841: 
1.1402    raeburn  8842: sub deeplink_check {
                   8843:     my ($priv,$symb,$uri) = @_;
                   8844:     return unless ($env{'request.course.id'});
                   8845:     return unless ($priv eq 'bre');
                   8846:     return if ($env{'request.state'} eq 'construct');
                   8847:     return if ($env{'request.role.adv'});
                   8848:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8849:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8850:     my (%possibles,@symbs);
                   8851:     if (!$symb) {
                   8852:         $symb = &symbread($uri,1,1,1,\%possibles);
                   8853:     }
                   8854:     if ($symb) {
                   8855:         @symbs = ($symb);
                   8856:     } elsif (keys(%possibles)) {
                   8857:         @symbs = keys(%possibles);
                   8858:     }
                   8859: 
                   8860:     my ($login,$switchrole,$allow);
                   8861:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   8862:         my $key = $1;
                   8863:         my $tinyurl;
                   8864:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   8865:         if (defined($cached)) {
                   8866:              $tinyurl = $result;
                   8867:         } else {
                   8868:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   8869:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   8870:              if ($currtiny{$key} ne '') {
                   8871:                  $tinyurl = $currtiny{$key};
                   8872:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   8873:              }
                   8874:         }
                   8875:         if ($tinyurl ne '') {
                   8876:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
                   8877:             if ($cnumreq eq $cnum) {
                   8878:                 $login = $posslogin;
                   8879:             } else {
                   8880:                 $switchrole = 1;
                   8881:             }
                   8882:         }
                   8883:     }
                   8884:     foreach my $symb (@symbs) {
                   8885:         last if ($allow);
                   8886:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8887:         if ($deeplink eq '') {
                   8888:             $allow = 1;
                   8889:         } else {
                   8890:             my ($listed,$scope,$access) = split(/,/,$deeplink);
                   8891:             if ($access eq 'any') {
                   8892:                 $allow = 1;
                   8893:             } elsif ($login) {
                   8894:                 if ($access eq 'only') {
                   8895:                     if ($scope eq 'res') {
                   8896:                         if ($symb eq $login) {
                   8897:                             $allow = 1;
                   8898:                         }
                   8899:                     } elsif ($scope eq 'map') {
                   8900: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
                   8901:                     } elsif ($scope eq 'rec') {
                   8902: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
                   8903:                     }
                   8904:                 } else {
                   8905:                     my ($acctype,$item) = split(/:/,$access);
                   8906:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
                   8907:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
                   8908:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8909:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
                   8910:                                 $allow = 1;
                   8911:                             }
                   8912:                         }
                   8913:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   8914:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   8915:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8916:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
                   8917:                                 $allow = 1;
                   8918:                             }
                   8919:                         }
                   8920:                     }
                   8921:                 }
                   8922:             }
                   8923:         }
                   8924:     }
                   8925:     return if ($allow);
                   8926:     return 1;
                   8927: }
                   8928: 
1.1282    raeburn  8929: # -------------------------------- Deversion and split uri into path an filename   
                   8930: 
1.1133    foxr     8931: #
1.1282    raeburn  8932: #   Removes the version from a URI and
1.1133    foxr     8933: #   splits it in to its filename and path to the filename.
                   8934: #   Seems like File::Basename could have done this more clearly.
                   8935: #   Parameters:
                   8936: #      $uri   - input URI
                   8937: #   Returns:
                   8938: #     Two element list consisting of 
                   8939: #     $pathname  - the URI up to and excluding the trailing /
                   8940: #     $filename  - The part of the URI following the last /
                   8941: #  NOTE:
                   8942: #    Another realization of this is simply:
                   8943: #    use File::Basename;
                   8944: #    ...
                   8945: #    $uri = shift;
                   8946: #    $filename = basename($uri);
                   8947: #    $path     = dirname($uri);
                   8948: #    return ($filename, $path);
                   8949: #
                   8950: #     The implementation below is probably faster however.
                   8951: #
1.710     albertel 8952: sub split_uri_for_cond {
                   8953:     my $uri=&deversion(&declutter(shift));
                   8954:     my @uriparts=split(/\//,$uri);
                   8955:     my $filename=pop(@uriparts);
                   8956:     my $pathname=join('/',@uriparts);
                   8957:     return ($pathname,$filename);
                   8958: }
1.232     www      8959: # --------------------------------------------------- Is a resource on the map?
                   8960: 
                   8961: sub is_on_map {
1.710     albertel 8962:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8963:     #Trying to find the conditional for the file
1.620     albertel 8964:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8965: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8966:     if ($match) {
1.289     bowersj2 8967: 	return (1,$1);
                   8968:     } else {
1.434     www      8969: 	return (0,0);
1.289     bowersj2 8970:     }
1.12      www      8971: }
                   8972: 
1.427     www      8973: # --------------------------------------------------------- Get symb from alias
                   8974: 
                   8975: sub get_symb_from_alias {
                   8976:     my $symb=shift;
                   8977:     my ($map,$resid,$url)=&decode_symb($symb);
                   8978: # Already is a symb
                   8979:     if ($url) { return $symb; }
                   8980: # Must be an alias
                   8981:     my $aliassymb='';
                   8982:     my %bighash;
1.620     albertel 8983:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8984:                             &GDBM_READER(),0640)) {
                   8985:         my $rid=$bighash{'mapalias_'.$symb};
                   8986: 	if ($rid) {
                   8987: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8988: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8989: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8990: 	}
                   8991:         untie %bighash;
                   8992:     }
                   8993:     return $aliassymb;
                   8994: }
                   8995: 
1.12      www      8996: # ----------------------------------------------------------------- Define Role
                   8997: 
                   8998: sub definerole {
                   8999:   if (allowed('mcr','/')) {
1.1326    raeburn  9000:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9001:     foreach my $role (split(':',$sysrole)) {
                   9002: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9003:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9004:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9005: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9006:                return "refused:s:$crole&$cqual"; 
                   9007:             }
                   9008:         }
1.191     harris41 9009:     }
1.800     albertel 9010:     foreach my $role (split(':',$domrole)) {
                   9011: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9012:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9013:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9014: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9015:                return "refused:d:$crole&$cqual"; 
                   9016:             }
                   9017:         }
1.191     harris41 9018:     }
1.800     albertel 9019:     foreach my $role (split(':',$courole)) {
                   9020: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9021:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9022:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9023: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9024:                return "refused:c:$crole&$cqual"; 
                   9025:             }
                   9026:         }
1.191     harris41 9027:     }
1.1326    raeburn  9028:     my $uhome;
                   9029:     if (($uname ne '') && ($udom ne '')) {
                   9030:         $uhome = &homeserver($uname,$udom);
                   9031:         return $uhome if ($uhome eq 'no_host');
                   9032:     } else {
                   9033:         $uname = $env{'user.name'};
                   9034:         $udom = $env{'user.domain'};
                   9035:         $uhome = $env{'user.home'};
                   9036:     }
1.620     albertel 9037:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9038:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9039:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9040:     return reply($command,$uhome);
1.12      www      9041:   } else {
                   9042:     return 'refused';
                   9043:   }
1.105     harris41 9044: }
                   9045: 
                   9046: # ---------------- Make a metadata query against the network of library servers
                   9047: 
                   9048: sub metadata_query {
1.1237    raeburn  9049:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9050:     my %rhash;
1.845     albertel 9051:     my %libserv = &all_library();
1.244     matthew  9052:     my @server_list = (defined($server_array) ? @$server_array
                   9053:                                               : keys(%libserv) );
                   9054:     for my $server (@server_list) {
1.1237    raeburn  9055:         my $domains = ''; 
                   9056:         if (ref($domains_hash) eq 'HASH') {
                   9057:             $domains = $domains_hash->{$server}; 
                   9058:         }
1.118     harris41 9059: 	unless ($custom or $customshow) {
1.1237    raeburn  9060: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9061: 	    $rhash{$server}=$reply;
                   9062: 	}
                   9063: 	else {
                   9064: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9065: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9066: 			     $server);
                   9067: 	    $rhash{$server}=$reply;
                   9068: 	}
1.112     harris41 9069:     }
1.118     harris41 9070:     return \%rhash;
1.240     www      9071: }
                   9072: 
                   9073: # ----------------------------------------- Send log queries and wait for reply
                   9074: 
                   9075: sub log_query {
                   9076:     my ($uname,$udom,$query,%filters)=@_;
                   9077:     my $uhome=&homeserver($uname,$udom);
                   9078:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9079:     my $uhost=&hostname($uhome);
1.800     albertel 9080:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9081:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9082:                        $uhome);
1.479     albertel 9083:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9084:     return get_query_reply($queryid);
                   9085: }
                   9086: 
1.818     raeburn  9087: # -------------------------- Update MySQL table for portfolio file
                   9088: 
                   9089: sub update_portfolio_table {
1.821     raeburn  9090:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9091:     if ($group ne '') {
                   9092:         $file_name =~s /^\Q$group\E//;
                   9093:     }
1.818     raeburn  9094:     my $homeserver = &homeserver($uname,$udom);
                   9095:     my $queryid=
1.821     raeburn  9096:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9097:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9098:     my $reply = &get_query_reply($queryid);
                   9099:     return $reply;
                   9100: }
                   9101: 
1.899     raeburn  9102: # -------------------------- Update MySQL allusers table
                   9103: 
                   9104: sub update_allusers_table {
                   9105:     my ($uname,$udom,$names) = @_;
                   9106:     my $homeserver = &homeserver($uname,$udom);
                   9107:     my $queryid=
                   9108:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9109:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9110:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9111:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9112:                'generation='.&escape($names->{'generation'}).'%%'.
                   9113:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9114:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9115:     return;
1.899     raeburn  9116: }
                   9117: 
1.508     raeburn  9118: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9119: 
                   9120: sub fetch_enrollment_query {
1.511     raeburn  9121:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9122:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9123:     my $maxtries = 1;
1.508     raeburn  9124:     if ($context eq 'automated') {
                   9125:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9126:         $sleep = 2;
                   9127:         $loopmax = 100;
1.547     raeburn  9128:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9129:     } else {
                   9130:         $homeserver = &homeserver($cnum,$dom);
                   9131:     }
1.838     albertel 9132:     my $host=&hostname($homeserver);
1.506     raeburn  9133:     my $cmd = '';
1.1000    raeburn  9134:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9135:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9136:     }
                   9137:     $cmd =~ s/%%$//;
                   9138:     $cmd = &escape($cmd);
                   9139:     my $query = 'fetchenrollment';
1.620     albertel 9140:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9141:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9142:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9143:         return 'error: '.$queryid;
                   9144:     }
1.1317    raeburn  9145:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9146:     my $tries = 1;
                   9147:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9148:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9149:         $tries ++;
                   9150:     }
1.526     raeburn  9151:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9152:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9153:     } else {
1.901     albertel 9154:         my @responses = split(/:/,$reply);
1.1322    raeburn  9155:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9156:             foreach my $line (@responses) {
                   9157:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9158:                 $$replyref{$key} = $value;
                   9159:             }
                   9160:         } else {
1.1117    foxr     9161:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9162:             foreach my $line (@responses) {
                   9163:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9164:                 $$replyref{$key} = $value;
                   9165:                 if ($value > 0) {
1.800     albertel 9166:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9167:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9168:                         my $destname = $pathname.'/'.$filename;
                   9169:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9170:                         if ($xml_classlist =~ /^error/) {
                   9171:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9172:                         } else {
1.1359    raeburn  9173:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9174:                                 print FILE &unescape($xml_classlist);
                   9175:                                 close(FILE);
1.526     raeburn  9176:                             } else {
                   9177:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9178:                             }
                   9179:                         }
                   9180:                     }
                   9181:                 }
                   9182:             }
                   9183:         }
                   9184:         return 'ok';
                   9185:     }
                   9186:     return 'error';
                   9187: }
                   9188: 
1.242     www      9189: sub get_query_reply {
1.1317    raeburn  9190:     my ($queryid,$sleep,$loopmax) = @_;;
                   9191:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9192:         $sleep = 0.2;
                   9193:     }
                   9194:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9195:         $loopmax = 100;
                   9196:     }
1.1117    foxr     9197:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9198:     my $reply='';
1.1317    raeburn  9199:     for (1..$loopmax) {
                   9200: 	sleep($sleep);
1.240     www      9201:         if (-e $replyfile.'.end') {
1.1359    raeburn  9202: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9203: 		$reply = join('',<$fh>);
                   9204: 		close($fh);
1.240     www      9205: 	   } else { return 'error: reply_file_error'; }
1.242     www      9206:            return &unescape($reply);
                   9207: 	}
1.240     www      9208:     }
1.242     www      9209:     return 'timeout:'.$queryid;
1.240     www      9210: }
                   9211: 
                   9212: sub courselog_query {
1.241     www      9213: #
                   9214: # possible filters:
                   9215: # url: url or symb
                   9216: # username
                   9217: # domain
                   9218: # action: view, submit, grade
                   9219: # start: timestamp
                   9220: # end: timestamp
                   9221: #
1.240     www      9222:     my (%filters)=@_;
1.620     albertel 9223:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9224:     if ($filters{'url'}) {
                   9225: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9226:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9227:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9228:     }
1.620     albertel 9229:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9230:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9231:     return &log_query($cname,$cdom,'courselog',%filters);
                   9232: }
                   9233: 
                   9234: sub userlog_query {
1.858     raeburn  9235: #
                   9236: # possible filters:
                   9237: # action: log check role
                   9238: # start: timestamp
                   9239: # end: timestamp
                   9240: #
1.240     www      9241:     my ($uname,$udom,%filters)=@_;
                   9242:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9243: }
                   9244: 
1.506     raeburn  9245: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9246: 
                   9247: sub auto_run {
1.508     raeburn  9248:     my ($cnum,$cdom) = @_;
1.876     raeburn  9249:     my $response = 0;
                   9250:     my $settings;
                   9251:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9252:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9253:         $settings = $domconfig{'autoenroll'};
                   9254:         if ($settings->{'run'} eq '1') {
                   9255:             $response = 1;
                   9256:         }
                   9257:     } else {
1.934     raeburn  9258:         my $homeserver;
                   9259:         if (&is_course($cdom,$cnum)) {
                   9260:             $homeserver = &homeserver($cnum,$cdom);
                   9261:         } else {
                   9262:             $homeserver = &domain($cdom,'primary');
                   9263:         }
                   9264:         if ($homeserver ne 'no_host') {
                   9265:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9266:         }
1.876     raeburn  9267:     }
1.506     raeburn  9268:     return $response;
                   9269: }
1.776     albertel 9270: 
1.506     raeburn  9271: sub auto_get_sections {
1.508     raeburn  9272:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9273:     my $homeserver;
                   9274:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9275:         $homeserver = &homeserver($cnum,$cdom);
                   9276:     }
                   9277:     if (!defined($homeserver)) { 
                   9278:         if ($cdom =~ /^$match_domain$/) {
                   9279:             $homeserver = &domain($cdom,'primary');
                   9280:         }
                   9281:     }
                   9282:     my @secs;
                   9283:     if (defined($homeserver)) {
                   9284:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9285:         unless ($response eq 'refused') {
                   9286:             @secs = split(/:/,$response);
                   9287:         }
1.506     raeburn  9288:     }
                   9289:     return @secs;
                   9290: }
1.776     albertel 9291: 
1.506     raeburn  9292: sub auto_new_course {
1.1099    raeburn  9293:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9294:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9295:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9296:     return $response;
                   9297: }
1.776     albertel 9298: 
1.506     raeburn  9299: sub auto_validate_courseID {
1.508     raeburn  9300:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9301:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9302:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9303:     return $response;
                   9304: }
1.776     albertel 9305: 
1.1007    raeburn  9306: sub auto_validate_instcode {
1.1020    raeburn  9307:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9308:     my ($homeserver,$response);
                   9309:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9310:         $homeserver = &homeserver($cnum,$cdom);
                   9311:     }
                   9312:     if (!defined($homeserver)) {
                   9313:         if ($cdom =~ /^$match_domain$/) {
                   9314:             $homeserver = &domain($cdom,'primary');
                   9315:         }
                   9316:     }
1.1065    raeburn  9317:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9318:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9319:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9320:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9321: }
                   9322: 
1.506     raeburn  9323: sub auto_create_password {
1.873     raeburn  9324:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9325:     my ($homeserver,$response);
1.506     raeburn  9326:     my $create_passwd = 0;
                   9327:     my $authchk = '';
1.873     raeburn  9328:     if ($udom =~ /^$match_domain$/) {
                   9329:         $homeserver = &domain($udom,'primary');
                   9330:     }
                   9331:     if ($homeserver eq '') {
                   9332:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9333:             $homeserver = &homeserver($cnum,$cdom);
                   9334:         }
                   9335:     }
                   9336:     if ($homeserver eq '') {
                   9337:         $authchk = 'nodomain';
1.506     raeburn  9338:     } else {
1.873     raeburn  9339:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9340:         if ($response eq 'refused') {
                   9341:             $authchk = 'refused';
                   9342:         } else {
1.901     albertel 9343:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9344:         }
1.506     raeburn  9345:     }
                   9346:     return ($authparam,$create_passwd,$authchk);
                   9347: }
                   9348: 
1.706     raeburn  9349: sub auto_photo_permission {
                   9350:     my ($cnum,$cdom,$students) = @_;
                   9351:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9352:     my ($outcome,$perm_reqd,$conditions) = 
                   9353: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9354:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9355: 	return (undef,undef);
                   9356:     }
1.706     raeburn  9357:     return ($outcome,$perm_reqd,$conditions);
                   9358: }
                   9359: 
                   9360: sub auto_checkphotos {
                   9361:     my ($uname,$udom,$pid) = @_;
                   9362:     my $homeserver = &homeserver($uname,$udom);
                   9363:     my ($result,$resulttype);
                   9364:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9365: 				   &escape($uname).':'.&escape($pid),
                   9366: 				   $homeserver));
1.709     albertel 9367:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9368: 	return (undef,undef);
                   9369:     }
1.706     raeburn  9370:     if ($outcome) {
                   9371:         ($result,$resulttype) = split(/:/,$outcome);
                   9372:     } 
                   9373:     return ($result,$resulttype);
                   9374: }
                   9375: 
                   9376: sub auto_photochoice {
                   9377:     my ($cnum,$cdom) = @_;
                   9378:     my $homeserver = &homeserver($cnum,$cdom);
                   9379:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9380: 						       &escape($cdom),
                   9381: 						       $homeserver)));
1.709     albertel 9382:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9383: 	return (undef,undef);
                   9384:     }
1.706     raeburn  9385:     return ($update,$comment);
                   9386: }
                   9387: 
                   9388: sub auto_photoupdate {
                   9389:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9390:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9391:     my $host=&hostname($homeserver);
1.706     raeburn  9392:     my $cmd = '';
                   9393:     my $maxtries = 1;
1.800     albertel 9394:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9395:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9396:     }
                   9397:     $cmd =~ s/%%$//;
                   9398:     $cmd = &escape($cmd);
                   9399:     my $query = 'institutionalphotos';
                   9400:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9401:     unless ($queryid=~/^\Q$host\E\_/) {
                   9402:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9403:         return 'error: '.$queryid;
                   9404:     }
                   9405:     my $reply = &get_query_reply($queryid);
                   9406:     my $tries = 1;
                   9407:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9408:         $reply = &get_query_reply($queryid);
                   9409:         $tries ++;
                   9410:     }
                   9411:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9412:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9413:     } else {
                   9414:         my @responses = split(/:/,$reply);
                   9415:         my $outcome = shift(@responses); 
                   9416:         foreach my $item (@responses) {
                   9417:             my ($key,$value) = split(/=/,$item);
                   9418:             $$photo{$key} = $value;
                   9419:         }
                   9420:         return $outcome;
                   9421:     }
                   9422:     return 'error';
                   9423: }
                   9424: 
1.521     raeburn  9425: sub auto_instcode_format {
1.793     albertel 9426:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9427: 	$cat_order) = @_;
1.521     raeburn  9428:     my $courses = '';
1.772     raeburn  9429:     my @homeservers;
1.521     raeburn  9430:     if ($caller eq 'global') {
1.841     albertel 9431: 	my %servers = &get_servers($codedom,'library');
                   9432: 	foreach my $tryserver (keys(%servers)) {
                   9433: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9434: 		push(@homeservers,$tryserver);
                   9435: 	    }
1.584     raeburn  9436:         }
1.1022    raeburn  9437:     } elsif ($caller eq 'requests') {
                   9438:         if ($codedom =~ /^$match_domain$/) {
                   9439:             my $chome = &domain($codedom,'primary');
                   9440:             unless ($chome eq 'no_host') {
                   9441:                 push(@homeservers,$chome);
                   9442:             }
                   9443:         }
1.521     raeburn  9444:     } else {
1.772     raeburn  9445:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9446:     }
1.793     albertel 9447:     foreach my $code (keys(%{$instcodes})) {
                   9448:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9449:     }
                   9450:     chop($courses);
1.772     raeburn  9451:     my $ok_response = 0;
                   9452:     my $response;
                   9453:     while (@homeservers > 0 && $ok_response == 0) {
                   9454:         my $server = shift(@homeservers); 
                   9455:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9456:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9457:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9458: 		split(/:/,$response);
1.772     raeburn  9459:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9460:             push(@{$codetitles},&str2array($codetitles_str));
                   9461:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9462:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9463:             $ok_response = 1;
                   9464:         }
                   9465:     }
                   9466:     if ($ok_response) {
1.521     raeburn  9467:         return 'ok';
1.772     raeburn  9468:     } else {
                   9469:         return $response;
1.521     raeburn  9470:     }
                   9471: }
                   9472: 
1.792     raeburn  9473: sub auto_instcode_defaults {
                   9474:     my ($domain,$returnhash,$code_order) = @_;
                   9475:     my @homeservers;
1.841     albertel 9476: 
                   9477:     my %servers = &get_servers($domain,'library');
                   9478:     foreach my $tryserver (keys(%servers)) {
                   9479: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9480: 	    push(@homeservers,$tryserver);
                   9481: 	}
1.792     raeburn  9482:     }
1.841     albertel 9483: 
1.792     raeburn  9484:     my $response;
1.841     albertel 9485:     foreach my $server (@homeservers) {
1.792     raeburn  9486:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9487:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9488: 	
                   9489: 	foreach my $pair (split(/\&/,$response)) {
                   9490: 	    my ($name,$value)=split(/\=/,$pair);
                   9491: 	    if ($name eq 'code_order') {
                   9492: 		@{$code_order} = split(/\&/,&unescape($value));
                   9493: 	    } else {
                   9494: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9495: 	    }
                   9496: 	}
                   9497: 	return 'ok';
1.792     raeburn  9498:     }
1.841     albertel 9499: 
                   9500:     return $response;
1.1003    raeburn  9501: }
                   9502: 
                   9503: sub auto_possible_instcodes {
1.1007    raeburn  9504:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9505:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9506:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9507:         return;
                   9508:     }
1.1003    raeburn  9509:     my (@homeservers,$uhome);
                   9510:     if (defined(&domain($domain,'primary'))) {
                   9511:         $uhome=&domain($domain,'primary');
                   9512:         push(@homeservers,&domain($domain,'primary'));
                   9513:     } else {
                   9514:         my %servers = &get_servers($domain,'library');
                   9515:         foreach my $tryserver (keys(%servers)) {
                   9516:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9517:                 push(@homeservers,$tryserver);
                   9518:             }
                   9519:         }
                   9520:     }
                   9521:     my $response;
                   9522:     foreach my $server (@homeservers) {
                   9523:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9524:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9525:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9526:             split(':',$response);
                   9527:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9528:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9529:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9530:             my ($name,$value)=split('=',$item);
                   9531:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9532:         }
                   9533:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9534:             my ($name,$value)=split('=',$item);
                   9535:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9536:         }
                   9537:         return 'ok';
                   9538:     }
                   9539:     return $response;
                   9540: }
1.792     raeburn  9541: 
1.1010    raeburn  9542: sub auto_courserequest_checks {
                   9543:     my ($dom) = @_;
1.1020    raeburn  9544:     my ($homeserver,%validations);
                   9545:     if ($dom =~ /^$match_domain$/) {
                   9546:         $homeserver = &domain($dom,'primary');
                   9547:     }
                   9548:     unless ($homeserver eq 'no_host') {
                   9549:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9550:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9551:             my @items = split(/&/,$response);
                   9552:             foreach my $item (@items) {
                   9553:                 my ($key,$value) = split('=',$item);
                   9554:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9555:             }
                   9556:         }
                   9557:     }
1.1010    raeburn  9558:     return %validations; 
                   9559: }
                   9560: 
1.1020    raeburn  9561: sub auto_courserequest_validation {
1.1255    raeburn  9562:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9563:     my ($homeserver,$response);
                   9564:     if ($dom =~ /^$match_domain$/) {
                   9565:         $homeserver = &domain($dom,'primary');
                   9566:     }
1.1255    raeburn  9567:     unless ($homeserver eq 'no_host') {
                   9568:         my $customdata;
                   9569:         if (ref($custominfo) eq 'HASH') {
                   9570:             $customdata = &freeze_escape($custominfo);
                   9571:         }
1.1020    raeburn  9572:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9573:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9574:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9575:                                     $customdata,$homeserver));
1.1020    raeburn  9576:     }
                   9577:     return $response;
                   9578: }
                   9579: 
1.777     albertel 9580: sub auto_validate_class_sec {
1.918     raeburn  9581:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9582:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9583:     my $ownerlist;
                   9584:     if (ref($owners) eq 'ARRAY') {
                   9585:         $ownerlist = join(',',@{$owners});
                   9586:     } else {
                   9587:         $ownerlist = $owners;
                   9588:     }
1.773     raeburn  9589:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9590:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9591:     return $response;
                   9592: }
                   9593: 
1.1367    raeburn  9594: sub auto_validate_instclasses {
                   9595:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9596:     my ($homeserver,%validations);
                   9597:     $homeserver = &homeserver($cnum,$cdom);
                   9598:     unless ($homeserver eq 'no_host') {
                   9599:         my $ownerlist;
                   9600:         if (ref($owners) eq 'ARRAY') {
                   9601:             $ownerlist = join(',',@{$owners});
                   9602:         } else {
                   9603:             $ownerlist = $owners;
                   9604:         }
                   9605:         if (ref($classesref) eq 'HASH') {
                   9606:             my $classes = &freeze_escape($classesref);
                   9607:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9608:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9609:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9610:                 my @items = split(/&/,$response);
                   9611:                 foreach my $item (@items) {
                   9612:                     my ($key,$value) = split('=',$item);
                   9613:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9614:                 }
                   9615:             }
                   9616:         }
                   9617:     }
                   9618:     return %validations;
                   9619: }
                   9620: 
1.1248    raeburn  9621: sub auto_crsreq_update {
                   9622:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9623:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9624:     my ($homeserver,%crsreqresponse);
                   9625:     if ($cdom =~ /^$match_domain$/) {
                   9626:         $homeserver = &domain($cdom,'primary');
                   9627:     }
                   9628:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9629:         my $info;
                   9630:         if (ref($inbound) eq 'HASH') {
                   9631:             $info = &freeze_escape($inbound);
                   9632:         }
                   9633:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9634:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9635:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9636:                             &escape($title).':'.&escape($code).':'.
                   9637:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9638:                             $homeserver);
1.1248    raeburn  9639:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9640:             my @items = split(/&/,$response);
                   9641:             foreach my $item (@items) {
                   9642:                 my ($key,$value) = split('=',$item);
                   9643:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9644:             }
                   9645:         }
                   9646:     }
                   9647:     return \%crsreqresponse;
                   9648: }
                   9649: 
1.1305    raeburn  9650: sub auto_export_grades {
1.1309    raeburn  9651:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9652:     my ($homeserver,%exportresponse);
                   9653:     if ($cdom =~ /^$match_domain$/) {
                   9654:         $homeserver = &domain($cdom,'primary');
                   9655:     }
                   9656:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9657:         my $info;
                   9658:         if (ref($inforef) eq 'HASH') {
                   9659:             $info = &freeze_escape($inforef);
                   9660:         }
                   9661:         if (ref($gradesref) eq 'HASH') {
                   9662:             my $grades = &freeze_escape($gradesref);
                   9663:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9664:                                 $info.':'.$grades,$homeserver);
                   9665:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9666:                 my @items = split(/&/,$response);
                   9667:                 foreach my $item (@items) {
                   9668:                     my ($key,$value) = split('=',$item);
                   9669:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9670:                 }
                   9671:             }
                   9672:         }
                   9673:     }
                   9674:     return \%exportresponse;
1.1305    raeburn  9675: }
                   9676: 
1.1287    raeburn  9677: sub check_instcode_cloning {
                   9678:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9679:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9680:         return;
                   9681:     }
                   9682:     my $canclone;
                   9683:     if (@{$code_order} > 0) {
                   9684:         my $instcoderegexp ='^';
                   9685:         my @clonecodes = split(/\&/,$cloner);
                   9686:         foreach my $item (@{$code_order}) {
                   9687:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9688:                 foreach my $pair (@clonecodes) {
                   9689:                     my ($key,$val) = split(/\=/,$pair,2);
                   9690:                     $val = &unescape($val);
                   9691:                     if ($key eq $item) {
                   9692:                         $instcoderegexp .= '('.$val.')';
                   9693:                         last;
                   9694:                     }
                   9695:                 }
                   9696:             } else {
                   9697:                 $instcoderegexp .= $codedefaults->{$item};
                   9698:             }
                   9699:         }
                   9700:         $instcoderegexp .= '$';
                   9701:         my (@from,@to);
                   9702:         eval {
                   9703:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9704:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9705:         };
                   9706:         if ((@from > 0) && (@to > 0)) {
                   9707:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9708:             if (!@diffs) {
                   9709:                 $canclone = 1;
                   9710:             }
                   9711:         }
                   9712:     }
                   9713:     return $canclone;
                   9714: }
                   9715: 
                   9716: sub default_instcode_cloning {
                   9717:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9718:     my (%codedefaults,@code_order,$canclone);
                   9719:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9720:         %codedefaults = %{$codedefaultsref};
                   9721:         @code_order = @{$codeorderref};
                   9722:     } elsif ($clonedom) {
                   9723:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9724:     }
                   9725:     if (($domdefclone) && (@code_order)) {
                   9726:         my @clonecodes = split(/\+/,$domdefclone);
                   9727:         my $instcoderegexp ='^';
                   9728:         foreach my $item (@code_order) {
                   9729:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9730:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9731:             } else {
                   9732:                 $instcoderegexp .= $codedefaults{$item};
                   9733:             }
                   9734:         }
                   9735:         $instcoderegexp .= '$';
                   9736:         my (@from,@to);
                   9737:         eval {
                   9738:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9739:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9740:         };
                   9741:         if ((@from > 0) && (@to > 0)) {
                   9742:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9743:             if (!@diffs) {
                   9744:                 $canclone = 1;
                   9745:             }
                   9746:         }
                   9747:     }
                   9748:     return $canclone;
                   9749: }
                   9750: 
1.679     raeburn  9751: # ------------------------------------------------------- Course Group routines
                   9752: 
                   9753: sub get_coursegroups {
1.809     raeburn  9754:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9755:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9756: }
                   9757: 
1.679     raeburn  9758: sub modify_coursegroup {
                   9759:     my ($cdom,$cnum,$groupsettings) = @_;
                   9760:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9761: }
                   9762: 
1.809     raeburn  9763: sub toggle_coursegroup_status {
                   9764:     my ($cdom,$cnum,$group,$action) = @_;
                   9765:     my ($from_namespace,$to_namespace);
                   9766:     if ($action eq 'delete') {
                   9767:         $from_namespace = 'coursegroups';
                   9768:         $to_namespace = 'deleted_groups';
                   9769:     } else {
                   9770:         $from_namespace = 'deleted_groups';
                   9771:         $to_namespace = 'coursegroups';
                   9772:     }
                   9773:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9774:     if (my $tmp = &error(%curr_group)) {
                   9775:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9776:         return ('read error',$tmp);
                   9777:     } else {
                   9778:         my %savedsettings = %curr_group; 
1.809     raeburn  9779:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9780:         my $deloutcome;
                   9781:         if ($result eq 'ok') {
1.809     raeburn  9782:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9783:         } else {
                   9784:             return ('write error',$result);
                   9785:         }
                   9786:         if ($deloutcome eq 'ok') {
                   9787:             return 'ok';
                   9788:         } else {
                   9789:             return ('delete error',$deloutcome);
                   9790:         }
                   9791:     }
                   9792: }
                   9793: 
1.679     raeburn  9794: sub modify_group_roles {
1.957     raeburn  9795:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9796:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9797:     my $role = 'gr/'.&escape($userprivs);
                   9798:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9799:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9800:     if ($result eq 'ok') {
                   9801:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9802:     }
1.679     raeburn  9803:     return $result;
                   9804: }
                   9805: 
                   9806: sub modify_coursegroup_membership {
                   9807:     my ($cdom,$cnum,$membership) = @_;
                   9808:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9809:     return $result;
                   9810: }
                   9811: 
1.682     raeburn  9812: sub get_active_groups {
                   9813:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9814:     my $now = time;
                   9815:     my %groups = ();
                   9816:     foreach my $key (keys(%env)) {
1.811     albertel 9817:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9818:             my ($start,$end) = split(/\./,$env{$key});
                   9819:             if (($end!=0) && ($end<$now)) { next; }
                   9820:             if (($start!=0) && ($start>$now)) { next; }
                   9821:             if ($1 eq $cdom && $2 eq $cnum) {
                   9822:                 $groups{$3} = $env{$key} ;
                   9823:             }
                   9824:         }
                   9825:     }
                   9826:     return %groups;
                   9827: }
                   9828: 
1.683     raeburn  9829: sub get_group_membership {
                   9830:     my ($cdom,$cnum,$group) = @_;
                   9831:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9832: }
                   9833: 
                   9834: sub get_users_groups {
                   9835:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9836:     my @usersgroups;
1.683     raeburn  9837:     my $cachetime=1800;
                   9838: 
                   9839:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9840:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9841:     if (defined($cached)) {
1.734     albertel 9842:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9843:     } else {  
                   9844:         $grouplist = '';
1.816     raeburn  9845:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9846:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9847:         my $access_end = $env{'course.'.$courseid.
                   9848:                               '.default_enrollment_end_date'};
                   9849:         my $now = time;
                   9850:         foreach my $key (keys(%roleshash)) {
                   9851:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9852:                 my $group = $1;
                   9853:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9854:                     my $start = $2;
                   9855:                     my $end = $1;
                   9856:                     if ($start == -1) { next; } # deleted from group
                   9857:                     if (($start!=0) && ($start>$now)) { next; }
                   9858:                     if (($end!=0) && ($end<$now)) {
                   9859:                         if ($access_end && $access_end < $now) {
                   9860:                             if ($access_end - $end < 86400) {
                   9861:                                 push(@usersgroups,$group);
1.733     raeburn  9862:                             }
                   9863:                         }
1.817     raeburn  9864:                         next;
1.733     raeburn  9865:                     }
1.817     raeburn  9866:                     push(@usersgroups,$group);
1.683     raeburn  9867:                 }
                   9868:             }
                   9869:         }
1.817     raeburn  9870:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9871:         $grouplist = join(':',@usersgroups);
                   9872:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9873:     }
1.733     raeburn  9874:     return @usersgroups;
1.683     raeburn  9875: }
                   9876: 
                   9877: sub devalidate_getgroups_cache {
                   9878:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9879:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9880: 
1.683     raeburn  9881:     my $hashid="$udom:$uname:$courseid";
                   9882:     &devalidate_cache_new('getgroups',$hashid);
                   9883: }
                   9884: 
1.12      www      9885: # ------------------------------------------------------------------ Plain Text
                   9886: 
                   9887: sub plaintext {
1.988     raeburn  9888:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9889:     if ($short =~ m{^cr/}) {
1.758     albertel 9890: 	return (split('/',$short))[-1];
                   9891:     }
1.742     raeburn  9892:     if (!defined($cid)) {
                   9893:         $cid = $env{'request.course.id'};
                   9894:     }
                   9895:     my %rolenames = (
1.1008    raeburn  9896:                       Course    => 'std',
                   9897:                       Community => 'alt1',
1.1305    raeburn  9898:                       Placement => 'std',
1.742     raeburn  9899:                     );
1.1037    raeburn  9900:     if ($cid ne '') {
                   9901:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9902:             unless ($forcedefault) {
                   9903:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9904:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9905:                 return &Apache::lonlocal::mt($roletext);
                   9906:             }
                   9907:         }
                   9908:     }
                   9909:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9910:         (defined($rolenames{$type})) && 
                   9911:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9912:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9913:     } elsif ($cid ne '') {
                   9914:         my $crstype = $env{'course.'.$cid.'.type'};
                   9915:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9916:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9917:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9918:         }
1.742     raeburn  9919:     }
1.1037    raeburn  9920:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9921: }
                   9922: 
                   9923: # ----------------------------------------------------------------- Assign Role
                   9924: 
                   9925: sub assignrole {
1.957     raeburn  9926:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9927:         $context)=@_;
1.21      www      9928:     my $mrole;
                   9929:     if ($role =~ /^cr\//) {
1.393     www      9930:         my $cwosec=$url;
1.811     albertel 9931:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9932: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9933:            my $refused = 1;
                   9934:            if ($context eq 'requestcourses') {
                   9935:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9936:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9937:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9938:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9939:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9940:                            if ($crsenv{'internal.courseowner'} eq
                   9941:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9942:                                $refused = '';
                   9943:                            }
                   9944:                        }
                   9945:                    }
                   9946:                }
                   9947:            }
                   9948:            if ($refused) {
                   9949:                &logthis('Refused custom assignrole: '.
                   9950:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9951:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9952:                return 'refused';
                   9953:            }
1.104     www      9954:         }
1.21      www      9955:         $mrole='cr';
1.678     raeburn  9956:     } elsif ($role =~ /^gr\//) {
                   9957:         my $cwogrp=$url;
1.811     albertel 9958:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9959:         unless (&allowed('mdg',$cwogrp)) {
                   9960:             &logthis('Refused group assignrole: '.
                   9961:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9962:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9963:             return 'refused';
                   9964:         }
                   9965:         $mrole='gr';
1.21      www      9966:     } else {
1.82      www      9967:         my $cwosec=$url;
1.811     albertel 9968:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9969:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9970:             my $refused;
                   9971:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9972:                 if (!(&allowed('c'.$role,$url))) {
                   9973:                     $refused = 1;
                   9974:                 }
                   9975:             } else {
                   9976:                 $refused = 1;
                   9977:             }
1.947     raeburn  9978:             if ($refused) {
1.1045    raeburn  9979:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9980:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9981:                     my %crsenv;
                   9982:                     if ($role eq 'cc' || $role eq 'co') {
                   9983:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9984:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9985:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9986:                                 if ($crsenv{'internal.courseowner'} eq 
                   9987:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9988:                                     $refused = '';
                   9989:                                 }
                   9990:                             }
                   9991:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9992:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9993:                                 if ($crsenv{'internal.courseowner'} eq 
                   9994:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9995:                                     $refused = '';
                   9996:                                 }
                   9997:                             }
                   9998:                         }
                   9999:                     }
1.1368    raeburn  10000:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10001:                     if ($role eq 'st') {
                   10002:                         $refused = '';
1.1377    raeburn  10003:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10004:                         $refused = '';
                   10005:                     }
1.1017    raeburn  10006:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10007:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10008:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10009:                         my $wrongcc;
                   10010:                         if ($cnum =~ /^$match_community$/) {
                   10011:                             $wrongcc = 1 if ($role eq 'cc');
                   10012:                         } else {
                   10013:                             $wrongcc = 1 if ($role eq 'co');
                   10014:                         }
                   10015:                         unless ($wrongcc) {
                   10016:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10017:                             if ($crsenv{'internal.courseowner'} eq 
                   10018:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10019:                                 $refused = '';
                   10020:                             }
1.1017    raeburn  10021:                         }
                   10022:                     }
1.1183    raeburn  10023:                 } elsif ($context eq 'requestauthor') {
                   10024:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10025:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10026:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10027:                             $refused = '';
                   10028:                         } else {
                   10029:                             my %domdefaults = &get_domain_defaults($udom);
                   10030:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10031:                                 my $checkbystatus;
                   10032:                                 if ($env{'user.adv'}) { 
                   10033:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10034:                                     if ($disposition eq 'automatic') {
                   10035:                                         $refused = '';
                   10036:                                     } elsif ($disposition eq '') {
                   10037:                                         $checkbystatus = 1;
                   10038:                                     } 
                   10039:                                 } else {
                   10040:                                     $checkbystatus = 1;
                   10041:                                 }
                   10042:                                 if ($checkbystatus) {
                   10043:                                     if ($env{'environment.inststatus'}) {
                   10044:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10045:                                         foreach my $type (@inststatuses) {
                   10046:                                             if (($type ne '') &&
                   10047:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10048:                                                 $refused = '';
                   10049:                                             }
                   10050:                                         }
                   10051:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10052:                                         $refused = '';
                   10053:                                     }
                   10054:                                 }
                   10055:                             }
                   10056:                         }
                   10057:                     }
1.1017    raeburn  10058:                 }
                   10059:                 if ($refused) {
1.947     raeburn  10060:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10061:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10062: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10063:                     return 'refused';
                   10064:                 }
1.932     raeburn  10065:             }
1.1131    raeburn  10066:         } elsif ($role eq 'au') {
                   10067:             if ($url ne '/'.$udom.'/') {
                   10068:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10069:                          ' to assign author role for '.$uname.':'.$udom.
                   10070:                          ' in domain: '.$url.' refused (wrong domain).');
                   10071:                 return 'refused';
                   10072:             }
1.104     www      10073:         }
1.21      www      10074:         $mrole=$role;
                   10075:     }
1.620     albertel 10076:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10077:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10078:     if ($end) { $command.='_'.$end; }
1.21      www      10079:     if ($start) {
                   10080: 	if ($end) { 
1.81      www      10081:            $command.='_'.$start; 
1.21      www      10082:         } else {
1.81      www      10083:            $command.='_0_'.$start;
1.21      www      10084:         }
                   10085:     }
1.739     raeburn  10086:     my $origstart = $start;
                   10087:     my $origend = $end;
1.957     raeburn  10088:     my $delflag;
1.357     www      10089: # actually delete
                   10090:     if ($deleteflag) {
1.373     www      10091: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10092: # modify command to delete the role
1.620     albertel 10093:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10094:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10095: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10096: # set start and finish to negative values for userrolelog
                   10097:            $start=-1;
                   10098:            $end=-1;
1.957     raeburn  10099:            $delflag = 1;
1.357     www      10100:         }
                   10101:     }
                   10102: # send command
1.349     www      10103:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10104: # log new user role if status is ok
1.349     www      10105:     if ($answer eq 'ok') {
1.663     raeburn  10106: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10107:         if (($role eq 'cc') || ($role eq 'in') ||
                   10108:             ($role eq 'ep') || ($role eq 'ad') ||
                   10109:             ($role eq 'ta') || ($role eq 'st') ||
                   10110:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10111:             ($role eq 'co')) {
1.1200    raeburn  10112: # for course roles, perform group memberships changes triggered by role change.
                   10113:             unless ($role =~ /^gr/) {
                   10114:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10115:                                                  $origstart,$selfenroll,$context);
                   10116:             }
1.1184    raeburn  10117:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10118:                            $selfenroll,$context);
                   10119:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10120:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10121:                  ($role eq 'da')) {
1.1184    raeburn  10122:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10123:                            $context);
                   10124:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10125:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10126:                              $context); 
                   10127:         }
1.1053    raeburn  10128:         if ($role eq 'cc') {
                   10129:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10130:         }
1.349     www      10131:     }
                   10132:     return $answer;
1.169     harris41 10133: }
                   10134: 
1.1053    raeburn  10135: sub autoupdate_coowners {
                   10136:     my ($url,$end,$start,$uname,$udom) = @_;
                   10137:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10138:     if (($cdom ne '') && ($cnum ne '')) {
                   10139:         my $now = time;
                   10140:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10141:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10142:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10143:             my $instcode = $coursehash{'internal.coursecode'};
                   10144:             if ($instcode ne '') {
1.1056    raeburn  10145:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10146:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10147:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10148:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   10149:                         if ($result eq 'valid') {
                   10150:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10151:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10152:                                     push(@newcoowners,$coowner);
                   10153:                                 }
                   10154:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10155:                                     push(@newcoowners,$uname.':'.$udom);
                   10156:                                 }
                   10157:                                 @newcoowners = sort(@newcoowners);
                   10158:                             } else {
                   10159:                                 push(@newcoowners,$uname.':'.$udom);
                   10160:                             }
                   10161:                         } else {
                   10162:                             if ($coursehash{'internal.co-owners'}) {
                   10163:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10164:                                     unless ($coowner eq $uname.':'.$udom) {
                   10165:                                         push(@newcoowners,$coowner);
                   10166:                                     }
                   10167:                                 }
                   10168:                                 unless (@newcoowners > 0) {
                   10169:                                     $delcoowners = 1;
                   10170:                                     $coowners = '';
                   10171:                                 }
                   10172:                             }
                   10173:                         }
                   10174:                         if (@newcoowners || $delcoowners) {
                   10175:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10176:                                             $delcoowners,@newcoowners);
                   10177:                         }
                   10178:                     }
                   10179:                 }
                   10180:             }
                   10181:         }
                   10182:     }
                   10183: }
                   10184: 
                   10185: sub store_coowners {
                   10186:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10187:     my $cid = $cdom.'_'.$cnum;
                   10188:     my ($coowners,$delresult,$putresult);
                   10189:     if (@newcoowners) {
                   10190:         $coowners = join(',',@newcoowners);
                   10191:         my %coownershash = (
                   10192:                             'internal.co-owners' => $coowners,
                   10193:                            );
                   10194:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10195:         if ($putresult eq 'ok') {
                   10196:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10197:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10198:             }
                   10199:         }
                   10200:     }
                   10201:     if ($delcoowners) {
                   10202:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10203:         if ($delresult eq 'ok') {
                   10204:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10205:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10206:             }
                   10207:         }
                   10208:     }
                   10209:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10210:         my %crsinfo =
                   10211:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10212:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10213:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10214:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10215:         }
                   10216:     }
                   10217: }
                   10218: 
1.169     harris41 10219: # -------------------------------------------------- Modify user authentication
1.197     www      10220: # Overrides without validation
                   10221: 
1.169     harris41 10222: sub modifyuserauth {
                   10223:     my ($udom,$uname,$umode,$upass)=@_;
                   10224:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10225:     my $allowed;
                   10226:     if (&allowed('mau',$udom)) {
                   10227:         $allowed = 1;
                   10228:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10229:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10230:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10231:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10232:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10233:         if (($cdom ne '') && ($cnum ne '')) {
                   10234:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10235:             if ($is_owner) {
                   10236:                 $allowed = 1;
                   10237:             }
                   10238:         }
                   10239:     }
                   10240:     unless ($allowed) { return 'refused'; }
1.197     www      10241:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10242:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10243:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10244:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10245: 		     &escape($upass),$uhome);
1.620     albertel 10246:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10247:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   10248:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   10249:     &log($udom,,$uname,$uhome,
1.620     albertel 10250:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10251:                                      $env{'user.name'}.', '.$umode.
1.197     www      10252:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 10253:     unless ($reply eq 'ok') {
1.197     www      10254:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10255: 	return 'error: '.$reply;
                   10256:     }   
1.170     harris41 10257:     return 'ok';
1.80      www      10258: }
                   10259: 
1.81      www      10260: # --------------------------------------------------------------- Modify a user
1.80      www      10261: 
1.81      www      10262: sub modifyuser {
1.206     matthew  10263:     my ($udom,    $uname, $uid,
                   10264:         $umode,   $upass, $first,
                   10265:         $middle,  $last,  $gene,
1.1058    raeburn  10266:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10267:     $udom= &LONCAPA::clean_domain($udom);
                   10268:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10269:     my $showcandelete = 'none';
                   10270:     if (ref($candelete) eq 'ARRAY') {
                   10271:         if (@{$candelete} > 0) {
                   10272:             $showcandelete = join(', ',@{$candelete});
                   10273:         }
                   10274:     }
1.81      www      10275:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10276:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10277: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10278:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10279:                                      ' desiredhome not specified'). 
1.620     albertel 10280:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10281:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10282:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10283:     my $newuser;
                   10284:     if ($uhome eq 'no_host') {
                   10285:         $newuser = 1;
1.1368    raeburn  10286:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10287:                 ($umode eq 'lti')) {
                   10288:             return 'error: more information needed to create new user';
                   10289:         }
1.1075    raeburn  10290:     }
1.80      www      10291: # ----------------------------------------------------------------- Create User
1.406     albertel 10292:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10293: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10294:         my $unhome='';
1.844     albertel 10295:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10296:             $unhome = $desiredhome;
1.620     albertel 10297: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10298: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10299:         } else { # load balancing routine for determining $unhome
1.81      www      10300:             my $loadm=10000000;
1.841     albertel 10301: 	    my %servers = &get_servers($udom,'library');
                   10302: 	    foreach my $tryserver (keys(%servers)) {
                   10303: 		my $answer=reply('load',$tryserver);
                   10304: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10305: 		    $loadm=$answer;
                   10306: 		    $unhome=$tryserver;
                   10307: 		}
1.80      www      10308: 	    }
                   10309:         }
                   10310:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10311: 	    return 'error: unable to find a home server for '.$uname.
                   10312:                    ' in domain '.$udom;
1.80      www      10313:         }
                   10314:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10315:                          &escape($upass),$unhome);
                   10316: 	unless ($reply eq 'ok') {
                   10317:             return 'error: '.$reply;
                   10318:         }   
1.230     stredwic 10319:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10320:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10321: 	    return 'error: unable verify users home machine.';
1.80      www      10322:         }
1.209     matthew  10323:     }   # End of creation of new user
1.80      www      10324: # ---------------------------------------------------------------------- Add ID
                   10325:     if ($uid) {
                   10326:        $uid=~tr/A-Z/a-z/;
                   10327:        my %uidhash=&idrget($udom,$uname);
1.196     www      10328:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10329:          && (!$forceid)) {
1.80      www      10330: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10331: 	      return 'error: user id "'.$uid.'" does not match '.
                   10332:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10333:           }
                   10334:        } else {
1.1300    raeburn  10335: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10336:        }
                   10337:     }
                   10338: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10339:     my @tmp=&get('environment',
1.899     raeburn  10340: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10341:                     'permanentemail','inststatus'],
1.134     albertel 10342: 		   $udom,$uname);
1.1075    raeburn  10343:     my (%names,%oldnames);
1.313     matthew  10344:     if ($tmp[0] =~ m/^error:.*/) { 
                   10345:         %names=(); 
                   10346:     } else {
                   10347:         %names = @tmp;
1.1075    raeburn  10348:         %oldnames = %names;
1.313     matthew  10349:     }
1.388     www      10350: #
1.1058    raeburn  10351: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10352: # of users did not contain them), do not overwrite existing values
                   10353: # unless field is in $candelete array ref.  
                   10354: #
                   10355: 
                   10356:     my @fields = ('firstname','middlename','lastname','generation',
                   10357:                   'permanentemail','id');
                   10358:     my %newvalues;
                   10359:     if (ref($candelete) eq 'ARRAY') {
                   10360:         foreach my $field (@fields) {
                   10361:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10362:                 if ($field eq 'firstname') {
                   10363:                     $names{$field} = $first;
                   10364:                 } elsif ($field eq 'middlename') {
                   10365:                     $names{$field} = $middle;
                   10366:                 } elsif ($field eq 'lastname') {
                   10367:                     $names{$field} = $last;
                   10368:                 } elsif ($field eq 'generation') { 
                   10369:                     $names{$field} = $gene;
                   10370:                 } elsif ($field eq 'permanentemail') {
                   10371:                     $names{$field} = $email;
                   10372:                 } elsif ($field eq 'id') {
                   10373:                     $names{$field}  = $uid;
                   10374:                 }
                   10375:             }
                   10376:         }
                   10377:     }
1.388     www      10378:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10379:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10380:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10381:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10382:     if ($email) {
                   10383:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10384:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10385:     }
1.899     raeburn  10386:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10387:     if (defined($inststatus)) {
                   10388:         $names{'inststatus'} = '';
                   10389:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10390:         if (ref($usertypes) eq 'HASH') {
                   10391:             my @okstatuses; 
                   10392:             foreach my $item (split(/:/,$inststatus)) {
                   10393:                 if (defined($usertypes->{$item})) {
                   10394:                     push(@okstatuses,$item);  
                   10395:                 }
                   10396:             }
                   10397:             if (@okstatuses) {
                   10398:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10399:             }
                   10400:         }
                   10401:     }
1.1075    raeburn  10402:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10403:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10404:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10405:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10406:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10407:     } else {
                   10408:         $logmsg .= ' during self creation';
                   10409:     }
1.1075    raeburn  10410:     my $changed;
                   10411:     if ($newuser) {
                   10412:         $changed = 1;
                   10413:     } else {
                   10414:         foreach my $field (@fields) {
                   10415:             if ($names{$field} ne $oldnames{$field}) {
                   10416:                 $changed = 1;
                   10417:                 last;
                   10418:             }
                   10419:         }
                   10420:     }
                   10421:     unless ($changed) {
                   10422:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10423:         &logthis($logmsg);
                   10424:         return 'ok';
                   10425:     }
                   10426:     my $reply = &put('environment', \%names, $udom,$uname);
                   10427:     if ($reply ne 'ok') { 
                   10428:         return 'error: '.$reply;
                   10429:     }
1.1087    raeburn  10430:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10431:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10432:     }
1.1075    raeburn  10433:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10434:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10435:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10436:     &logthis($logmsg);
1.134     albertel 10437:     return 'ok';
1.80      www      10438: }
                   10439: 
1.81      www      10440: # -------------------------------------------------------------- Modify student
1.80      www      10441: 
1.81      www      10442: sub modifystudent {
                   10443:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10444:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10445:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10446:     if (!$cid) {
1.620     albertel 10447: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10448: 	    return 'not_in_class';
                   10449: 	}
1.80      www      10450:     }
                   10451: # --------------------------------------------------------------- Make the user
1.81      www      10452:     my $reply=&modifyuser
1.209     matthew  10453: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10454:          $desiredhome,$email,$inststatus);
1.80      www      10455:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10456:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10457:     # student's environment
1.297     matthew  10458:     $uid = undef if (!$forceid);
1.455     albertel 10459:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10460:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10461:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10462:     return $reply;
                   10463: }
                   10464: 
                   10465: sub modify_student_enrollment {
1.1216    raeburn  10466:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10467:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10468:     my ($cdom,$cnum,$chome);
                   10469:     if (!$cid) {
1.620     albertel 10470: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10471: 	    return 'not_in_class';
                   10472: 	}
1.620     albertel 10473: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10474: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10475:     } else {
                   10476: 	($cdom,$cnum)=split(/_/,$cid);
                   10477:     }
1.620     albertel 10478:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10479:     if (!$chome) {
1.457     raeburn  10480: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10481:     }
1.455     albertel 10482:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10483:     # Make sure the user exists
1.81      www      10484:     my $uhome=&homeserver($uname,$udom);
                   10485:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10486: 	return 'error: no such user';
                   10487:     }
1.297     matthew  10488:     # Get student data if we were not given enough information
                   10489:     if (!defined($first)  || $first  eq '' || 
                   10490:         !defined($last)   || $last   eq '' || 
                   10491:         !defined($uid)    || $uid    eq '' || 
                   10492:         !defined($middle) || $middle eq '' || 
                   10493:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10494:         # They did not supply us with enough data to enroll the student, so
                   10495:         # we need to pick up more information.
1.297     matthew  10496:         my %tmp = &get('environment',
1.294     matthew  10497:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10498:                        ,$udom,$uname);
                   10499: 
1.800     albertel 10500:         #foreach my $key (keys(%tmp)) {
                   10501:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10502:         #}
1.294     matthew  10503:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10504:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10505:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10506:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10507:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10508:     }
1.556     albertel 10509:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10510:     my $user = "$uname:$udom";
                   10511:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10512:     my $reply=cput('classlist',
1.1148    raeburn  10513: 		   {$user => 
1.1314    raeburn  10514: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10515: 		   $cdom,$cnum);
1.1148    raeburn  10516:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10517:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10518:     } else { 
1.81      www      10519: 	return 'error: '.$reply;
                   10520:     }
1.297     matthew  10521:     # Add student role to user
1.83      www      10522:     my $uurl='/'.$cid;
1.81      www      10523:     $uurl=~s/\_/\//g;
                   10524:     if ($usec) {
                   10525: 	$uurl.='/'.$usec;
                   10526:     }
1.1148    raeburn  10527:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10528:                              $selfenroll,$context);
                   10529:     if ($result ne 'ok') {
                   10530:         if ($old_entry{$user} ne '') {
                   10531:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10532:         } else {
                   10533:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10534:         }
                   10535:     }
                   10536:     return $result; 
1.21      www      10537: }
                   10538: 
1.556     albertel 10539: sub format_name {
                   10540:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10541:     my $name;
                   10542:     if ($first ne 'lastname') {
                   10543: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10544:     } else {
                   10545: 	if ($lastname=~/\S/) {
                   10546: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10547: 	    $name=~s/\s+,/,/;
                   10548: 	} else {
                   10549: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10550: 	}
                   10551:     }
                   10552:     $name=~s/^\s+//;
                   10553:     $name=~s/\s+$//;
                   10554:     $name=~s/\s+/ /g;
                   10555:     return $name;
                   10556: }
                   10557: 
1.84      www      10558: # ------------------------------------------------- Write to course preferences
                   10559: 
                   10560: sub writecoursepref {
                   10561:     my ($courseid,%prefs)=@_;
                   10562:     $courseid=~s/^\///;
                   10563:     $courseid=~s/\_/\//g;
                   10564:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10565:     my $chome=homeserver($cnum,$cdomain);
                   10566:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10567: 	return 'error: no such course';
                   10568:     }
                   10569:     my $cstring='';
1.800     albertel 10570:     foreach my $pref (keys(%prefs)) {
                   10571: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10572:     }
1.84      www      10573:     $cstring=~s/\&$//;
                   10574:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10575: }
                   10576: 
                   10577: # ---------------------------------------------------------- Make/modify course
                   10578: 
                   10579: sub createcourse {
1.741     raeburn  10580:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10581:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10582:     $url=&declutter($url);
                   10583:     my $cid='';
1.1028    raeburn  10584:     if ($context eq 'requestcourses') {
                   10585:         my $can_create = 0;
                   10586:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10587:         if ($udom eq $ownerdom) {
                   10588:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10589:                                   $context)) {
                   10590:                 $can_create = 1;
                   10591:             }
                   10592:         } else {
                   10593:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10594:                                            $category);
                   10595:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10596:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10597:                 if (@curr > 0) {
                   10598:                     my @options = qw(approval validate autolimit);
                   10599:                     my $optregex = join('|',@options);
                   10600:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10601:                         $can_create = 1;
                   10602:                     }
                   10603:                 }
                   10604:             }
                   10605:         }
                   10606:         if ($can_create) {
                   10607:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10608:                 unless (&allowed('ccc',$udom)) {
                   10609:                     return 'refused'; 
                   10610:                 }
1.1017    raeburn  10611:             }
                   10612:         } else {
                   10613:             return 'refused';
                   10614:         }
1.1028    raeburn  10615:     } elsif (!&allowed('ccc',$udom)) {
                   10616:         return 'refused';
1.84      www      10617:     }
1.1011    raeburn  10618: # --------------------------------------------------------------- Get Unique ID
                   10619:     my $uname;
                   10620:     if ($cnum =~ /^$match_courseid$/) {
                   10621:         my $chome=&homeserver($cnum,$udom,'true');
                   10622:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10623:             $uname = $cnum;
                   10624:         } else {
1.1038    raeburn  10625:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10626:         }
                   10627:     } else {
1.1038    raeburn  10628:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10629:     }
                   10630:     return $uname if ($uname =~ /^error/);
                   10631: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10632:     if (!defined($course_server)) {
                   10633:         if (defined(&domain($udom,'primary'))) {
                   10634:             $course_server = &domain($udom,'primary');
                   10635:         } else {
                   10636:             $course_server = $env{'user.home'}; 
                   10637:         }
                   10638:     }
                   10639:     my %host_servers =
                   10640:         &Apache::lonnet::get_servers($udom,'library');
                   10641:     unless ($host_servers{$course_server}) {
                   10642:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10643:     }
1.84      www      10644: # ------------------------------------------------------------- Make the course
                   10645:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10646:                       $course_server);
1.84      www      10647:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10648:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10649:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10650: 	return 'error: no such course';
                   10651:     }
1.271     www      10652: # ----------------------------------------------------------------- Course made
1.516     raeburn  10653: # log existence
1.1029    raeburn  10654:     my $now = time;
1.918     raeburn  10655:     my $newcourse = {
                   10656:                     $udom.'_'.$uname => {
1.921     raeburn  10657:                                      description => $description,
                   10658:                                      inst_code   => $inst_code,
                   10659:                                      owner       => $course_owner,
                   10660:                                      type        => $crstype,
1.1029    raeburn  10661:                                      creator     => $env{'user.name'}.':'.
                   10662:                                                     $env{'user.domain'},
                   10663:                                      created     => $now,
                   10664:                                      context     => $context,
1.918     raeburn  10665:                                                 },
                   10666:                     };
1.921     raeburn  10667:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10668: # set toplevel url
1.271     www      10669:     my $topurl=$url;
                   10670:     unless ($nonstandard) {
                   10671: # ------------------------------------------ For standard courses, make top url
                   10672:         my $mapurl=&clutter($url);
1.278     www      10673:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10674:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10675: <map>
                   10676: <resource id="1" type="start"></resource>
                   10677: <resource id="2" src="$mapurl"></resource>
                   10678: <resource id="3" type="finish"></resource>
                   10679: <link index="1" from="1" to="2"></link>
                   10680: <link index="2" from="2" to="3"></link>
                   10681: </map>
                   10682: ENDINITMAP
                   10683:         $topurl=&declutter(
1.638     albertel 10684:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10685:                           );
                   10686:     }
                   10687: # ----------------------------------------------------------- Write preferences
1.84      www      10688:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10689:                      ('description'              => $description,
                   10690:                       'url'                      => $topurl,
                   10691:                       'internal.creator'         => $env{'user.name'}.':'.
                   10692:                                                     $env{'user.domain'},
                   10693:                       'internal.created'         => $now,
                   10694:                       'internal.creationcontext' => $context)
                   10695:                     );
1.84      www      10696:     return '/'.$udom.'/'.$uname;
                   10697: }
                   10698: 
1.1011    raeburn  10699: # ------------------------------------------------------------------- Create ID
                   10700: sub generate_coursenum {
1.1038    raeburn  10701:     my ($udom,$crstype) = @_;
1.1011    raeburn  10702:     my $domdesc = &domain($udom);
                   10703:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10704:     my $first;
                   10705:     if ($crstype eq 'Community') {
                   10706:         $first = '0';
                   10707:     } else {
                   10708:         $first = int(1+rand(9)); 
                   10709:     } 
                   10710:     my $uname=$first.
1.1011    raeburn  10711:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10712:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10713:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10714: # ----------------------------------------------- Make sure that does not exist
                   10715:     my $uhome=&homeserver($uname,$udom,'true');
                   10716:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10717:         if ($crstype eq 'Community') {
                   10718:             $first = '0';
                   10719:         } else {
                   10720:             $first = int(1+rand(9));
                   10721:         }
                   10722:         $uname=$first.
1.1011    raeburn  10723:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10724:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10725:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10726:         $uhome=&homeserver($uname,$udom,'true');
                   10727:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10728:             return 'error: unable to generate unique course-ID';
                   10729:         }
                   10730:     }
                   10731:     return $uname;
                   10732: }
                   10733: 
1.813     albertel 10734: sub is_course {
1.1167    droeschl 10735:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10736:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10737: 
1.1381    raeburn  10738:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10739:     my $uhome=&homeserver($cnum,$cdom);
                   10740:     my $iscourse;
                   10741:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10742:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10743:     } else {
                   10744:         my $hashid = $cdom.':'.$cnum;
                   10745:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10746:         unless (defined($cached)) {
                   10747:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10748:                                         $cnum,undef,undef,'.');
                   10749:             $iscourse = 0;
                   10750:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10751:                 $iscourse = 1;
                   10752:             }
                   10753:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10754:         }
                   10755:     }
                   10756:     return unless ($iscourse);
1.1167    droeschl 10757:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10758: }
                   10759: 
1.1015    raeburn  10760: sub store_userdata {
                   10761:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10762:     my $result;
1.1016    raeburn  10763:     if ($datakey ne '') {
1.1013    raeburn  10764:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10765:             if ($udom eq '' || $uname eq '') {
                   10766:                 $udom = $env{'user.domain'};
                   10767:                 $uname = $env{'user.name'};
                   10768:             }
                   10769:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10770:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10771:                 $result = 'error: no_host';
                   10772:             } else {
                   10773:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10774:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10775: 
                   10776:                 my $namevalue='';
                   10777:                 foreach my $key (keys(%{$storehash})) {
                   10778:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10779:                 }
                   10780:                 $namevalue=~s/\&$//;
1.1224    raeburn  10781:                 unless ($namespace eq 'courserequests') {
                   10782:                     $datakey = &escape($datakey);
                   10783:                 }
1.1105    raeburn  10784:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10785:                                   $namevalue,$uhome);
1.1013    raeburn  10786:             }
                   10787:         } else {
                   10788:             $result = 'error: data to store was not a hash reference'; 
                   10789:         }
                   10790:     } else {
                   10791:         $result= 'error: invalid requestkey'; 
                   10792:     }
                   10793:     return $result;
                   10794: }
                   10795: 
1.21      www      10796: # ---------------------------------------------------------- Assign Custom Role
                   10797: 
                   10798: sub assigncustomrole {
1.957     raeburn  10799:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10800:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10801:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10802: }
                   10803: 
                   10804: # ----------------------------------------------------------------- Revoke Role
                   10805: 
                   10806: sub revokerole {
1.957     raeburn  10807:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10808:     my $now=time;
1.965     raeburn  10809:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10810: }
                   10811: 
                   10812: # ---------------------------------------------------------- Revoke Custom Role
                   10813: 
                   10814: sub revokecustomrole {
1.957     raeburn  10815:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10816:     my $now=time;
1.357     www      10817:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10818:            $deleteflag,$selfenroll,$context);
1.17      www      10819: }
                   10820: 
1.533     banghart 10821: # ------------------------------------------------------------ Disk usage
1.535     albertel 10822: sub diskusage {
1.955     raeburn  10823:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10824:     $directorypath =~ s/\/$//;
                   10825:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10826:                        .&escape($getpropath).':'.&escape($uname).':'
                   10827:                        .&escape($udom),homeserver($uname,$udom));
                   10828:     if ($listing eq 'unknown_cmd') {
                   10829:         if ($getpropath) {
                   10830:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10831:         }
                   10832:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10833:     }
1.514     albertel 10834:     return $listing;
1.512     banghart 10835: }
                   10836: 
1.566     banghart 10837: sub is_locked {
1.1096    raeburn  10838:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10839:     my @check;
                   10840:     my $is_locked;
1.1093    raeburn  10841:     push (@check,$file_name);
1.613     albertel 10842:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10843: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10844:     my ($tmp)=keys(%locked);
                   10845:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10846:     
1.566     banghart 10847:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10848:         $is_locked = 'false';
                   10849:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10850:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10851:                $is_locked = 'true';
1.1096    raeburn  10852:                if (ref($which) eq 'ARRAY') {
                   10853:                    push(@{$which},$entry);
                   10854:                } else {
                   10855:                    last;
                   10856:                }
1.745     raeburn  10857:            }
                   10858:        }
1.566     banghart 10859:     } else {
                   10860:         $is_locked = 'false';
                   10861:     }
1.1093    raeburn  10862:     return $is_locked;
1.566     banghart 10863: }
                   10864: 
1.759     albertel 10865: sub declutter_portfile {
                   10866:     my ($file) = @_;
1.833     albertel 10867:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10868:     return $file;
                   10869: }
                   10870: 
1.559     banghart 10871: # ------------------------------------------------------------- Mark as Read Only
                   10872: 
                   10873: sub mark_as_readonly {
                   10874:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10875:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10876:     my ($tmp)=keys(%current_permissions);
                   10877:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10878:     foreach my $file (@{$files}) {
1.759     albertel 10879: 	$file = &declutter_portfile($file);
1.561     banghart 10880:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10881:     }
1.613     albertel 10882:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10883:     return;
                   10884: }
                   10885: 
1.572     banghart 10886: # ------------------------------------------------------------Save Selected Files
                   10887: 
                   10888: sub save_selected_files {
                   10889:     my ($user, $path, @files) = @_;
                   10890:     my $filename = $user."savedfiles";
1.573     banghart 10891:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10892:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10893:     foreach my $file (@files) {
1.620     albertel 10894:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10895:     }
                   10896:     foreach my $file (@other_files) {
1.574     banghart 10897:         print (OUT $file."\n");
1.572     banghart 10898:     }
1.574     banghart 10899:     close (OUT);
1.572     banghart 10900:     return 'ok';
                   10901: }
                   10902: 
1.574     banghart 10903: sub clear_selected_files {
                   10904:     my ($user) = @_;
                   10905:     my $filename = $user."savedfiles";
1.1359    raeburn  10906:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10907:     print (OUT undef);
                   10908:     close (OUT);
                   10909:     return ("ok");    
                   10910: }
                   10911: 
1.572     banghart 10912: sub files_in_path {
                   10913:     my ($user, $path) = @_;
                   10914:     my $filename = $user."savedfiles";
                   10915:     my %return_files;
1.1359    raeburn  10916:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10917:     while (my $line_in = <IN>) {
1.574     banghart 10918:         chomp ($line_in);
                   10919:         my @paths_and_file = split (m!/!, $line_in);
                   10920:         my $file_part = pop (@paths_and_file);
                   10921:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10922:         $path_part.='/';
                   10923:         my $path_and_file = $path_part.$file_part;
                   10924:         if ($path_part eq $path) {
                   10925:             $return_files{$file_part}= 'selected';
                   10926:         }
                   10927:     }
1.574     banghart 10928:     close (IN);
                   10929:     return (\%return_files);
1.572     banghart 10930: }
                   10931: 
                   10932: # called in portfolio select mode, to show files selected NOT in current directory
                   10933: sub files_not_in_path {
                   10934:     my ($user, $path) = @_;
                   10935:     my $filename = $user."savedfiles";
                   10936:     my @return_files;
                   10937:     my $path_part;
1.1359    raeburn  10938:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10939:     while (my $line = <IN>) {
1.572     banghart 10940:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10941:         my @paths_and_file = split(m|/|, $line);
                   10942:         my $file_part = pop(@paths_and_file);
                   10943:         chomp($file_part);
                   10944:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10945:         $path_part .= '/';
                   10946:         my $path_and_file = $path_part.$file_part;
                   10947:         if ($path_part ne $path) {
1.800     albertel 10948:             push(@return_files, ($path_and_file));
1.572     banghart 10949:         }
                   10950:     }
1.800     albertel 10951:     close(OUT);
1.574     banghart 10952:     return (@return_files);
1.572     banghart 10953: }
                   10954: 
1.1273    raeburn  10955: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10956:  
                   10957: sub portfiles_versioning {
                   10958:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10959:     my $portfolio_root = '/userfiles/portfolio';
                   10960:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10961:     foreach my $file (@{$portfiles}) {
                   10962:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10963:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10964:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10965:         my $getpropath = 1;
                   10966:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10967:                                              $stu_name,$getpropath);
                   10968:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10969:         my $new_answer = 
                   10970:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10971:         if ($new_answer ne 'problem getting file') {
                   10972:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10973:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10974:                               [$symb,$env{'request.course.id'},'graded']);
                   10975:         }
                   10976:     }
                   10977: }
                   10978: 
                   10979: sub get_next_version {
                   10980:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10981:     my $version;
                   10982:     if (ref($dir_list) eq 'ARRAY') {
                   10983:         foreach my $row (@{$dir_list}) {
                   10984:             my ($file) = split(/\&/,$row,2);
                   10985:             my ($file_name,$file_version,$file_ext) =
                   10986:                 &file_name_version_ext($file);
                   10987:             if (($file_name eq $answer_name) &&
                   10988:                 ($file_ext eq $answer_ext)) {
                   10989:                      # gets here if filename and extension match,
                   10990:                      # regardless of version
                   10991:                 if ($file_version ne '') {
                   10992:                     # a versioned file is found  so save it for later
                   10993:                     if ($file_version > $version) {
                   10994:                         $version = $file_version;
                   10995:                     }
                   10996:                 }
                   10997:             }
                   10998:         }
                   10999:     }
                   11000:     $version ++;
                   11001:     return($version);
                   11002: }
                   11003: 
                   11004: sub version_selected_portfile {
                   11005:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11006:     my ($answer_name,$answer_ver,$answer_ext) =
                   11007:         &file_name_version_ext($file_name);
                   11008:     my $new_answer;
                   11009:     $env{'form.copy'} =
                   11010:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11011:     if($env{'form.copy'} eq '-1') {
                   11012:         $new_answer = 'problem getting file';
                   11013:     } else {
                   11014:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11015:         my $copy_result = 
                   11016:             &finishuserfileupload($stu_name,$domain,'copy',
                   11017:                                   '/portfolio'.$directory.$new_answer);
                   11018:     }
                   11019:     undef($env{'form.copy'});
                   11020:     return ($new_answer);
                   11021: }
                   11022: 
                   11023: sub file_name_version_ext {
                   11024:     my ($file)=@_;
                   11025:     my @file_parts = split(/\./, $file);
                   11026:     my ($name,$version,$ext);
                   11027:     if (@file_parts > 1) {
                   11028:         $ext=pop(@file_parts);
                   11029:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11030:             $version=pop(@file_parts);
                   11031:         }
                   11032:         $name=join('.',@file_parts);
                   11033:     } else {
                   11034:         $name=join('.',@file_parts);
                   11035:     }
                   11036:     return($name,$version,$ext);
                   11037: }
                   11038: 
1.745     raeburn  11039: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11040: 
1.745     raeburn  11041: sub get_portfile_permissions {
                   11042:     my ($domain,$user) = @_;
1.613     albertel 11043:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11044:     my ($tmp)=keys(%current_permissions);
                   11045:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11046:     return \%current_permissions;
                   11047: }
                   11048: 
                   11049: #---------------------------------------------Get portfolio file access controls
                   11050: 
1.749     raeburn  11051: sub get_access_controls {
1.745     raeburn  11052:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11053:     my %access;
                   11054:     my $real_file = $file;
                   11055:     $file =~ s/\.meta$//;
1.745     raeburn  11056:     if (defined($file)) {
1.749     raeburn  11057:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11058:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11059:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11060:             }
                   11061:         }
1.745     raeburn  11062:     } else {
1.749     raeburn  11063:         foreach my $key (keys(%{$current_permissions})) {
                   11064:             if ($key =~ /\0accesscontrol$/) {
                   11065:                 if (defined($group)) {
                   11066:                     if ($key !~ m-^\Q$group\E/-) {
                   11067:                         next;
                   11068:                     }
                   11069:                 }
                   11070:                 my ($fullpath) = split(/\0/,$key);
                   11071:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11072:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11073:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11074:                     }
                   11075:                 }
                   11076:             }
                   11077:         }
                   11078:     }
                   11079:     return %access;
                   11080: }
                   11081: 
                   11082: sub modify_access_controls {
                   11083:     my ($file_name,$changes,$domain,$user)=@_;
                   11084:     my ($outcome,$deloutcome);
                   11085:     my %store_permissions;
                   11086:     my %new_values;
                   11087:     my %new_control;
                   11088:     my %translation;
                   11089:     my @deletions = ();
                   11090:     my $now = time;
                   11091:     if (exists($$changes{'activate'})) {
                   11092:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11093:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11094:             my $numnew = scalar(@newitems);
                   11095:             for (my $i=0; $i<$numnew; $i++) {
                   11096:                 my $newkey = $newitems[$i];
                   11097:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11098:                 if ($newkey =~ /^\d+:/) { 
                   11099:                     $newkey =~ s/^(\d+)/$newid/;
                   11100:                     $translation{$1} = $newid;
                   11101:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11102:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11103:                     $translation{$1} = $newid;
                   11104:                 }
1.749     raeburn  11105:                 $new_values{$file_name."\0".$newkey} = 
                   11106:                                           $$changes{'activate'}{$newitems[$i]};
                   11107:                 $new_control{$newkey} = $now;
                   11108:             }
                   11109:         }
                   11110:     }
                   11111:     my %todelete;
                   11112:     my %changed_items;
                   11113:     foreach my $action ('delete','update') {
                   11114:         if (exists($$changes{$action})) {
                   11115:             if (ref($$changes{$action}) eq 'HASH') {
                   11116:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11117:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11118:                     if ($action eq 'delete') { 
                   11119:                         $todelete{$itemnum} = 1;
                   11120:                     } else {
                   11121:                         $changed_items{$itemnum} = $key;
                   11122:                     }
                   11123:                 }
1.745     raeburn  11124:             }
                   11125:         }
1.749     raeburn  11126:     }
                   11127:     # get lock on access controls for file.
                   11128:     my $lockhash = {
                   11129:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11130:                                                        ':'.$env{'user.domain'},
                   11131:                    }; 
                   11132:     my $tries = 0;
                   11133:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11134:    
1.1288    damieng  11135:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11136:         $tries ++;
1.1289    damieng  11137:         sleep(0.1);
1.749     raeburn  11138:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11139:     }
                   11140:     if ($gotlock eq 'ok') {
                   11141:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11142:         my ($tmp)=keys(%curr_permissions);
                   11143:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11144:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11145:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11146:             if (ref($curr_controls) eq 'HASH') {
                   11147:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11148:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11149:                     if (defined($todelete{$itemnum})) {
                   11150:                         push(@deletions,$file_name."\0".$control_item);
                   11151:                     } else {
                   11152:                         if (defined($changed_items{$itemnum})) {
                   11153:                             $new_control{$changed_items{$itemnum}} = $now;
                   11154:                             push(@deletions,$file_name."\0".$control_item);
                   11155:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11156:                         } else {
                   11157:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11158:                         }
                   11159:                     }
1.745     raeburn  11160:                 }
                   11161:             }
                   11162:         }
1.970     raeburn  11163:         my ($group);
                   11164:         if (&is_course($domain,$user)) {
                   11165:             ($group,my $file) = split(/\//,$file_name,2);
                   11166:         }
1.749     raeburn  11167:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11168:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11169:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11170:         #  remove lock
                   11171:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11172:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11173:         my $sqlresult =
1.970     raeburn  11174:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11175:                                     $group);
1.749     raeburn  11176:     } else {
                   11177:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11178:     }
1.749     raeburn  11179:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11180: }
                   11181: 
1.827     raeburn  11182: sub make_public_indefinitely {
1.1271    raeburn  11183:     my (@requrl) = @_;
                   11184:     return &automated_portfile_access('public',\@requrl);
                   11185: }
                   11186: 
                   11187: sub automated_portfile_access {
                   11188:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11189:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11190:         return 'invalid';
                   11191:     }
1.1271    raeburn  11192:     my %urls;
                   11193:     if (ref($addsref) eq 'ARRAY') {
                   11194:         foreach my $requrl (@{$addsref}) {
                   11195:             if (&is_portfolio_url($requrl)) {
                   11196:                 unless (exists($urls{$requrl})) {
                   11197:                     $urls{$requrl} = 'add';
                   11198:                 }
                   11199:             }
                   11200:         }
                   11201:     }
                   11202:     if (ref($delsref) eq 'ARRAY') {
                   11203:         foreach my $requrl (@{$delsref}) { 
                   11204:             if (&is_portfolio_url($requrl)) {
                   11205:                 unless (exists($urls{$requrl})) {
                   11206:                     $urls{$requrl} = 'delete'; 
                   11207:                 }
                   11208:             }
                   11209:         }
                   11210:     }
                   11211:     unless (keys(%urls)) {
                   11212:         return 'invalid';
                   11213:     }
                   11214:     my $ip;
                   11215:     if ($accesstype eq 'ip') {
                   11216:         if (ref($info) eq 'HASH') {
                   11217:             if ($info->{'ip'} ne '') {
                   11218:                 $ip = $info->{'ip'};
                   11219:             }
                   11220:         }
                   11221:         if ($ip eq '') {
                   11222:             return 'invalid';
                   11223:         }
                   11224:     }
                   11225:     my $errors;
1.827     raeburn  11226:     my $now = time;
1.1271    raeburn  11227:     my %current_perms;
                   11228:     foreach my $requrl (sort(keys(%urls))) {
                   11229:         my $action;
                   11230:         if ($urls{$requrl} eq 'add') {
                   11231:             $action = 'activate';
                   11232:         } else {
                   11233:             $action = 'none';
                   11234:         }
                   11235:         my $aclnum = 0;
1.827     raeburn  11236:         my (undef,$udom,$unum,$file_name,$group) =
                   11237:             &parse_portfolio_url($requrl);
1.1271    raeburn  11238:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11239:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11240:         }
                   11241:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11242:                                                    $group,$file_name);
                   11243:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11244:             my ($num,$scope,$end,$start) = 
                   11245:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11246:             if ($scope eq $accesstype) {
                   11247:                 if (($start <= $now) && ($end == 0)) {
                   11248:                     if ($accesstype eq 'ip') {
                   11249:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11250:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11251:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11252:                                     if ($urls{$requrl} eq 'add') {
                   11253:                                         $action = 'none';
                   11254:                                         last;
                   11255:                                     } else {
                   11256:                                         $action = 'delete';
                   11257:                                         $aclnum = $num;
                   11258:                                         last;
                   11259:                                     }
                   11260:                                 }
                   11261:                             }
                   11262:                         }
                   11263:                     } elsif ($accesstype eq 'public') {
                   11264:                         if ($urls{$requrl} eq 'add') {
                   11265:                             $action = 'none';
                   11266:                             last;
                   11267:                         } else {
                   11268:                             $action = 'delete';
                   11269:                             $aclnum = $num;
                   11270:                             last;
                   11271:                         }
                   11272:                     }
                   11273:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11274:                     $action = 'update';
                   11275:                     $aclnum = $num;
1.1271    raeburn  11276:                     last;
1.827     raeburn  11277:                 }
                   11278:             }
                   11279:         }
                   11280:         if ($action eq 'none') {
1.1271    raeburn  11281:             next;
1.827     raeburn  11282:         } else {
                   11283:             my %changes;
                   11284:             my $newend = 0;
                   11285:             my $newstart = $now;
1.1271    raeburn  11286:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11287:             $changes{$action}{$newkey} = {
1.1271    raeburn  11288:                 type => $accesstype,
1.827     raeburn  11289:                 time => {
                   11290:                     start => $newstart,
                   11291:                     end   => $newend,
                   11292:                 },
                   11293:             };
1.1271    raeburn  11294:             if ($accesstype eq 'ip') {
                   11295:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11296:             }
1.827     raeburn  11297:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11298:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11299:             unless ($outcome eq 'ok') {
                   11300:                 $errors .= $outcome.' ';
                   11301:             }
1.827     raeburn  11302:         }
1.1271    raeburn  11303:     }
                   11304:     if ($errors) {
                   11305:         $errors =~ s/\s$//;
                   11306:         return $errors;
1.827     raeburn  11307:     } else {
1.1271    raeburn  11308:         return 'ok';
1.827     raeburn  11309:     }
                   11310: }
                   11311: 
1.745     raeburn  11312: #------------------------------------------------------Get Marked as Read Only
                   11313: 
                   11314: sub get_marked_as_readonly {
                   11315:     my ($domain,$user,$what,$group) = @_;
                   11316:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11317:     my @readonly_files;
1.629     banghart 11318:     my $cmp1=$what;
                   11319:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11320:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11321:         if (defined($group)) {
                   11322:             if ($file_name !~ m-^\Q$group\E/-) {
                   11323:                 next;
                   11324:             }
                   11325:         }
1.561     banghart 11326:         if (ref($value) eq "ARRAY"){
                   11327:             foreach my $stored_what (@{$value}) {
1.629     banghart 11328:                 my $cmp2=$stored_what;
1.759     albertel 11329:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11330:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11331:                 }
1.629     banghart 11332:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11333:                     push(@readonly_files, $file_name);
1.745     raeburn  11334:                     last;
1.563     banghart 11335:                 } elsif (!defined($what)) {
                   11336:                     push(@readonly_files, $file_name);
1.745     raeburn  11337:                     last;
1.561     banghart 11338:                 }
                   11339:             }
1.745     raeburn  11340:         }
1.561     banghart 11341:     }
                   11342:     return @readonly_files;
                   11343: }
1.577     banghart 11344: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11345: 
1.577     banghart 11346: sub get_marked_as_readonly_hash {
1.745     raeburn  11347:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11348:     my %readonly_files;
1.745     raeburn  11349:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11350:         if (defined($group)) {
                   11351:             if ($file_name !~ m-^\Q$group\E/-) {
                   11352:                 next;
                   11353:             }
                   11354:         }
1.577     banghart 11355:         if (ref($value) eq "ARRAY"){
                   11356:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11357:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11358:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11359:                         if ($lock_descriptor eq 'graded') {
                   11360:                             $readonly_files{$file_name} = 'graded';
                   11361:                         } elsif ($lock_descriptor eq 'handback') {
                   11362:                             $readonly_files{$file_name} = 'handback';
                   11363:                         } else {
                   11364:                             if (!exists($readonly_files{$file_name})) {
                   11365:                                 $readonly_files{$file_name} = 'locked';
                   11366:                             }
                   11367:                         }
1.745     raeburn  11368:                     }
1.750     banghart 11369:                 } 
1.577     banghart 11370:             }
                   11371:         } 
                   11372:     }
                   11373:     return %readonly_files;
                   11374: }
1.559     banghart 11375: # ------------------------------------------------------------ Unmark as Read Only
                   11376: 
                   11377: sub unmark_as_readonly {
1.629     banghart 11378:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11379:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11380:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11381:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11382:     my $symb_crs = $what;
                   11383:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11384:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11385:     my ($tmp)=keys(%current_permissions);
                   11386:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11387:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11388:     foreach my $file (@readonly_files) {
1.759     albertel 11389: 	my $clean_file = &declutter_portfile($file);
                   11390: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11391: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11392:         my @new_locks;
                   11393:         my @del_keys;
                   11394:         if (ref($current_locks) eq "ARRAY"){
                   11395:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11396:                 my $compare=$locker;
1.749     raeburn  11397:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11398:                     $compare=join('',@{$locker});
1.746     raeburn  11399:                     if ($compare ne $symb_crs) {
                   11400:                         push(@new_locks, $locker);
                   11401:                     }
1.563     banghart 11402:                 }
                   11403:             }
1.650     albertel 11404:             if (scalar(@new_locks) > 0) {
1.563     banghart 11405:                 $current_permissions{$file} = \@new_locks;
                   11406:             } else {
                   11407:                 push(@del_keys, $file);
1.613     albertel 11408:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11409:                 delete($current_permissions{$file});
1.563     banghart 11410:             }
                   11411:         }
1.561     banghart 11412:     }
1.613     albertel 11413:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11414:     return;
                   11415: }
1.512     banghart 11416: 
1.17      www      11417: # ------------------------------------------------------------ Directory lister
                   11418: 
                   11419: sub dirlist {
1.955     raeburn  11420:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11421:     $uri=~s/^\///;
                   11422:     $uri=~s/\/$//;
1.253     stredwic 11423:     my ($udom, $uname);
1.955     raeburn  11424:     if ($getuserdir) {
1.253     stredwic 11425:         $udom = $userdomain;
                   11426:         $uname = $username;
1.955     raeburn  11427:     } else {
                   11428:         (undef,$udom,$uname)=split(/\//,$uri);
                   11429:         if(defined($userdomain)) {
                   11430:             $udom = $userdomain;
                   11431:         }
                   11432:         if(defined($username)) {
                   11433:             $uname = $username;
                   11434:         }
1.253     stredwic 11435:     }
1.955     raeburn  11436:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11437: 
1.955     raeburn  11438:     $dirRoot = $perlvar{'lonDocRoot'};
                   11439:     if (defined($getpropath)) {
                   11440:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11441:         $dirRoot =~ s/\/$//;
1.955     raeburn  11442:     } elsif (defined($getuserdir)) {
                   11443:         my $subdir=$uname.'__';
                   11444:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11445:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11446:                    ."/$udom/$subdir/$uname";
                   11447:     } elsif (defined($alternateRoot)) {
                   11448:         $dirRoot = $alternateRoot;
1.751     banghart 11449:     }
1.253     stredwic 11450: 
                   11451:     if($udom) {
                   11452:         if($uname) {
1.1135    raeburn  11453:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11454:             if ($uhome eq 'no_host') {
                   11455:                 return ([],'no_host');
                   11456:             }
1.955     raeburn  11457:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11458:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11459:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11460:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11461:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11462:             } else {
                   11463:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11464:             }
1.605     matthew  11465:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11466:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11467:                 @listing_results = split(/:/,$listing);
                   11468:             } else {
                   11469:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11470:             }
1.1135    raeburn  11471:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11472:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11473:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11474:                 return ([],$listing);
                   11475:             } else {
                   11476:                 return (\@listing_results);
1.1135    raeburn  11477:             }
1.955     raeburn  11478:         } elsif(!$alternateRoot) {
1.1136    raeburn  11479:             my (%allusers,%listerror);
1.841     albertel 11480: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11481:  	    foreach my $tryserver (keys(%servers)) {
                   11482:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11483:                                   &escape($udom),$tryserver);
                   11484:                 if ($listing eq 'unknown_cmd') {
                   11485: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11486: 				      $udom, $tryserver);
                   11487:                 } else {
                   11488:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11489:                 }
1.841     albertel 11490: 		if ($listing eq 'unknown_cmd') {
                   11491: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11492: 				      $udom, $tryserver);
                   11493: 		    @listing_results = split(/:/,$listing);
                   11494: 		} else {
                   11495: 		    @listing_results =
                   11496: 			map { &unescape($_); } split(/:/,$listing);
                   11497: 		}
1.1136    raeburn  11498:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11499:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11500:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11501:                     $listerror{$tryserver} = $listing;
                   11502:                 } else {
1.841     albertel 11503: 		    foreach my $line (@listing_results) {
                   11504: 			my ($entry) = split(/&/,$line,2);
                   11505: 			$allusers{$entry} = 1;
                   11506: 		    }
                   11507: 		}
1.253     stredwic 11508:             }
1.1136    raeburn  11509:             my @alluserslist=();
1.800     albertel 11510:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11511:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11512:             }
1.1318    droeschl 11513: 
                   11514:             if (!%listerror) {
                   11515:                 # no errors
                   11516:                 return (\@alluserslist);
                   11517:             } elsif (scalar(keys(%servers)) == 1) {
                   11518:                 # one library server, one error 
                   11519:                 my ($key) = keys(%listerror);
                   11520:                 return (\@alluserslist, $listerror{$key});
                   11521:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11522:                 # con_lost indicates that we might miss data from at least one
                   11523:                 # library server
                   11524:                 return (\@alluserslist, 'con_lost');
                   11525:             } else {
                   11526:                 # multiple library servers and no con_lost -> data should be
                   11527:                 # complete. 
                   11528:                 return (\@alluserslist);
                   11529:             }
                   11530: 
1.253     stredwic 11531:         } else {
1.1136    raeburn  11532:             return ([],'missing username');
1.253     stredwic 11533:         }
1.955     raeburn  11534:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11535:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11536:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11537:         return (\@all_domains);
1.955     raeburn  11538:     } else {
1.1136    raeburn  11539:         return ([],'missing domain');
1.275     stredwic 11540:     }
                   11541: }
                   11542: 
                   11543: # --------------------------------------------- GetFileTimestamp
                   11544: # This function utilizes dirlist and returns the date stamp for
                   11545: # when it was last modified.  It will also return an error of -1
                   11546: # if an error occurs
                   11547: 
                   11548: sub GetFileTimestamp {
1.955     raeburn  11549:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11550:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11551:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11552:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11553:                                     undef,$getuserdir);
                   11554:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11555:         return -1;
                   11556:     }
                   11557:     if (ref($fileref) eq 'ARRAY') {
                   11558:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11559:         # @stats contains first the filename, then the stat output
                   11560:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11561:     } else {
                   11562:         return -1;
1.253     stredwic 11563:     }
1.26      www      11564: }
                   11565: 
1.712     albertel 11566: sub stat_file {
                   11567:     my ($uri) = @_;
1.787     albertel 11568:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11569: 
1.955     raeburn  11570:     my ($udom,$uname,$file);
1.712     albertel 11571:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11572: 	($udom,$uname,$file) =
1.811     albertel 11573: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11574: 	$file = 'userfiles/'.$file;
                   11575:     }
                   11576:     if ($uri =~ m-^/res/-) {
                   11577: 	($udom,$uname) = 
1.807     albertel 11578: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11579: 	$file = $uri;
                   11580:     }
                   11581: 
                   11582:     if (!$udom || !$uname || !$file) {
                   11583: 	# unable to handle the uri
                   11584: 	return ();
                   11585:     }
1.956     raeburn  11586:     my $getpropath;
                   11587:     if ($file =~ /^userfiles\//) {
                   11588:         $getpropath = 1;
                   11589:     }
1.1136    raeburn  11590:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11591:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11592:         return ();
                   11593:     } else {
                   11594:         if (ref($listref) eq 'ARRAY') {
                   11595:             my @stats = split('&',$listref->[0]);
                   11596: 	    shift(@stats); #filename is first
                   11597: 	    return @stats;
                   11598:         }
1.712     albertel 11599:     }
                   11600:     return ();
                   11601: }
                   11602: 
1.1313    raeburn  11603: # --------------------------------------------------------- recursedirs
                   11604: # Recursive function to traverse either a specific user's Authoring Space
                   11605: # or corresponding Published Resource Space, and populate the hash ref:
                   11606: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11607: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11608: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11609: # files in Authoring Space.
                   11610: #
                   11611: # Inputs:
                   11612: #
                   11613: # $is_home - true if current server is home server for user's space
                   11614: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11615: # $docroot - Document root (i.e., /home/httpd/html
                   11616: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11617: # $relpath - Current path (relative to top level).
                   11618: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11619: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11620: #
                   11621: # Returns: nothing
                   11622: #
                   11623: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11624: #
                   11625: # Currently used by interface/londocs.pm to create linked select boxes for
                   11626: # directory and filename to import a Course "Author" resource into a course, and
                   11627: # also to create linked select boxes for Authoring Space and Directory to choose
                   11628: # save location for creation of a new "standard" problem from the Course Editor.
                   11629: #
                   11630: 
                   11631: sub recursedirs {
                   11632:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11633:     return unless (ref($dirhashref) eq 'HASH');
                   11634:     my $currpath = $docroot.$toppath;
                   11635:     if ($relpath) {
                   11636:         $currpath .= "/$relpath";
                   11637:     }
                   11638:     my $savefile;
                   11639:     if (ref($filehashref)) {
                   11640:         $savefile = 1;
                   11641:     }
                   11642:     if ($is_home) {
                   11643:         if (opendir(my $dirh,$currpath)) {
                   11644:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11645:                 next if ($item eq '');
                   11646:                 if (-d "$currpath/$item") {
                   11647:                     my $newpath;
                   11648:                     if ($relpath) {
                   11649:                         $newpath = "$relpath/$item";
                   11650:                     } else {
                   11651:                         $newpath = $item;
                   11652:                     }
                   11653:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11654:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11655:                 } elsif ($savefile) {
                   11656:                     if ($context eq 'priv') {
                   11657:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11658:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11659:                         }
                   11660:                     } else {
                   11661:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11662:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11663:                         }
                   11664:                     }
                   11665:                 }
                   11666:             }
                   11667:             closedir($dirh);
                   11668:         }
                   11669:     } else {
                   11670:         my ($dirlistref,$listerror) =
                   11671:             &dirlist($toppath.$relpath);
                   11672:         my @dir_lines;
                   11673:         my $dirptr=16384;
                   11674:         if (ref($dirlistref) eq 'ARRAY') {
                   11675:             foreach my $dir_line (sort
                   11676:                               {
                   11677:                                   my ($afile)=split('&',$a,2);
                   11678:                                   my ($bfile)=split('&',$b,2);
                   11679:                                   return (lc($afile) cmp lc($bfile));
                   11680:                               } (@{$dirlistref})) {
                   11681:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11682:                     split(/\&/,$dir_line,16);
                   11683:                 $item =~ s/\s+$//;
                   11684:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11685:                 if ($dirptr&$testdir) {
                   11686:                     my $newpath;
                   11687:                     if ($relpath) {
                   11688:                         $newpath = "$relpath/$item";
                   11689:                     } else {
                   11690:                         $relpath = '/';
                   11691:                         $newpath = $item;
                   11692:                     }
                   11693:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11694:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11695:                 } elsif ($savefile) {
                   11696:                     if ($context eq 'priv') {
                   11697:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11698:                             $filehashref->{$relpath}{$item} = 1;
                   11699:                         }
                   11700:                     } else {
                   11701:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11702:                             $filehashref->{$relpath}{$item} = 1;
                   11703:                         }
                   11704:                     }
                   11705:                 }
                   11706:             }
                   11707:         }
                   11708:     }
                   11709:     return;
                   11710: }
                   11711: 
1.26      www      11712: # -------------------------------------------------------- Value of a Condition
                   11713: 
1.713     albertel 11714: # gets the value of a specific preevaluated condition
                   11715: #    stored in the string  $env{user.state.<cid>}
                   11716: # or looks up a condition reference in the bighash and if if hasn't
                   11717: # already been evaluated recurses into docondval to get the value of
                   11718: # the condition, then memoizing it to 
                   11719: #   $env{user.state.<cid>.<condition>}
1.40      www      11720: sub directcondval {
                   11721:     my $number=shift;
1.620     albertel 11722:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11723: 	&Apache::lonuserstate::evalstate();
                   11724:     }
1.713     albertel 11725:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11726: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11727:     } elsif ($number =~ /^_/) {
                   11728: 	my $sub_condition;
                   11729: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11730: 		&GDBM_READER(),0640)) {
                   11731: 	    $sub_condition=$bighash{'conditions'.$number};
                   11732: 	    untie(%bighash);
                   11733: 	}
                   11734: 	my $value = &docondval($sub_condition);
1.949     raeburn  11735: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11736: 	return $value;
                   11737:     }
1.620     albertel 11738:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11739:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11740:     } else {
                   11741:        return 2;
                   11742:     }
                   11743: }
                   11744: 
1.713     albertel 11745: # get the collection of conditions for this resource
1.26      www      11746: sub condval {
                   11747:     my $condidx=shift;
1.54      www      11748:     my $allpathcond='';
1.713     albertel 11749:     foreach my $cond (split(/\|/,$condidx)) {
                   11750: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11751: 	    $allpathcond.=
                   11752: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11753: 	}
1.191     harris41 11754:     }
1.54      www      11755:     $allpathcond=~s/\|$//;
1.713     albertel 11756:     return &docondval($allpathcond);
                   11757: }
                   11758: 
                   11759: #evaluates an expression of conditions
                   11760: sub docondval {
                   11761:     my ($allpathcond) = @_;
                   11762:     my $result=0;
                   11763:     if ($env{'request.course.id'}
                   11764: 	&& defined($allpathcond)) {
                   11765: 	my $operand='|';
                   11766: 	my @stack;
                   11767: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11768: 	    if ($chunk eq '(') {
                   11769: 		push @stack,($operand,$result);
                   11770: 	    } elsif ($chunk eq ')') {
                   11771: 		my $before=pop @stack;
                   11772: 		if (pop @stack eq '&') {
                   11773: 		    $result=$result>$before?$before:$result;
                   11774: 		} else {
                   11775: 		    $result=$result>$before?$result:$before;
                   11776: 		}
                   11777: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11778: 		$operand=$chunk;
                   11779: 	    } else {
                   11780: 		my $new=directcondval($chunk);
                   11781: 		if ($operand eq '&') {
                   11782: 		    $result=$result>$new?$new:$result;
                   11783: 		} else {
                   11784: 		    $result=$result>$new?$result:$new;
                   11785: 		}
                   11786: 	    }
                   11787: 	}
1.26      www      11788:     }
                   11789:     return $result;
1.421     albertel 11790: }
                   11791: 
                   11792: # ---------------------------------------------------- Devalidate courseresdata
                   11793: 
                   11794: sub devalidatecourseresdata {
                   11795:     my ($coursenum,$coursedomain)=@_;
                   11796:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11797:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11798: }
                   11799: 
1.763     www      11800: 
1.200     www      11801: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11802: #
                   11803: #  Parameters:
                   11804: #      $coursenum    - Number of the course.
                   11805: #      $coursedomain - Domain at which the course was created.
                   11806: #  Returns:
                   11807: #     A hash of the course parameters along (I think) with timestamps
                   11808: #     and version info.
1.877     foxr     11809: 
1.624     albertel 11810: sub get_courseresdata {
                   11811:     my ($coursenum,$coursedomain)=@_;
1.200     www      11812:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11813:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11814:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11815:     my %dumpreply;
1.417     albertel 11816:     unless (defined($cached)) {
1.624     albertel 11817: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11818: 	$result=\%dumpreply;
1.251     albertel 11819: 	my ($tmp) = keys(%dumpreply);
                   11820: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11821: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11822: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11823: 	    return $tmp;
1.416     albertel 11824: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11825: 	    $result=undef;
1.599     albertel 11826: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11827: 	}
                   11828:     }
1.624     albertel 11829:     return $result;
                   11830: }
                   11831: 
1.633     albertel 11832: sub devalidateuserresdata {
                   11833:     my ($uname,$udom)=@_;
                   11834:     my $hashid="$udom:$uname";
                   11835:     &devalidate_cache_new('userres',$hashid);
                   11836: }
                   11837: 
1.624     albertel 11838: sub get_userresdata {
                   11839:     my ($uname,$udom)=@_;
                   11840:     #most student don\'t have any data set, check if there is some data
                   11841:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11842: 
                   11843:     my $hashid="$udom:$uname";
                   11844:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11845:     if (!defined($cached)) {
                   11846: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11847: 	$result=\%resourcedata;
                   11848: 	&do_cache_new('userres',$hashid,$result,600);
                   11849:     }
                   11850:     my ($tmp)=keys(%$result);
                   11851:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11852: 	return $result;
                   11853:     }
                   11854:     #error 2 occurs when the .db doesn't exist
                   11855:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11856:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11857: 	    &logthis("<font color=\"blue\">WARNING:".
                   11858: 		     " Trying to get resource data for ".
                   11859: 		     $uname." at ".$udom.": ".
                   11860: 		     $tmp."</font>");
                   11861:         }
1.624     albertel 11862:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11863: 	#&EXT_cache_set($udom,$uname);
                   11864: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11865: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11866:     }
                   11867:     return $tmp;
                   11868: }
1.879     foxr     11869: #----------------------------------------------- resdata - return resource data
                   11870: #  Purpose:
                   11871: #    Return resource data for either users or for a course.
                   11872: #  Parameters:
                   11873: #     $name      - Course/user name.
                   11874: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11875: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11876: #     $mapp      - decluttered URL of enclosing map  
                   11877: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11878: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11879: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11880: #     $courseid  - CourseID (first part of param identifier).
                   11881: #     $modifier  - Middle part of param identifier.
                   11882: #     $what      - Last part of param identifier.
1.879     foxr     11883: #     @which     - Array of names of resources desired.
                   11884: #  Returns:
                   11885: #     The value of the first reasource in @which that is found in the
                   11886: #     resource hash.
                   11887: #  Exceptional Conditions:
                   11888: #     If the $type passed in is not valid (not the string 'course' or 
                   11889: #     'user', an undefined  reference is returned.
                   11890: #     If none of the resources are found, an undef is returned
1.624     albertel 11891: sub resdata {
1.1301    raeburn  11892:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11893:         $modifier,$what,@which)=@_;
1.624     albertel 11894:     my $result;
                   11895:     if ($type eq 'course') {
                   11896: 	$result=&get_courseresdata($name,$domain);
                   11897:     } elsif ($type eq 'user') {
                   11898: 	$result=&get_userresdata($name,$domain);
                   11899:     }
                   11900:     if (!ref($result)) { return $result; }    
1.251     albertel 11901:     foreach my $item (@which) {
1.1301    raeburn  11902:         if ($item->[1] eq 'course') {
                   11903:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11904:                 unless ($$recursed) {
1.1302    raeburn  11905:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11906:                     $$recursed = 1;
                   11907:                 }
                   11908:                 foreach my $item (@${recurseup}) {
                   11909:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11910:                     last if (defined($result->{$norecursechk}));
                   11911:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11912:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11913:                 }
                   11914:             }
                   11915:         }
                   11916:         if (defined($result->{$item->[0]})) {
1.927     albertel 11917: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11918: 	}
1.250     albertel 11919:     }
1.291     albertel 11920:     return undef;
1.200     www      11921: }
                   11922: 
1.1360    raeburn  11923: sub get_domain_lti {
                   11924:     my ($cdom,$context) = @_;
                   11925:     my ($name,%lti);
                   11926:     if ($context eq 'consumer') {
                   11927:         $name = 'ltitools';
                   11928:     } elsif ($context eq 'provider') {
                   11929:         $name = 'lti';
                   11930:     } else {
                   11931:         return %lti;
                   11932:     }
                   11933:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11934:     if (defined($cached)) {
                   11935:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11936:             %lti = %{$result};
1.1298    raeburn  11937:         }
                   11938:     } else {
1.1360    raeburn  11939:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11940:         if (ref($domconfig{$name}) eq 'HASH') {
                   11941:             %lti = %{$domconfig{$name}};
                   11942:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11943:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11944:                 foreach my $id (keys(%lti)) {
                   11945:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11946:                         foreach my $item ('key','secret') {
1.1360    raeburn  11947:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11948:                         }
                   11949:                     }
                   11950:                 }
                   11951:             }
1.1298    raeburn  11952:         }
                   11953:         my $cachetime = 24*60*60;
1.1360    raeburn  11954:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11955:     }
1.1360    raeburn  11956:     return %lti;
1.1298    raeburn  11957: }
                   11958: 
1.1236    raeburn  11959: sub get_numsuppfiles {
                   11960:     my ($cnum,$cdom,$ignorecache)=@_;
                   11961:     my $hashid=$cnum.':'.$cdom;
                   11962:     my ($suppcount,$cached);
                   11963:     unless ($ignorecache) {
                   11964:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11965:     }
                   11966:     unless (defined($cached)) {
                   11967:         my $chome=&homeserver($cnum,$cdom);
                   11968:         unless ($chome eq 'no_host') {
1.1366    raeburn  11969:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11970:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11971:             ($suppcount,$supptools,$errors) =
                   11972:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11973:                                                          $supptools,$errors);
1.1236    raeburn  11974:         }
                   11975:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11976:     }
                   11977:     return $suppcount;
                   11978: }
                   11979: 
1.379     matthew  11980: #
                   11981: # EXT resource caching routines
                   11982: #
                   11983: 
1.1302    raeburn  11984: {
                   11985: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11986: #
                   11987: # The course for which we cache
                   11988: my $cachedmapkey='';
                   11989: # The cached recursive maps for this course
                   11990: my %cachedmaps=();
                   11991: # When this was last done
                   11992: my $cachedmaptime='';
                   11993: 
1.379     matthew  11994: sub clear_EXT_cache_status {
1.383     albertel 11995:     &delenv('cache.EXT.');
1.379     matthew  11996: }
                   11997: 
                   11998: sub EXT_cache_status {
                   11999:     my ($target_domain,$target_user) = @_;
1.383     albertel 12000:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12001:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12002:         # We know already the user has no data
                   12003:         return 1;
                   12004:     } else {
                   12005:         return 0;
                   12006:     }
                   12007: }
                   12008: 
                   12009: sub EXT_cache_set {
                   12010:     my ($target_domain,$target_user) = @_;
1.383     albertel 12011:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12012:     #&appenv({$cachename => time});
1.379     matthew  12013: }
                   12014: 
1.28      www      12015: # --------------------------------------------------------- Value of a Variable
1.58      www      12016: sub EXT {
1.715     albertel 12017: 
1.1228    raeburn  12018:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12019:     unless ($varname) { return ''; }
1.218     albertel 12020:     #get real user name/domain, courseid and symb
                   12021:     my $courseid;
1.359     albertel 12022:     my $publicuser;
1.427     www      12023:     if ($symbparm) {
                   12024: 	$symbparm=&get_symb_from_alias($symbparm);
                   12025:     }
1.218     albertel 12026:     if (!($uname && $udom)) {
1.790     albertel 12027:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12028:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12029:     } else {
1.620     albertel 12030: 	$courseid=$env{'request.course.id'};
1.218     albertel 12031:     }
1.48      www      12032:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12033:     my $rest;
1.320     albertel 12034:     if (defined($therest[0])) {
1.48      www      12035:        $rest=join('.',@therest);
                   12036:     } else {
                   12037:        $rest='';
                   12038:     }
1.320     albertel 12039: 
1.57      www      12040:     my $qualifierrest=$qualifier;
                   12041:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12042:     my $spacequalifierrest=$space;
                   12043:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12044:     if ($realm eq 'user') {
1.48      www      12045: # --------------------------------------------------------------- user.resource
                   12046: 	if ($space eq 'resource') {
1.651     albertel 12047: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12048: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12049: 		 &&
1.744     albertel 12050: 		 ($symbparm eq &symbread()) ) {	
                   12051: 		# if we are in the middle of processing the resource the
                   12052: 		# get the value we are planning on committing
                   12053:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12054:                     return $Apache::lonhomework::results{$qualifierrest};
                   12055:                 } else {
                   12056:                     return $Apache::lonhomework::history{$qualifierrest};
                   12057:                 }
1.335     albertel 12058: 	    } else {
1.359     albertel 12059: 		my %restored;
1.620     albertel 12060: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12061: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12062: 		} else {
                   12063: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12064: 		}
1.335     albertel 12065: 		return $restored{$qualifierrest};
                   12066: 	    }
1.48      www      12067: # ----------------------------------------------------------------- user.access
                   12068:         } elsif ($space eq 'access') {
1.218     albertel 12069: 	    # FIXME - not supporting calls for a specific user
1.48      www      12070:             return &allowed($qualifier,$rest);
                   12071: # ------------------------------------------ user.preferences, user.environment
                   12072:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12073: 	    if (($uname eq $env{'user.name'}) &&
                   12074: 		($udom eq $env{'user.domain'})) {
                   12075: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12076: 	    } else {
1.359     albertel 12077: 		my %returnhash;
                   12078: 		if (!$publicuser) {
                   12079: 		    %returnhash=&userenvironment($udom,$uname,
                   12080: 						 $qualifierrest);
                   12081: 		}
1.218     albertel 12082: 		return $returnhash{$qualifierrest};
                   12083: 	    }
1.48      www      12084: # ----------------------------------------------------------------- user.course
                   12085:         } elsif ($space eq 'course') {
1.218     albertel 12086: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12087:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12088: # ------------------------------------------------------------------- user.role
                   12089:         } elsif ($space eq 'role') {
1.218     albertel 12090: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12091:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12092:             if ($qualifier eq 'value') {
                   12093: 		return $role;
                   12094:             } elsif ($qualifier eq 'extent') {
                   12095:                 return $where;
                   12096:             }
                   12097: # ----------------------------------------------------------------- user.domain
                   12098:         } elsif ($space eq 'domain') {
1.218     albertel 12099:             return $udom;
1.48      www      12100: # ------------------------------------------------------------------- user.name
                   12101:         } elsif ($space eq 'name') {
1.218     albertel 12102:             return $uname;
1.48      www      12103: # ---------------------------------------------------- Any other user namespace
1.29      www      12104:         } else {
1.359     albertel 12105: 	    my %reply;
                   12106: 	    if (!$publicuser) {
                   12107: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12108: 	    }
                   12109: 	    return $reply{$qualifierrest};
1.48      www      12110:         }
1.236     www      12111:     } elsif ($realm eq 'query') {
                   12112: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12113:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12114: 						[$spacequalifierrest]);
1.620     albertel 12115: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12116:    } elsif ($realm eq 'request') {
1.48      www      12117: # ------------------------------------------------------------- request.browser
                   12118:         if ($space eq 'browser') {
1.1145    bisitz   12119:             return $env{'browser.'.$qualifier};
1.57      www      12120: # ------------------------------------------------------------ request.filename
                   12121:         } else {
1.620     albertel 12122:             return $env{'request.'.$spacequalifierrest};
1.29      www      12123:         }
1.28      www      12124:     } elsif ($realm eq 'course') {
1.48      www      12125: # ---------------------------------------------------------- course.description
1.620     albertel 12126:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12127:     } elsif ($realm eq 'resource') {
1.165     www      12128: 
1.620     albertel 12129: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12130: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12131: 	}
1.693     albertel 12132: 
1.1232    raeburn  12133:         if ($qualifier eq '') {
                   12134: 	    if ($space eq 'title') {
                   12135: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12136: 	        return &gettitle($symbparm);
                   12137: 	    }
1.693     albertel 12138: 	
1.1232    raeburn  12139: 	    if ($space eq 'map') {
                   12140: 	        my ($map) = &decode_symb($symbparm);
                   12141: 	        return &symbread($map);
                   12142: 	    }
                   12143:             if ($space eq 'maptitle') {
                   12144:                 my ($map) = &decode_symb($symbparm);
                   12145:                 return &gettitle($map);
                   12146:             }
                   12147: 	    if ($space eq 'filename') {
                   12148: 	        if ($symbparm) {
                   12149: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12150: 	        }
                   12151: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12152: 	    }
1.1232    raeburn  12153: 
1.1233    raeburn  12154:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12155:                 if ($space eq 'visibleparts') {
                   12156:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12157:                     my $item;
                   12158:                     if (ref($navmap)) {
                   12159:                         my $res = $navmap->getBySymb($symbparm);
                   12160:                         my $parts = $res->parts();
                   12161:                         if (ref($parts) eq 'ARRAY') {
                   12162:                             $item = join(',',@{$parts});
                   12163:                         }
                   12164:                         undef($navmap);
1.1232    raeburn  12165:                     }
1.1233    raeburn  12166:                     return $item;
1.1232    raeburn  12167:                 }
                   12168:             }
                   12169:         }
1.693     albertel 12170: 
1.1301    raeburn  12171: 	my ($section, $group, @groups, @recurseup, $recursed);
                   12172: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12173:         if (($courseid eq '') && ($cid)) {
                   12174:             $courseid = $cid;
                   12175:         }
                   12176: 	if (($symbparm && $courseid) && 
                   12177: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12178: 
1.218     albertel 12179: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12180: 
1.60      www      12181: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12182: 	    my $symbp=$symbparm;
1.1301    raeburn  12183: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12184: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12185:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12186: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12187: 	    if (($env{'user.name'} eq $uname) &&
                   12188: 		($env{'user.domain'} eq $udom)) {
                   12189: 		$section=$env{'request.course.sec'};
1.733     raeburn  12190:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12191:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12192: 	    } else {
1.539     albertel 12193: 		if (! defined($usection)) {
1.551     albertel 12194: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12195: 		} else {
                   12196: 		    $section = $usection;
                   12197: 		}
1.733     raeburn  12198:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12199: 	    }
                   12200: 
                   12201: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12202: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12203:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12204: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12205: 
1.593     albertel 12206: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12207: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12208:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12209: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12210: 
1.60      www      12211: # ----------------------------------------------------------- first, check user
1.624     albertel 12212: 
1.1301    raeburn  12213: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12214:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12215: 				       ([$courselevelr,'resource'],
                   12216: 					[$courselevelm,'map'     ],
1.1301    raeburn  12217:                                         [$courseleveli,'map'     ],
1.927     albertel 12218: 					[$courselevel, 'course'  ]));
1.931     albertel 12219: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12220: 
1.594     albertel 12221: # ------------------------------------------------ second, check some of course
1.684     raeburn  12222:             my $coursereply;
1.691     raeburn  12223:             if (@groups > 0) {
                   12224:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12225:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12226:                                        $mapp,\$recursed,\@recurseup);
                   12227:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12228:             }
1.96      www      12229: 
1.684     raeburn  12230: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12231: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12232: 				  'course',$mapp,\$recursed,\@recurseup,
                   12233:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12234: 				  ([$seclevelr,   'resource'],
                   12235: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12236:                                    [$secleveli,   'map'     ],
1.927     albertel 12237: 				   [$seclevel,    'course'  ],
                   12238: 				   [$courselevelr,'resource']));
                   12239: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12240: 
1.60      www      12241: # ------------------------------------------------------ third, check map parms
1.218     albertel 12242: 	    my %parmhash=();
                   12243: 	    my $thisparm='';
                   12244: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12245: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12246: 		    &GDBM_READER(),0640)) {
1.218     albertel 12247: 		$thisparm=$parmhash{$symbparm};
                   12248: 		untie(%parmhash);
                   12249: 	    }
1.927     albertel 12250: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12251: 	}
1.594     albertel 12252: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12253:  
                   12254:         my $what = $spacequalifierrest;
                   12255: 	$what=~s/\./\_/;
1.282     albertel 12256: 	my $filename;
                   12257: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12258: 	if ($symbparm) {
1.409     www      12259: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12260: 	} else {
1.620     albertel 12261: 	    $filename=$env{'request.filename'};
1.282     albertel 12262: 	}
1.1362    raeburn  12263:         my $toolsymb;
                   12264:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12265:             $toolsymb = $symbparm;
                   12266:         }
                   12267: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12268: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12269: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12270: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12271: 
1.1301    raeburn  12272: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12273: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12274: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12275: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12276: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12277: 				     'course',$mapp,\$recursed,\@recurseup,
                   12278:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12279: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12280:                                       [$courseleveli,'map'   ],
1.927     albertel 12281: 				      [$courselevel, 'course']));
                   12282: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12283: 	}
1.145     www      12284: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12285: 	unless ($space eq '0') {
1.336     albertel 12286: 	    my @parts=split(/_/,$space);
                   12287: 	    my $id=pop(@parts);
                   12288: 	    my $part=join('_',@parts);
                   12289: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12290: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12291: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12292: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12293: 	}
1.395     albertel 12294: 	if ($recurse) { return undef; }
1.1362    raeburn  12295: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12296: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12297: # ---------------------------------------------------- Any other user namespace
                   12298:     } elsif ($realm eq 'environment') {
                   12299: # ----------------------------------------------------------------- environment
1.620     albertel 12300: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12301: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12302: 	} else {
1.770     albertel 12303: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12304: 		return '';
                   12305: 	    }
1.219     albertel 12306: 	    my %returnhash=&userenvironment($udom,$uname,
                   12307: 					    $spacequalifierrest);
                   12308: 	    return $returnhash{$spacequalifierrest};
                   12309: 	}
1.28      www      12310:     } elsif ($realm eq 'system') {
1.48      www      12311: # ----------------------------------------------------------------- system.time
                   12312: 	if ($space eq 'time') {
                   12313: 	    return time;
                   12314:         }
1.696     albertel 12315:     } elsif ($realm eq 'server') {
                   12316: # ----------------------------------------------------------------- system.time
                   12317: 	if ($space eq 'name') {
                   12318: 	    return $ENV{'SERVER_NAME'};
                   12319:         }
1.1415    raeburn  12320:     } elsif ($realm eq 'client') {
                   12321:         if ($space eq 'remote_addr') {
                   12322:             return $ENV{'REMOTE_ADDR'};
                   12323:         }
1.28      www      12324:     }
1.48      www      12325:     return '';
1.61      www      12326: }
                   12327: 
1.927     albertel 12328: sub get_reply {
                   12329:     my ($reply_value) = @_;
1.940     raeburn  12330:     if (ref($reply_value) eq 'ARRAY') {
                   12331:         if (wantarray) {
                   12332: 	    return @$reply_value;
                   12333:         }
                   12334:         return $reply_value->[0];
                   12335:     } else {
                   12336:         return $reply_value;
1.927     albertel 12337:     }
                   12338: }
                   12339: 
1.691     raeburn  12340: sub check_group_parms {
1.1301    raeburn  12341:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12342:         $recursed,$recurseupref) = @_;
                   12343:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12344:                   [$what,'course']);
                   12345:     my $coursereply;
1.691     raeburn  12346:     foreach my $group (@{$groups}) {
1.1301    raeburn  12347:         my @groupitems = ();
1.691     raeburn  12348:         foreach my $level (@levels) {
1.927     albertel 12349:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12350:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12351:         }
1.1301    raeburn  12352:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12353:                                    $env{'course.'.$courseid.'.domain'},
                   12354:                                    'course',$mapp,$recursed,$recurseupref,
                   12355:                                    $courseid,'.['.$group.'].',$what,
                   12356:                                    @groupitems);
                   12357:         last if (defined($coursereply));
1.691     raeburn  12358:     }
                   12359:     return $coursereply;
                   12360: }
                   12361: 
1.1301    raeburn  12362: sub get_map_hierarchy {
1.1302    raeburn  12363:     my ($mapname,$courseid) = @_;
                   12364:     my @recurseup = ();
1.1301    raeburn  12365:     if ($mapname) {
1.1302    raeburn  12366:         if (($cachedmapkey eq $courseid) &&
                   12367:             (abs($cachedmaptime-time)<5)) {
                   12368:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12369:                 return @{$cachedmaps{$mapname}};
                   12370:             }
                   12371:         }
1.1301    raeburn  12372:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12373:         if (ref($navmap)) {
                   12374:             @recurseup = $navmap->recurseup_maps($mapname);
                   12375:             undef($navmap);
1.1302    raeburn  12376:             $cachedmaps{$mapname} = \@recurseup;
                   12377:             $cachedmaptime=time;
                   12378:             $cachedmapkey=$courseid;
1.1301    raeburn  12379:         }
                   12380:     }
                   12381:     return @recurseup;
                   12382: }
                   12383: 
1.1302    raeburn  12384: }
                   12385: 
1.691     raeburn  12386: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12387:     my ($courseid,@groups) = @_;
                   12388:     @groups = sort(@groups);
1.691     raeburn  12389:     return @groups;
                   12390: }
                   12391: 
1.395     albertel 12392: sub packages_tab_default {
1.1362    raeburn  12393:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12394:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12395: 
                   12396:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12397:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12398: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12399: 	if ($pack_type eq 'default') {
                   12400: 	    $do_default=1;
                   12401: 	} elsif ($pack_type eq 'extension') {
                   12402: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12403: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12404: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12405: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12406: 	}
                   12407:     }
                   12408:     # first look for a package that matches the requested part id
                   12409:     foreach my $package (@specifics) {
                   12410: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12411: 	next if ($pack_part ne $part);
                   12412: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12413: 	    return $packagetab{"$pack_type&$name&default"};
                   12414: 	}
                   12415:     }
                   12416:     # look for any possible matching non extension_ package
                   12417:     foreach my $package (@specifics) {
                   12418: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12419: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12420: 	    return $packagetab{"$pack_type&$name&default"};
                   12421: 	}
1.585     albertel 12422: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12423: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12424: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12425: 	}
                   12426:     }
1.738     albertel 12427:     # look for any posible extension_ match
                   12428:     foreach my $package (@extension) {
                   12429: 	my ($package,$pack_type)=@{$package};
                   12430: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12431: 	    return $packagetab{"$pack_type&$name&default"};
                   12432: 	}
                   12433: 	if (defined($packagetab{$package."&$name&default"})) {
                   12434: 	    return $packagetab{$package."&$name&default"};
                   12435: 	}
                   12436:     }
                   12437:     # look for a global default setting
                   12438:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12439: 	return $packagetab{"default&$name&default"};
                   12440:     }
1.395     albertel 12441:     return undef;
                   12442: }
                   12443: 
1.334     albertel 12444: sub add_prefix_and_part {
                   12445:     my ($prefix,$part)=@_;
                   12446:     my $keyroot;
                   12447:     if (defined($prefix) && $prefix !~ /^__/) {
                   12448: 	# prefix that has a part already
                   12449: 	$keyroot=$prefix;
                   12450:     } elsif (defined($prefix)) {
                   12451: 	# prefix that is missing a part
                   12452: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12453:     } else {
                   12454: 	# no prefix at all
                   12455: 	if (defined($part)) { $keyroot='_'.$part; }
                   12456:     }
                   12457:     return $keyroot;
                   12458: }
                   12459: 
1.71      www      12460: # ---------------------------------------------------------------- Get metadata
                   12461: 
1.599     albertel 12462: my %metaentry;
1.1070    www      12463: my %importedpartids;
1.1369    raeburn  12464: my %importedrespids;
1.71      www      12465: sub metadata {
1.1362    raeburn  12466:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12467:     $uri=&declutter($uri);
1.288     albertel 12468:     # if it is a non metadata possible uri return quickly
1.529     albertel 12469:     if (($uri eq '') || 
                   12470: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12471: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12472:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12473: 	return undef;
                   12474:     }
1.1261    raeburn  12475:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12476: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12477: 	return undef;
1.288     albertel 12478:     }
1.73      www      12479:     my $filename=$uri;
                   12480:     $uri=~s/\.meta$//;
1.172     www      12481: #
                   12482: # Is the metadata already cached?
1.177     www      12483: # Look at timestamp of caching
1.172     www      12484: # Everything is cached by the main uri, libraries are never directly cached
                   12485: #
1.428     albertel 12486:     if (!defined($liburi)) {
1.599     albertel 12487: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12488: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12489:     }
1.1362    raeburn  12490: 
                   12491: #
                   12492: # If the uri is for an external tool the file from
                   12493: # which metadata should be retrieved depends on whether
                   12494: # the tool had been configured to be gradable (set in the Course
                   12495: # Editor or Resource Editor).
                   12496: #
                   12497: # If a valid symb has been included as the third arg in the call
                   12498: # to &metadata() that can be used to retrieve the value of
                   12499: # parameter_0_gradable set for the resource, and included in the
                   12500: # uploaded map containing the tool. The value is retrieved via
                   12501: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12502: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12503: # is retrieved via &get().
                   12504: #
                   12505: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12506: # hiddenresource and encrypturl (during course initialization)
                   12507: # the map-level parameter for resource.0.gradable included in the 
                   12508: # uploaded map containing the tool will not yet have been stored
                   12509: # in the user_course_parms.db file for the user's session, so in 
                   12510: # this case fall back to retrieving gradable status from the
                   12511: # exttool_$marker.db file.
1.1362    raeburn  12512: #
                   12513: # In order to avoid an infinite loop, &metadata() will return
                   12514: # before a call to &EXT(), if the uri is for an external tool
                   12515: # and the $what for which metadata is being requested is
                   12516: # parameter_0_gradable or 0_gradable.
                   12517: #
                   12518: 
                   12519:     if ($uri =~ /ext\.tool$/) {
                   12520:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12521:             return;
                   12522:         } else {
                   12523:             my ($checked,$use_passback);
                   12524:             if ($toolsymb ne '') {
                   12525:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12526:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12527:                     $checked = 1;
                   12528:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12529:                         $use_passback = 1;
                   12530:                     }
                   12531:                 }
                   12532:             }
                   12533:             unless ($checked) {
                   12534:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12535:                 $marker=~s/\D//g;
1.1363    raeburn  12536:                 if ($marker) {
1.1362    raeburn  12537:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12538:                     $use_passback = $toolsettings{'gradable'};
                   12539:                 }
                   12540:             }
                   12541:             if ($use_passback) {
                   12542:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12543:             } else {
                   12544:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12545:             }
                   12546:         }
                   12547:     }
                   12548: 
1.428     albertel 12549:     {
1.1069    www      12550: # Imported parts would go here
1.1369    raeburn  12551:         my @origfiletagids=();
1.1069    www      12552:         my $importedparts=0;
1.1369    raeburn  12553: 
                   12554: # Imported responseids would go here
                   12555:         my $importedresponses=0;
1.172     www      12556: #
                   12557: # Is this a recursive call for a library?
                   12558: #
1.599     albertel 12559: #	if (! exists($metacache{$uri})) {
                   12560: #	    $metacache{$uri}={};
                   12561: #	}
1.924     albertel 12562: 	my $cachetime = 60*60;
1.171     www      12563:         if ($liburi) {
                   12564: 	    $liburi=&declutter($liburi);
                   12565:             $filename=$liburi;
1.401     bowersj2 12566:         } else {
1.599     albertel 12567: 	    &devalidate_cache_new('meta',$uri);
                   12568: 	    undef(%metaentry);
1.401     bowersj2 12569: 	}
1.140     www      12570:         my %metathesekeys=();
1.73      www      12571:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12572: 	my $metastring;
1.1140    www      12573: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12574: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12575: 	    $metastring = 
1.929     albertel 12576: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12577: 					  ('grade_target' => 'meta'));
                   12578: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12579: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12580:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12581: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12582: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12583: 	    $metastring=&getfile($file);
1.489     albertel 12584: 	}
1.208     albertel 12585:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12586:         my $token;
1.140     www      12587:         undef %metathesekeys;
1.71      www      12588:         while ($token=$parser->get_token) {
1.339     albertel 12589: 	    if ($token->[0] eq 'S') {
                   12590: 		if (defined($token->[2]->{'package'})) {
1.172     www      12591: #
                   12592: # This is a package - get package info
                   12593: #
1.339     albertel 12594: 		    my $package=$token->[2]->{'package'};
                   12595: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12596: 		    if (defined($token->[2]->{'id'})) { 
                   12597: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12598: 		    }
1.599     albertel 12599: 		    if ($metaentry{':packages'}) {
                   12600: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12601: 		    } else {
1.599     albertel 12602: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12603: 		    }
1.736     albertel 12604: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12605: 			my $part=$keyroot;
                   12606: 			$part=~s/^\_//;
1.736     albertel 12607: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12608: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12609: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12610: 			    # ignore package.tab specified default values
                   12611:                             # here &package_tab_default() will fetch those
                   12612: 			    if ($subp eq 'default') { next; }
1.736     albertel 12613: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12614: 			    my $unikey;
                   12615: 			    if ($pack =~ /_0$/) {
                   12616: 				$unikey='parameter_0_'.$name;
                   12617: 				$part=0;
                   12618: 			    } else {
                   12619: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12620: 			    }
1.339     albertel 12621: 			    if ($subp eq 'display') {
                   12622: 				$value.=' [Part: '.$part.']';
                   12623: 			    }
1.599     albertel 12624: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12625: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12626: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12627: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12628: 			    }
1.599     albertel 12629: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12630: 				$metaentry{':'.$unikey}=
                   12631: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12632: 			    }
1.339     albertel 12633: 			}
                   12634: 		    }
                   12635: 		} else {
1.172     www      12636: #
                   12637: # This is not a package - some other kind of start tag
1.339     albertel 12638: #
                   12639: 		    my $entry=$token->[1];
1.1068    www      12640: 		    my $unikey='';
1.175     www      12641: 
1.339     albertel 12642: 		    if ($entry eq 'import') {
1.175     www      12643: #
                   12644: # Importing a library here
1.339     albertel 12645: #
1.1067    www      12646:                         my $location=$parser->get_text('/import');
                   12647:                         my $dir=$filename;
                   12648:                         $dir=~s|[^/]*$||;
                   12649:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12650: 
                   12651:                         my $importid=$token->[2]->{'id'};
1.1068    www      12652:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12653: #
                   12654: # Check metadata for imported file to
                   12655: # see if it contained response items
                   12656: #
1.1372    raeburn  12657:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12658:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12659:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12660:                                                            $depthcount+1));
                   12661:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12662:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12663:                                                              undef,$depthcount+1);
                   12664:                             if ($libresponseorder ne '') {
                   12665:                                 if ($#origfiletagids<0) {
                   12666:                                     undef(%importedrespids);
                   12667:                                     undef(%importedpartids);
                   12668:                                 }
1.1373    raeburn  12669:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12670:                                 if (@respids) {
                   12671:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12672:                                 }
                   12673:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12674:                                     $importedresponses = 1;
1.1369    raeburn  12675: # We need to get the original file and the imported file to get the response order correct
                   12676: # Load and inspect original file
1.1372    raeburn  12677:                                     if ($#origfiletagids<0) {
                   12678:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12679:                                         $origfile=&getfile($origfilelocation);
                   12680:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12681:                                     }
1.1369    raeburn  12682:                                 }
                   12683:                             }
                   12684:                         }
1.1370    raeburn  12685: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12686: # hash populated for imported library file
                   12687:                         %metaentry = %currmetaentry;
                   12688:                         undef(%currmetaentry);
1.1374    raeburn  12689:                         if ($importmode eq 'part') {
1.1068    www      12690: # Import as part(s)
1.1069    www      12691:                            $importedparts=1;
                   12692: # We need to get the original file and the imported file to get the part order correct
                   12693: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12694: # Load and inspect original file if we didn't do that already
                   12695:                            if ($#origfiletagids<0) {
                   12696:                                undef(%importedrespids);
                   12697:                                undef(%importedpartids);
                   12698:                                if ($origfile eq '') {
                   12699:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12700:                                    $origfile=&getfile($origfilelocation);
                   12701:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12702:                                }
1.1070    www      12703:                            }
1.1372    raeburn  12704:                            my @impfilepartids;
                   12705: # If <partorder> tag is included in metadata for the imported file
                   12706: # get the parts in the imported file from that.
                   12707:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12708:                                %currmetaentry = %metaentry;
                   12709:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12710:                                                             $depthcount+1);
                   12711:                                %metaentry = %currmetaentry;
                   12712:                                undef(%currmetaentry);
                   12713:                                if ($libpartorder ne '') {
                   12714:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12715:                                }
                   12716:                            } else {
                   12717: # If no <partorder> tag available, load and inspect imported file
                   12718:                                my $impfile=&getfile($location);
                   12719:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12720:                            }
1.1069    www      12721:                            if ($#impfilepartids>=0) {
                   12722: # This problem had parts
1.1070    www      12723:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12724:                            } else {
                   12725: # Importing by turning a single problem into a problem part
                   12726: # It gets the import-tags ID as part-ID
                   12727:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12728:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12729:                            }
1.1068    www      12730:                         } else {
1.1374    raeburn  12731: # Import as problem or as normal import
                   12732:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12733:                             unless ($importmode eq 'problem') {
1.1068    www      12734: # Normal import
1.1374    raeburn  12735:                                 if (defined($token->[2]->{'id'})) {
                   12736:                                     $unikey.='_'.$token->[2]->{'id'};
                   12737:                                 }
                   12738:                             }
                   12739: # Check metadata for imported file to
                   12740: # see if it contained parts
                   12741:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12742:                                 %currmetaentry = %metaentry;
                   12743:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12744:                                                              $depthcount+1);
                   12745:                                 %metaentry = %currmetaentry;
                   12746:                                 undef(%currmetaentry);
                   12747:                                 if ($libpartorder ne '') {
                   12748:                                     $importedparts = 1;
                   12749:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12750:                                 }
                   12751:                             }
1.1067    www      12752:                         }
1.339     albertel 12753: 			if ($depthcount<20) {
1.736     albertel 12754: 			    my $metadata = 
1.1362    raeburn  12755: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12756: 					  $depthcount+1);
                   12757: 			    foreach my $meta (split(',',$metadata)) {
                   12758: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12759: 				$metathesekeys{$meta}=1;
1.339     albertel 12760: 			    }
1.1068    www      12761:                         }
1.1067    www      12762: 		    } else {
                   12763: #
                   12764: # Not importing, some other kind of non-package, non-library start tag
                   12765: # 
                   12766:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12767:                         if (defined($token->[2]->{'id'})) {
                   12768:                             $unikey.='_'.$token->[2]->{'id'};
                   12769:                         }
1.339     albertel 12770: 			if (defined($token->[2]->{'name'})) { 
                   12771: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12772: 			}
                   12773: 			$metathesekeys{$unikey}=1;
1.736     albertel 12774: 			foreach my $param (@{$token->[3]}) {
                   12775: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12776: 				$token->[2]->{$param};
1.339     albertel 12777: 			}
                   12778: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12779: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12780: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12781: 		 # only ws inside the tag, and not in default, so use default
                   12782: 		 # as value
1.599     albertel 12783: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12784: 			} elsif ( $internaltext =~ /\S/ ) {
                   12785: 		  # something interesting inside the tag
                   12786: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12787: 			} else {
1.908     albertel 12788: 		  # no interesting values, don't set a default
1.339     albertel 12789: 			}
1.172     www      12790: # end of not-a-package not-a-library import
1.339     albertel 12791: 		    }
1.172     www      12792: # end of not-a-package start tag
1.339     albertel 12793: 		}
1.172     www      12794: # the next is the end of "start tag"
1.339     albertel 12795: 	    }
                   12796: 	}
1.483     albertel 12797: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12798: 	$extension = lc($extension);
                   12799: 	if ($extension eq 'htm') { $extension='html'; }
                   12800: 
1.737     albertel 12801: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12802: 	    #no specific packages #how's our extension
                   12803: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12804: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12805: 					 \%metathesekeys);
                   12806: 	}
1.883     albertel 12807: 
                   12808: 	if (!exists($metaentry{':packages'})
                   12809: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12810: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12811: 		#no specific packages well let's get default then
                   12812: 		if ($key!~/^default&/) { next; }
1.488     albertel 12813: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12814: 					     \%metathesekeys);
                   12815: 	    }
                   12816: 	}
1.338     www      12817: # are there custom rights to evaluate
1.599     albertel 12818: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12819: 
1.338     www      12820:     #
                   12821:     # Importing a rights file here
1.339     albertel 12822:     #
                   12823: 	    unless ($depthcount) {
1.599     albertel 12824: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12825: 		my $dir=$filename;
                   12826: 		$dir=~s|[^/]*$||;
                   12827: 		$location=&filelocation($dir,$location);
1.736     albertel 12828: 		my $rights_metadata =
1.1362    raeburn  12829: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12830: 			      $depthcount+1);
                   12831: 		foreach my $rights (split(',',$rights_metadata)) {
                   12832: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12833: 		    $metathesekeys{$rights}=1;
1.339     albertel 12834: 		}
                   12835: 	    }
                   12836: 	}
1.737     albertel 12837: 	# uniqifiy package listing
                   12838: 	my %seen;
                   12839: 	my @uniq_packages =
                   12840: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12841: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12842: 
1.1369    raeburn  12843:         if (($importedresponses) || ($importedparts)) {
                   12844:             if ($importedparts) {
1.1070    www      12845: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12846:                 $metaentry{':partorder'}='';
                   12847:                 $metathesekeys{'partorder'}=1;
                   12848:             }
                   12849:             if ($importedresponses) {
                   12850: # We had imported responses and need to rebuil responseorder
                   12851:                 $metaentry{':responseorder'}='';
                   12852:                 $metathesekeys{'responseorder'}=1;
                   12853:             }
                   12854:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12855:                 my $origid = $origfiletagids[$index+1];
                   12856:                 if ($origfiletagids[$index] eq 'part') {
                   12857: # Original part, part of the problem
                   12858:                     if ($importedparts) {
                   12859:                         $metaentry{':partorder'}.=','.$origid;
                   12860:                     }
                   12861:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12862:                     if ($importedparts) {
                   12863: # We have imported parts at this position
1.1373    raeburn  12864:                         if ($importedpartids{$origid} ne '') {
                   12865:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12866:                         }
1.1369    raeburn  12867:                     }
                   12868:                     if ($importedresponses) {
                   12869: # We have imported responses at this position
1.1373    raeburn  12870:                         if ($importedrespids{$origid} ne '') {
                   12871:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12872:                         }
                   12873:                     }
                   12874:                 } else {
                   12875: # Original response item, part of the problem
                   12876:                     if ($importedresponses) {
                   12877:                         $metaentry{':responseorder'}.=','.$origid;
                   12878:                     }
                   12879:                 }
                   12880:             }
                   12881:             if ($importedparts) {
                   12882:                 $metaentry{':partorder'}=~s/^\,//;
                   12883:             }
                   12884:             if ($importedresponses) {
                   12885:                 $metaentry{':responseorder'}=~s/^\,//;
                   12886:             }
1.1070    www      12887:         }
1.737     albertel 12888: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12889: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12890: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12891:         unless ($liburi) {
                   12892: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12893:         }
1.177     www      12894: # this is the end of "was not already recently cached
1.71      www      12895:     }
1.599     albertel 12896:     return $metaentry{':'.$what};
1.261     albertel 12897: }
                   12898: 
1.488     albertel 12899: sub metadata_create_package_def {
1.483     albertel 12900:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12901:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12902:     if ($subp eq 'default') { next; }
                   12903:     
1.599     albertel 12904:     if (defined($metaentry{':packages'})) {
                   12905: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12906:     } else {
1.599     albertel 12907: 	$metaentry{':packages'}=$package;
1.483     albertel 12908:     }
                   12909:     my $value=$packagetab{$key};
                   12910:     my $unikey;
                   12911:     $unikey='parameter_0_'.$name;
1.599     albertel 12912:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12913:     $$metathesekeys{$unikey}=1;
1.599     albertel 12914:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12915: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12916:     }
1.599     albertel 12917:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12918: 	$metaentry{':'.$unikey}=
                   12919: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12920:     }
                   12921: }
                   12922: 
1.261     albertel 12923: sub metadata_generate_part0 {
                   12924:     my ($metadata,$metacache,$uri) = @_;
                   12925:     my %allnames;
1.737     albertel 12926:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12927: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12928: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12929: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12930: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12931: 	    $allnames{$name}=$part;
                   12932: 	  }
                   12933: 	}
                   12934:     }
                   12935:     foreach my $name (keys(%allnames)) {
                   12936:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12937:       my $key=":parameter_0_$name";
1.261     albertel 12938:       $$metacache{"$key.part"}='0';
                   12939:       $$metacache{"$key.name"}=$name;
1.428     albertel 12940:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12941: 					   $allnames{$name}.'_'.$name.
                   12942: 					   '.type'};
1.428     albertel 12943:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12944: 			     '.display'};
1.644     www      12945:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12946:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12947:       $$metacache{"$key.display"}=$olddis;
                   12948:     }
1.71      www      12949: }
                   12950: 
1.764     albertel 12951: # ------------------------------------------------------ Devalidate title cache
                   12952: 
                   12953: sub devalidate_title_cache {
                   12954:     my ($url)=@_;
                   12955:     if (!$env{'request.course.id'}) { return; }
                   12956:     my $symb=&symbread($url);
                   12957:     if (!$symb) { return; }
                   12958:     my $key=$env{'request.course.id'}."\0".$symb;
                   12959:     &devalidate_cache_new('title',$key);
                   12960: }
                   12961: 
1.1014    droeschl 12962: # ------------------------------------------------- Get the title of a course
                   12963: 
                   12964: sub current_course_title {
                   12965:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12966: }
1.301     www      12967: # ------------------------------------------------- Get the title of a resource
                   12968: 
                   12969: sub gettitle {
                   12970:     my $urlsymb=shift;
                   12971:     my $symb=&symbread($urlsymb);
1.534     albertel 12972:     if ($symb) {
1.620     albertel 12973: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12974: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12975: 	if (defined($cached)) { 
                   12976: 	    return $result;
                   12977: 	}
1.534     albertel 12978: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12979: 	my $title='';
1.907     albertel 12980: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12981: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12982: 	} else {
                   12983: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12984: 		    &GDBM_READER(),0640)) {
                   12985: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12986: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12987: 		untie(%bighash);
                   12988: 	    }
1.534     albertel 12989: 	}
                   12990: 	$title=~s/\&colon\;/\:/gs;
                   12991: 	if ($title) {
1.1159    www      12992: # Remember both $symb and $title for dynamic metadata
                   12993:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12994:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12995: # Cache this title and then return it
1.599     albertel 12996: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12997: 	}
                   12998: 	$urlsymb=$url;
                   12999:     }
                   13000:     my $title=&metadata($urlsymb,'title');
                   13001:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13002:     return $title;
1.301     www      13003: }
1.613     albertel 13004: 
1.614     albertel 13005: sub get_slot {
                   13006:     my ($which,$cnum,$cdom)=@_;
                   13007:     if (!$cnum || !$cdom) {
1.790     albertel 13008: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13009: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13010: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13011:     }
1.703     albertel 13012:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13013:     my %slotinfo;
                   13014:     if (exists($remembered{$key})) {
                   13015: 	$slotinfo{$which} = $remembered{$key};
                   13016:     } else {
                   13017: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13018: 	&Apache::lonhomework::showhash(%slotinfo);
                   13019: 	my ($tmp)=keys(%slotinfo);
                   13020: 	if ($tmp=~/^error:/) { return (); }
                   13021: 	$remembered{$key} = $slotinfo{$which};
                   13022:     }
1.616     albertel 13023:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13024: 	return %{$slotinfo{$which}};
                   13025:     }
                   13026:     return $slotinfo{$which};
1.614     albertel 13027: }
1.1150    raeburn  13028: 
                   13029: sub get_reservable_slots {
                   13030:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13031:     my $now = time;
                   13032:     my $reservable_info;
                   13033:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13034:     if (exists($remembered{$key})) {
                   13035:         $reservable_info = $remembered{$key};
                   13036:     } else {
                   13037:         my %resv;
                   13038:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13039:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13040:         $reservable_info = \%resv;
                   13041:         $remembered{$key} = $reservable_info;
                   13042:     }
                   13043:     return $reservable_info;
                   13044: }
                   13045: 
                   13046: sub get_course_slots {
                   13047:     my ($cnum,$cdom) = @_;
                   13048:     my $hashid=$cnum.':'.$cdom;
                   13049:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13050:     if (defined($cached)) {
                   13051:         if (ref($result) eq 'HASH') {
                   13052:             return %{$result};
                   13053:         }
                   13054:     } else {
                   13055:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13056:         my ($tmp) = keys(%slots);
                   13057:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13058:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13059:             return %slots;
                   13060:         }
                   13061:     }
                   13062:     return;
                   13063: }
                   13064: 
                   13065: sub devalidate_slots_cache {
                   13066:     my ($cnum,$cdom)=@_;
                   13067:     my $hashid=$cnum.':'.$cdom;
                   13068:     &devalidate_cache_new('allslots',$hashid);
                   13069: }
                   13070: 
1.1181    raeburn  13071: sub get_coursechange {
                   13072:     my ($cdom,$cnum) = @_;
                   13073:     if ($cdom eq '' || $cnum eq '') {
                   13074:         return unless ($env{'request.course.id'});
                   13075:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13076:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13077:     }
                   13078:     my $hashid=$cdom.'_'.$cnum;
                   13079:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13080:     if ((defined($cached)) && ($change ne '')) {
                   13081:         return $change;
                   13082:     } else {
                   13083:         my %crshash;
                   13084:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13085:         if ($crshash{'internal.contentchange'} eq '') {
                   13086:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13087:             if ($change eq '') {
                   13088:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13089:                 $change = $crshash{'internal.created'};
                   13090:             }
                   13091:         } else {
                   13092:             $change = $crshash{'internal.contentchange'};
                   13093:         }
                   13094:         my $cachetime = 600;
                   13095:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13096:     }
                   13097:     return $change;
                   13098: }
                   13099: 
                   13100: sub devalidate_coursechange_cache {
                   13101:     my ($cnum,$cdom)=@_;
                   13102:     my $hashid=$cnum.':'.$cdom;
                   13103:     &devalidate_cache_new('crschange',$hashid);
                   13104: }
                   13105: 
1.31      www      13106: # ------------------------------------------------- Update symbolic store links
                   13107: 
                   13108: sub symblist {
                   13109:     my ($mapname,%newhash)=@_;
1.438     www      13110:     $mapname=&deversion(&declutter($mapname));
1.31      www      13111:     my %hash;
1.620     albertel 13112:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13113:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13114:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13115: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13116: 		next if ($url eq 'last_known'
                   13117: 			 && $env{'form.no_update_last_known'});
                   13118: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13119: 						    $newhash{$url}->[1],
                   13120: 						    $newhash{$url}->[0]);
1.191     harris41 13121:             }
1.31      www      13122:             if (untie(%hash)) {
                   13123: 		return 'ok';
                   13124:             }
                   13125:         }
                   13126:     }
                   13127:     return 'error';
1.212     www      13128: }
                   13129: 
                   13130: # --------------------------------------------------------------- Verify a symb
                   13131: 
                   13132: sub symbverify {
1.1190    raeburn  13133:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13134:     my $thisfn=$thisurl;
1.439     www      13135:     $thisfn=&declutter($thisfn);
1.215     www      13136: # direct jump to resource in page or to a sequence - will construct own symbs
                   13137:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13138: # check URL part
1.409     www      13139:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13140: 
1.431     www      13141:     unless ($url eq $thisfn) { return 0; }
1.213     www      13142: 
1.216     www      13143:     $symb=&symbclean($symb);
1.510     www      13144:     $thisurl=&deversion($thisurl);
1.439     www      13145:     $thisfn=&deversion($thisfn);
1.213     www      13146: 
                   13147:     my %bighash;
                   13148:     my $okay=0;
1.431     www      13149: 
1.620     albertel 13150:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13151:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13152:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13153:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13154:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13155:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13156:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13157:             }
                   13158:         }
                   13159:         my $ids;
1.1419    raeburn  13160:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13161:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  13162:         } else {
                   13163:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13164:         }
1.1102    raeburn  13165:         unless ($ids) {
                   13166:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13167:             $ids=$bighash{$idkey};
1.216     www      13168:         }
                   13169:         if ($ids) {
                   13170: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13171:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13172:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13173:             }
1.800     albertel 13174: 	    foreach my $id (split(/\,/,$ids)) {
                   13175: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13176:                if (
                   13177:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13178:    eq $symb) {
                   13179:                    if (ref($encstate)) {
                   13180:                        $$encstate = $bighash{'encrypted_'.$id};
                   13181:                    }
1.620     albertel 13182: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13183: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13184:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13185: 		       $okay=1;
1.1202    raeburn  13186:                        last;
1.582     albertel 13187: 		   }
                   13188: 	       }
1.216     www      13189: 	   }
                   13190:         }
1.213     www      13191: 	untie(%bighash);
                   13192:     }
                   13193:     return $okay;
1.31      www      13194: }
                   13195: 
1.210     www      13196: # --------------------------------------------------------------- Clean-up symb
                   13197: 
                   13198: sub symbclean {
                   13199:     my $symb=shift;
1.568     albertel 13200:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13201: # remove version from map
                   13202:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13203: 
1.210     www      13204: # remove version from URL
                   13205:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13206: 
1.507     www      13207: # remove wrapper
                   13208: 
1.510     www      13209:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13210:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13211:     return $symb;
1.409     www      13212: }
                   13213: 
                   13214: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13215: 
                   13216: sub encode_symb {
                   13217:     my ($map,$resid,$url)=@_;
                   13218:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13219: }
1.409     www      13220: 
                   13221: sub decode_symb {
1.568     albertel 13222:     my $symb=shift;
                   13223:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13224:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13225:     return (&fixversion($map),$resid,&fixversion($url));
                   13226: }
                   13227: 
                   13228: sub fixversion {
                   13229:     my $fn=shift;
1.609     banghart 13230:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13231:     my %bighash;
                   13232:     my $uri=&clutter($fn);
1.620     albertel 13233:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13234: # is this cached?
1.599     albertel 13235:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13236:     if (defined($cached)) { return $result; }
                   13237: # unfortunately not cached, or expired
1.620     albertel 13238:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13239: 	    &GDBM_READER(),0640)) {
                   13240:  	if ($bighash{'version_'.$uri}) {
                   13241:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13242:  	    unless (($version eq 'mostrecent') || 
                   13243: 		    ($version==&getversion($uri))) {
1.440     www      13244:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13245:  	    }
                   13246:  	}
                   13247:  	untie %bighash;
1.413     www      13248:     }
1.599     albertel 13249:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13250: }
                   13251: 
                   13252: sub deversion {
                   13253:     my $url=shift;
                   13254:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13255:     return $url;
1.210     www      13256: }
                   13257: 
1.31      www      13258: # ------------------------------------------------------ Return symb list entry
                   13259: 
                   13260: sub symbread {
1.1282    raeburn  13261:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  13262:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  13263:     if (defined($env{$cache_str})) {
                   13264:         if ($ignorecachednull) {
                   13265:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13266:         } else {
                   13267:             return $env{$cache_str};
                   13268:         }
                   13269:     }
1.242     www      13270: # no filename provided? try from environment
1.1265    raeburn  13271:     unless ($thisfn) {
1.620     albertel 13272:         if ($env{'request.symb'}) {
                   13273: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13274: 	}
1.620     albertel 13275: 	$thisfn=$env{'request.filename'};
1.44      www      13276:     }
1.569     albertel 13277:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13278: # is that filename actually a symb? Verify, clean, and return
                   13279:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13280: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 13281: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13282: 	}
1.242     www      13283:     }
1.44      www      13284:     $thisfn=declutter($thisfn);
1.31      www      13285:     my %hash;
1.37      www      13286:     my %bighash;
                   13287:     my $syval='';
1.620     albertel 13288:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13289:         my $targetfn = $thisfn;
1.609     banghart 13290:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13291:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13292:         }
1.687     albertel 13293: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13294: 	    $targetfn=$1;
                   13295: 	}
1.620     albertel 13296:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13297:                       &GDBM_READER(),0640)) {
1.481     raeburn  13298: 	    $syval=$hash{$targetfn};
1.37      www      13299:             untie(%hash);
                   13300:         }
                   13301: # ---------------------------------------------------------- There was an entry
                   13302:         if ($syval) {
1.601     albertel 13303: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13304: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13305: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13306: 		    #return $env{$cache_str}='';
1.601     albertel 13307: 		#}    
                   13308: 		#$syval.=$1;
                   13309: 	    #}
1.37      www      13310:         } else {
                   13311: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13312:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13313:                             &GDBM_READER(),0640)) {
1.37      www      13314: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13315:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13316:               unless ($ids) { 
                   13317:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13318:               }
                   13319:               unless ($ids) {
                   13320: # alias?
                   13321: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13322:               }
1.37      www      13323:               if ($ids) {
                   13324: # ------------------------------------------------------------------- Has ID(s)
                   13325:                  my @possibilities=split(/\,/,$ids);
1.39      www      13326:                  if ($#possibilities==0) {
                   13327: # ----------------------------------------------- There is only one possibility
1.37      www      13328: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13329: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13330: 						    $resid,$thisfn);
1.1282    raeburn  13331:                      if (ref($possibles) eq 'HASH') {
                   13332:                          $possibles->{$syval} = 1;    
                   13333:                      }
                   13334:                      if ($checkforblock) {
                   13335:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   13336:                          if (@blockers) {
                   13337:                              $syval = '';
                   13338:                              return;
                   13339:                          }
                   13340:                      }
                   13341:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13342: # ------------------------------------------ There is more than one possibility
                   13343:                      my $realpossible=0;
1.800     albertel 13344:                      foreach my $id (@possibilities) {
                   13345: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13346:                          my $canaccess;
                   13347:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13348:                              $canaccess = 1;
                   13349:                          } else { 
                   13350:                              $canaccess = &allowed('bre',$file);
                   13351:                          }
                   13352:                          if ($canaccess) {
                   13353:          		     my ($mapid,$resid)=split(/\./,$id);
                   13354:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13355:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13356: 						             $resid,$thisfn);
                   13357:                                  if (ref($possibles) eq 'HASH') {
                   13358:                                      $possibles->{$syval} = 1;
                   13359:                                  }
                   13360:                                  if ($checkforblock) {
                   13361:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   13362:                                      unless (@blockers > 0) {
                   13363:                                          $syval = $poss_syval;
                   13364:                                          $realpossible++;
                   13365:                                      }
                   13366:                                  } else {
                   13367:                                      $syval = $poss_syval;
                   13368:                                      $realpossible++;
                   13369:                                  }
                   13370:                              }
1.39      www      13371: 			 }
1.191     harris41 13372:                      }
1.39      www      13373: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13374:                  } else {
                   13375:                      $syval='';
1.37      www      13376:                  }
                   13377: 	      }
1.1282    raeburn  13378:               untie(%bighash);
1.481     raeburn  13379:            }
1.31      www      13380:         }
1.62      www      13381:         if ($syval) {
1.620     albertel 13382: 	    return $env{$cache_str}=$syval;
1.62      www      13383:         }
1.31      www      13384:     }
1.949     raeburn  13385:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13386:     return $env{$cache_str}='';
1.31      www      13387: }
                   13388: 
                   13389: # ---------------------------------------------------------- Return random seed
                   13390: 
1.32      www      13391: sub numval {
                   13392:     my $txt=shift;
                   13393:     $txt=~tr/A-J/0-9/;
                   13394:     $txt=~tr/a-j/0-9/;
                   13395:     $txt=~tr/K-T/0-9/;
                   13396:     $txt=~tr/k-t/0-9/;
                   13397:     $txt=~tr/U-Z/0-5/;
                   13398:     $txt=~tr/u-z/0-5/;
                   13399:     $txt=~s/\D//g;
1.564     albertel 13400:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13401:     return int($txt);
1.368     albertel 13402: }
                   13403: 
1.484     albertel 13404: sub numval2 {
                   13405:     my $txt=shift;
                   13406:     $txt=~tr/A-J/0-9/;
                   13407:     $txt=~tr/a-j/0-9/;
                   13408:     $txt=~tr/K-T/0-9/;
                   13409:     $txt=~tr/k-t/0-9/;
                   13410:     $txt=~tr/U-Z/0-5/;
                   13411:     $txt=~tr/u-z/0-5/;
                   13412:     $txt=~s/\D//g;
                   13413:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13414:     my $total;
                   13415:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13416:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13417:     return int($total);
                   13418: }
                   13419: 
1.575     albertel 13420: sub numval3 {
                   13421:     use integer;
                   13422:     my $txt=shift;
                   13423:     $txt=~tr/A-J/0-9/;
                   13424:     $txt=~tr/a-j/0-9/;
                   13425:     $txt=~tr/K-T/0-9/;
                   13426:     $txt=~tr/k-t/0-9/;
                   13427:     $txt=~tr/U-Z/0-5/;
                   13428:     $txt=~tr/u-z/0-5/;
                   13429:     $txt=~s/\D//g;
                   13430:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13431:     my $total;
                   13432:     foreach my $val (@txts) { $total+=$val; }
                   13433:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13434:     return $total;
                   13435: }
                   13436: 
1.675     albertel 13437: sub digest {
                   13438:     my ($data)=@_;
                   13439:     my $digest=&Digest::MD5::md5($data);
                   13440:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13441:     my ($e,$f);
                   13442:     {
                   13443:         use integer;
                   13444:         $e=($a+$b);
                   13445:         $f=($c+$d);
                   13446:         if ($_64bit) {
                   13447:             $e=(($e<<32)>>32);
                   13448:             $f=(($f<<32)>>32);
                   13449:         }
                   13450:     }
                   13451:     if (wantarray) {
                   13452: 	return ($e,$f);
                   13453:     } else {
                   13454: 	my $g;
                   13455: 	{
                   13456: 	    use integer;
                   13457: 	    $g=($e+$f);
                   13458: 	    if ($_64bit) {
                   13459: 		$g=(($g<<32)>>32);
                   13460: 	    }
                   13461: 	}
                   13462: 	return $g;
                   13463:     }
                   13464: }
                   13465: 
1.368     albertel 13466: sub latest_rnd_algorithm_id {
1.675     albertel 13467:     return '64bit5';
1.366     albertel 13468: }
1.32      www      13469: 
1.503     albertel 13470: sub get_rand_alg {
                   13471:     my ($courseid)=@_;
1.790     albertel 13472:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13473:     if ($courseid) {
1.620     albertel 13474: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13475:     }
                   13476:     return &latest_rnd_algorithm_id();
                   13477: }
                   13478: 
1.562     albertel 13479: sub validCODE {
                   13480:     my ($CODE)=@_;
                   13481:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13482:     return 0;
                   13483: }
                   13484: 
1.491     albertel 13485: sub getCODE {
1.620     albertel 13486:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13487:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13488: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13489: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13490: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13491:     }
                   13492:     return undef;
                   13493: }
1.1133    foxr     13494: #
                   13495: #  Determines the random seed for a specific context:
                   13496: #
                   13497: # parameters:
                   13498: #   symb      - in course context the symb for the seed.
                   13499: #   course_id - The course id of the form domain_coursenum.
                   13500: #   domain    - Domain for the user.
                   13501: #   course    - Course for the user.
                   13502: #   cenv      - environment of the course.
                   13503: #
                   13504: # NOTE:
                   13505: #   All parameters are picked out of the environment if missing
                   13506: #   or not defined.
                   13507: #   If a symb cannot be determined the current time is used instead.
                   13508: #
                   13509: #  For a given well defined symb, courside, domain, username,
                   13510: #  and course environment, the seed is reproducible.
                   13511: #
1.31      www      13512: sub rndseed {
1.1133    foxr     13513:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13514:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13515:     if (!defined($symb)) {
1.366     albertel 13516: 	unless ($symb=$wsymb) { return time; }
                   13517:     }
1.1146    foxr     13518:     if (!defined $courseid) { 
                   13519: 	$courseid=$wcourseid; 
                   13520:     }
                   13521:     if (!defined $domain) { $domain=$wdomain; }
                   13522:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13523: 
                   13524:     my $which;
                   13525:     if (defined($cenv->{'rndseed'})) {
                   13526: 	$which = $cenv->{'rndseed'};
                   13527:     } else {
                   13528: 	$which =&get_rand_alg($courseid);
                   13529:     }
1.491     albertel 13530:     if (defined(&getCODE())) {
1.1133    foxr     13531: 
1.675     albertel 13532: 	if ($which eq '64bit5') {
                   13533: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13534: 	} elsif ($which eq '64bit4') {
1.575     albertel 13535: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13536: 	} else {
                   13537: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13538: 	}
1.675     albertel 13539:     } elsif ($which eq '64bit5') {
                   13540: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13541:     } elsif ($which eq '64bit4') {
                   13542: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13543:     } elsif ($which eq '64bit3') {
                   13544: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13545:     } elsif ($which eq '64bit2') {
                   13546: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13547:     } elsif ($which eq '64bit') {
                   13548: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13549:     }
                   13550:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13551: }
                   13552: 
                   13553: sub rndseed_32bit {
                   13554:     my ($symb,$courseid,$domain,$username)=@_;
                   13555:     {
                   13556: 	use integer;
                   13557: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13558: 	my $symbseed=numval($symb) << 22;
                   13559: 	my $namechck=unpack("%32C*",$username) << 17;
                   13560: 	my $nameseed=numval($username) << 12;
                   13561: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13562: 	my $courseseed=unpack("%32C*",$courseid);
                   13563: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13564: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13565: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13566: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13567: 	return $num;
                   13568:     }
                   13569: }
                   13570: 
                   13571: sub rndseed_64bit {
                   13572:     my ($symb,$courseid,$domain,$username)=@_;
                   13573:     {
                   13574: 	use integer;
                   13575: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13576: 	my $symbseed=numval($symb) << 10;
                   13577: 	my $namechck=unpack("%32S*",$username);
                   13578: 	
                   13579: 	my $nameseed=numval($username) << 21;
                   13580: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13581: 	my $courseseed=unpack("%32S*",$courseid);
                   13582: 	
                   13583: 	my $num1=$symbchck+$symbseed+$namechck;
                   13584: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13585: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13586: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13587: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13588: 	return "$num1,$num2";
1.155     albertel 13589:     }
1.366     albertel 13590: }
                   13591: 
1.443     albertel 13592: sub rndseed_64bit2 {
                   13593:     my ($symb,$courseid,$domain,$username)=@_;
                   13594:     {
                   13595: 	use integer;
                   13596: 	# strings need to be an even # of cahracters long, it it is odd the
                   13597:         # last characters gets thrown away
                   13598: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13599: 	my $symbseed=numval($symb) << 10;
                   13600: 	my $namechck=unpack("%32S*",$username.' ');
                   13601: 	
                   13602: 	my $nameseed=numval($username) << 21;
1.501     albertel 13603: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13604: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13605: 	
                   13606: 	my $num1=$symbchck+$symbseed+$namechck;
                   13607: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13608: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13609: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13610: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13611: 	return "$num1,$num2";
                   13612:     }
                   13613: }
                   13614: 
                   13615: sub rndseed_64bit3 {
                   13616:     my ($symb,$courseid,$domain,$username)=@_;
                   13617:     {
                   13618: 	use integer;
                   13619: 	# strings need to be an even # of cahracters long, it it is odd the
                   13620:         # last characters gets thrown away
                   13621: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13622: 	my $symbseed=numval2($symb) << 10;
                   13623: 	my $namechck=unpack("%32S*",$username.' ');
                   13624: 	
                   13625: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13626: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13627: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13628: 	
                   13629: 	my $num1=$symbchck+$symbseed+$namechck;
                   13630: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13631: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13632: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13633: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13634: 	
1.503     albertel 13635: 	return "$num1:$num2";
1.443     albertel 13636:     }
                   13637: }
                   13638: 
1.575     albertel 13639: sub rndseed_64bit4 {
                   13640:     my ($symb,$courseid,$domain,$username)=@_;
                   13641:     {
                   13642: 	use integer;
                   13643: 	# strings need to be an even # of cahracters long, it it is odd the
                   13644:         # last characters gets thrown away
                   13645: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13646: 	my $symbseed=numval3($symb) << 10;
                   13647: 	my $namechck=unpack("%32S*",$username.' ');
                   13648: 	
                   13649: 	my $nameseed=numval3($username) << 21;
                   13650: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13651: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13652: 	
                   13653: 	my $num1=$symbchck+$symbseed+$namechck;
                   13654: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13655: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13656: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13657: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13658: 	
1.575     albertel 13659: 	return "$num1:$num2";
                   13660:     }
                   13661: }
                   13662: 
1.675     albertel 13663: sub rndseed_64bit5 {
                   13664:     my ($symb,$courseid,$domain,$username)=@_;
                   13665:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13666:     return "$num1:$num2";
                   13667: }
                   13668: 
1.366     albertel 13669: sub rndseed_CODE_64bit {
                   13670:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13671:     {
1.366     albertel 13672: 	use integer;
1.443     albertel 13673: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13674: 	my $symbseed=numval2($symb);
1.491     albertel 13675: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13676: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13677: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13678: 	my $num1=$symbseed+$CODEchck;
                   13679: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13680: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13681: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13682: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13683: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13684: 	return "$num1:$num2";
1.366     albertel 13685:     }
                   13686: }
                   13687: 
1.575     albertel 13688: sub rndseed_CODE_64bit4 {
                   13689:     my ($symb,$courseid,$domain,$username)=@_;
                   13690:     {
                   13691: 	use integer;
                   13692: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13693: 	my $symbseed=numval3($symb);
                   13694: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13695: 	my $CODEseed=numval3(&getCODE());
                   13696: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13697: 	my $num1=$symbseed+$CODEchck;
                   13698: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13699: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13700: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13701: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13702: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13703: 	return "$num1:$num2";
                   13704:     }
                   13705: }
                   13706: 
1.675     albertel 13707: sub rndseed_CODE_64bit5 {
                   13708:     my ($symb,$courseid,$domain,$username)=@_;
                   13709:     my $code = &getCODE();
                   13710:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13711:     return "$num1:$num2";
                   13712: }
                   13713: 
1.366     albertel 13714: sub setup_random_from_rndseed {
                   13715:     my ($rndseed)=@_;
1.503     albertel 13716:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13717:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13718:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13719:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13720:         } else {
                   13721:             &Math::Random::random_set_seed($num1,$num2);
                   13722:         }
1.366     albertel 13723:     } else {
                   13724: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13725:     }
1.36      albertel 13726: }
                   13727: 
1.474     albertel 13728: sub latest_receipt_algorithm_id {
1.835     albertel 13729:     return 'receipt3';
1.474     albertel 13730: }
                   13731: 
1.480     www      13732: sub recunique {
                   13733:     my $fucourseid=shift;
                   13734:     my $unique;
1.835     albertel 13735:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13736: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13737: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13738:     } else {
                   13739: 	$unique=$perlvar{'lonReceipt'};
                   13740:     }
                   13741:     return unpack("%32C*",$unique);
                   13742: }
                   13743: 
                   13744: sub recprefix {
                   13745:     my $fucourseid=shift;
                   13746:     my $prefix;
1.835     albertel 13747:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13748: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13749: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13750:     } else {
                   13751: 	$prefix=$perlvar{'lonHostID'};
                   13752:     }
                   13753:     return unpack("%32C*",$prefix);
                   13754: }
                   13755: 
1.76      www      13756: sub ireceipt {
1.474     albertel 13757:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13758: 
                   13759:     my $return =&recprefix($fucourseid).'-';
                   13760: 
                   13761:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13762: 	$env{'request.state'} eq 'construct') {
                   13763: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13764: 	return $return;
                   13765:     }
                   13766: 
1.76      www      13767:     my $cuname=unpack("%32C*",$funame);
                   13768:     my $cudom=unpack("%32C*",$fudom);
                   13769:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13770:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13771:     my $cunique=&recunique($fucourseid);
1.474     albertel 13772:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13773:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13774: 
1.790     albertel 13775: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13776: 			       
                   13777: 	$return.= ($cunique%$cuname+
                   13778: 		   $cunique%$cudom+
                   13779: 		   $cusymb%$cuname+
                   13780: 		   $cusymb%$cudom+
                   13781: 		   $cucourseid%$cuname+
                   13782: 		   $cucourseid%$cudom+
                   13783: 		   $cpart%$cuname+
                   13784: 		   $cpart%$cudom);
                   13785:     } else {
                   13786: 	$return.= ($cunique%$cuname+
                   13787: 		   $cunique%$cudom+
                   13788: 		   $cusymb%$cuname+
                   13789: 		   $cusymb%$cudom+
                   13790: 		   $cucourseid%$cuname+
                   13791: 		   $cucourseid%$cudom);
                   13792:     }
                   13793:     return $return;
1.76      www      13794: }
                   13795: 
                   13796: sub receipt {
1.474     albertel 13797:     my ($part)=@_;
1.790     albertel 13798:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13799:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13800: }
1.260     ng       13801: 
1.790     albertel 13802: sub whichuser {
                   13803:     my ($passedsymb)=@_;
                   13804:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13805:     if (defined($env{'form.grade_symb'})) {
                   13806: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13807: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13808: 	if (!$allowed &&
                   13809: 	    exists($env{'request.course.sec'}) &&
                   13810: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13811: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13812: 			      '/'.$env{'request.course.sec'});
                   13813: 	}
                   13814: 	if ($allowed) {
                   13815: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13816: 	    $courseid=$tmp_courseid;
                   13817: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13818: 	    ($name)=&get_env_multiple('form.grade_username');
                   13819: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13820: 	}
                   13821:     }
                   13822:     if (!$passedsymb) {
                   13823: 	$symb=&symbread();
                   13824:     } else {
                   13825: 	$symb=$passedsymb;
                   13826:     }
                   13827:     $courseid=$env{'request.course.id'};
                   13828:     $domain=$env{'user.domain'};
                   13829:     $name=$env{'user.name'};
                   13830:     if ($name eq 'public' && $domain eq 'public') {
                   13831: 	if (!defined($env{'form.username'})) {
                   13832: 	    $env{'form.username'}.=time.rand(10000000);
                   13833: 	}
                   13834: 	$name.=$env{'form.username'};
                   13835:     }
                   13836:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13837: 
                   13838: }
                   13839: 
1.36      albertel 13840: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13841: # returns either the contents of the file or 
                   13842: # -1 if the file doesn't exist
1.481     raeburn  13843: #
                   13844: # if the target is a file that was uploaded via DOCS, 
                   13845: # a check will be made to see if a current copy exists on the local server,
                   13846: # if it does this will be served, otherwise a copy will be retrieved from
                   13847: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13848: # the local server.   
1.472     albertel 13849: 
1.36      albertel 13850: sub getfile {
1.538     albertel 13851:     my ($file) = @_;
1.609     banghart 13852:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13853:     &repcopy($file);
                   13854:     return &readfile($file);
                   13855: }
                   13856: 
                   13857: sub repcopy_userfile {
                   13858:     my ($file)=@_;
1.1142    raeburn  13859:     my $londocroot = $perlvar{'lonDocRoot'};
                   13860:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13861:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13862:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13863: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13864:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13865:     if (-e "$file") {
1.828     www      13866: # we already have a local copy, check it out
1.538     albertel 13867: 	my @fileinfo = stat($file);
1.828     www      13868: 	my $rtncode;
                   13869: 	my $info;
1.538     albertel 13870: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13871: 	if ($lwpresp ne 'ok') {
1.828     www      13872: # there is no such file anymore, even though we had a local copy
1.482     albertel 13873: 	    if ($rtncode eq '404') {
1.538     albertel 13874: 		unlink($file);
1.482     albertel 13875: 	    }
                   13876: 	    return -1;
                   13877: 	}
                   13878: 	if ($info < $fileinfo[9]) {
1.828     www      13879: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13880: 	    return 'ok';
1.828     www      13881: 	} else {
                   13882: # the file is outdated, get rid of it
                   13883: 	    unlink($file);
1.482     albertel 13884: 	}
1.828     www      13885:     }
                   13886: # one way or the other, at this point, we don't have the file
                   13887: # construct the correct path for the file
                   13888:     my @parts = ($cdom,$cnum); 
                   13889:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13890: 	push @parts, split(/\//,$1);
                   13891:     }
                   13892:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13893:     foreach my $part (@parts) {
                   13894: 	$path .= '/'.$part;
                   13895: 	if (!-e $path) {
                   13896: 	    mkdir($path,0770);
1.482     albertel 13897: 	}
                   13898:     }
1.828     www      13899: # now the path exists for sure
                   13900: # get a user agent
                   13901:     my $transferfile=$file.'.in.transfer';
                   13902: # FIXME: this should flock
                   13903:     if (-e $transferfile) { return 'ok'; }
                   13904:     my $request;
                   13905:     $uri=~s/^\///;
1.980     raeburn  13906:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  13907:     my $hostname = &hostname($homeserver);
1.980     raeburn  13908:     my $protocol = $protocol{$homeserver};
                   13909:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13910:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  13911:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13912: # did it work?
                   13913:     if ($response->is_error()) {
                   13914: 	unlink($transferfile);
                   13915: 	&logthis("Userfile repcopy failed for $uri");
                   13916: 	return -1;
                   13917:     }
                   13918: # worked, rename the transfer file
                   13919:     rename($transferfile,$file);
1.607     raeburn  13920:     return 'ok';
1.481     raeburn  13921: }
                   13922: 
1.517     albertel 13923: sub tokenwrapper {
                   13924:     my $uri=shift;
1.980     raeburn  13925:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13926:     $uri=~s|^/||;
1.620     albertel 13927:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13928:     my $token=$1;
1.552     albertel 13929:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13930:     if ($udom && $uname && $file) {
                   13931: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13932:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13933:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  13934:         my $hostname = &hostname($homeserver);
1.980     raeburn  13935:         my $protocol = $protocol{$homeserver};
                   13936:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13937:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13938:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13939:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13940:     } else {
                   13941:         return '/adm/notfound.html';
                   13942:     }
                   13943: }
                   13944: 
1.828     www      13945: # call with reqtype HEAD: get last modification time
                   13946: # call with reqtype GET: get the file contents
                   13947: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13948: #
1.481     raeburn  13949: sub getuploaded {
                   13950:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13951:     $uri=~s/^\///;
1.980     raeburn  13952:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  13953:     my $hostname = &hostname($homeserver);
1.980     raeburn  13954:     my $protocol = $protocol{$homeserver};
                   13955:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13956:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13957:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13958:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13959:     $$rtncode = $response->code;
1.482     albertel 13960:     if (! $response->is_success()) {
                   13961: 	return 'failed';
                   13962:     }      
                   13963:     if ($reqtype eq 'HEAD') {
1.486     www      13964: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13965:     } elsif ($reqtype eq 'GET') {
                   13966: 	$$info = $response->content;
1.472     albertel 13967:     }
1.482     albertel 13968:     return 'ok';
1.36      albertel 13969: }
                   13970: 
1.481     raeburn  13971: sub readfile {
                   13972:     my $file = shift;
                   13973:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13974:     my $fh;
1.1359    raeburn  13975:     open($fh,"<",$file);
1.481     raeburn  13976:     my $a='';
1.800     albertel 13977:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13978:     return $a;
                   13979: }
                   13980: 
1.36      albertel 13981: sub filelocation {
1.590     banghart 13982:     my ($dir,$file) = @_;
                   13983:     my $location;
                   13984:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13985: 
                   13986:     if ($file =~ m-^/adm/-) {
                   13987: 	$file=~s-^/adm/wrapper/-/-;
                   13988: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13989:     }
1.882     albertel 13990: 
1.1139    www      13991:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13992:         $location = $file;
1.609     banghart 13993:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13994:         my ($udom,$uname,$filename)=
1.811     albertel 13995:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13996:         my $home=&homeserver($uname,$udom);
                   13997:         my $is_me=0;
                   13998:         my @ids=&current_machine_ids();
                   13999:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14000:         if ($is_me) {
1.1117    foxr     14001:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14002:         } else {
                   14003:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14004:   	      $udom.'/'.$uname.'/'.$filename;
                   14005:         }
1.882     albertel 14006:     } elsif ($file =~ m-^/adm/-) {
                   14007: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14008:     } else {
                   14009:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14010:         $file=~s:^/(res|priv)/:/:;
                   14011:         my $space=$1;
1.590     banghart 14012:         if ( !( $file =~ m:^/:) ) {
                   14013:             $location = $dir. '/'.$file;
                   14014:         } else {
1.1142    raeburn  14015:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14016:         }
1.59      albertel 14017:     }
1.590     banghart 14018:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14019:     while ($location=~m{/\.\./}) {
                   14020: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14021: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14022: 	} else {
                   14023: 	    $location=~ s{/\.\./}{/}g;
                   14024: 	}
                   14025:     } #remove dir/..
1.590     banghart 14026:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14027:     return $location;
1.46      www      14028: }
1.36      albertel 14029: 
1.46      www      14030: sub hreflocation {
                   14031:     my ($dir,$file)=@_;
1.980     raeburn  14032:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14033: 	$file=filelocation($dir,$file);
1.700     albertel 14034:     } elsif ($file=~m-^/adm/-) {
                   14035: 	$file=~s-^/adm/wrapper/-/-;
                   14036: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14037:     }
                   14038:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14039: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14040:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14041: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14042: 	        {/uploaded/$1/$2/}x;
1.46      www      14043:     }
1.913     albertel 14044:     if ($file=~ m{^/userfiles/}) {
                   14045: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14046:     }
1.462     albertel 14047:     return $file;
1.465     albertel 14048: }
                   14049: 
1.1139    www      14050: 
                   14051: 
                   14052: 
                   14053: 
1.465     albertel 14054: sub current_machine_domains {
1.853     albertel 14055:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14056: }
                   14057: 
                   14058: sub machine_domains {
                   14059:     my ($hostname) = @_;
1.465     albertel 14060:     my @domains;
1.838     albertel 14061:     my %hostname = &all_hostnames();
1.465     albertel 14062:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14063: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14064: 	if ($hostname eq $name) {
1.844     albertel 14065: 	    push(@domains,&host_domain($id));
1.465     albertel 14066: 	}
                   14067:     }
                   14068:     return @domains;
                   14069: }
                   14070: 
                   14071: sub current_machine_ids {
1.853     albertel 14072:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14073: }
                   14074: 
                   14075: sub machine_ids {
                   14076:     my ($hostname) = @_;
                   14077:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14078:     my @ids;
1.888     albertel 14079:     my %name_to_host = &all_names();
1.889     albertel 14080:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14081: 	return @{ $name_to_host{$hostname} };
                   14082:     }
                   14083:     return;
1.31      www      14084: }
                   14085: 
1.824     raeburn  14086: sub additional_machine_domains {
                   14087:     my @domains;
1.1359    raeburn  14088:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  14089:     while( my $line = <$fh>) {
                   14090:         $line =~ s/\s//g;
                   14091:         push(@domains,$line);
                   14092:     }
                   14093:     return @domains;
                   14094: }
                   14095: 
                   14096: sub default_login_domain {
                   14097:     my $domain = $perlvar{'lonDefDomain'};
                   14098:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14099:     foreach my $posdom (&current_machine_domains(),
                   14100:                         &additional_machine_domains()) {
                   14101:         if (lc($posdom) eq lc($testdomain)) {
                   14102:             $domain=$posdom;
                   14103:             last;
                   14104:         }
                   14105:     }
                   14106:     return $domain;
                   14107: }
                   14108: 
1.1414    raeburn  14109: sub shared_institution {
                   14110:     my ($dom) = @_;
                   14111:     my $same_intdom;
                   14112:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   14113:     if ($hostintdom ne '') {
                   14114:         my %iphost = &get_iphost();
                   14115:         my $primary_id = &domain($dom,'primary');
                   14116:         my $primary_ip = &get_host_ip($primary_id);
                   14117:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14118:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14119:                 my $intdom = &internet_dom($id);
                   14120:                 if ($intdom eq $hostintdom) {
                   14121:                     $same_intdom = 1;
                   14122:                     last;
                   14123:                 }
                   14124:             }
                   14125:         }
                   14126:     }
                   14127:     return $same_intdom;
                   14128: }
                   14129: 
1.1398    raeburn  14130: sub uses_sts {
                   14131:     my ($ignore_cache) = @_;
                   14132:     my $lonhost = $perlvar{'lonHostID'};
                   14133:     my $hostname = &hostname($lonhost);
                   14134:     my $sts_on;
                   14135:     if ($protocol{$lonhost} eq 'https') {
                   14136:         my $cachetime = 12*3600;
                   14137:         if (!$ignore_cache) {
                   14138:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14139:             if (defined($cached)) {
                   14140:                 return $sts_on;
                   14141:             }
                   14142:         }
                   14143:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14144:         my $request=new HTTP::Request('HEAD',$url);
                   14145:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14146:         if ($response->is_success) {
                   14147:             my $has_sts = $response->header('Strict-Transport-Security');
                   14148:             if ($has_sts eq '') {
                   14149:                 $sts_on = 0;
                   14150:             } else {
                   14151:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14152:                     my $maxage = $1;
                   14153:                     if ($maxage) {
                   14154:                         $sts_on = 1;
                   14155:                     } else {
                   14156:                         $sts_on = 0;
                   14157:                     }
                   14158:                 } else {
                   14159:                     $sts_on = 0;
                   14160:                 }
                   14161:             }
                   14162:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14163:         }
                   14164:     }
                   14165:     return;
                   14166: }
                   14167: 
1.31      www      14168: # ------------------------------------------------------------- Declutters URLs
                   14169: 
                   14170: sub declutter {
                   14171:     my $thisfn=shift;
1.569     albertel 14172:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14173:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14174:         $thisfn=~s{^/home/httpd/html}{};
                   14175:     }
1.31      www      14176:     $thisfn=~s/^\///;
1.697     albertel 14177:     $thisfn=~s|^adm/wrapper/||;
                   14178:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14179:     $thisfn=~s/^res\///;
1.1172    bisitz   14180:     $thisfn=~s/^priv\///;
1.1032    raeburn  14181:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14182:         $thisfn=~s/\?.+$//;
                   14183:     }
1.268     www      14184:     return $thisfn;
                   14185: }
                   14186: 
                   14187: # ------------------------------------------------------------- Clutter up URLs
                   14188: 
                   14189: sub clutter {
                   14190:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14191:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14192: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14193:        $thisfn='/res'.$thisfn; 
                   14194:     }
1.1031    raeburn  14195:     if ($thisfn !~m|^/adm|) {
                   14196: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14197: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14198: 	} else {
                   14199: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14200: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14201: 	    if ($embstyle eq 'ssi'
                   14202: 		|| ($embstyle eq 'hdn')
                   14203: 		|| ($embstyle eq 'rat')
                   14204: 		|| ($embstyle eq 'prv')
                   14205: 		|| ($embstyle eq 'ign')) {
                   14206: 		#do nothing with these
                   14207: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14208: 		|| ($embstyle eq 'emb')
                   14209: 		|| ($embstyle eq 'wrp')) {
                   14210: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14211: 	    } elsif ($embstyle eq 'unk'
                   14212: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14213: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14214: 	    } else {
1.718     www      14215: #		&logthis("Got a blank emb style");
1.695     albertel 14216: 	    }
1.694     albertel 14217: 	}
1.1343    raeburn  14218:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14219:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14220:     }
1.31      www      14221:     return $thisfn;
1.12      www      14222: }
                   14223: 
1.787     albertel 14224: sub clutter_with_no_wrapper {
                   14225:     my $uri = &clutter(shift);
                   14226:     if ($uri =~ m-^/adm/-) {
                   14227: 	$uri =~ s-^/adm/wrapper/-/-;
                   14228: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14229:     }
                   14230:     return $uri;
                   14231: }
                   14232: 
1.557     albertel 14233: sub freeze_escape {
                   14234:     my ($value)=@_;
                   14235:     if (ref($value)) {
                   14236: 	$value=&nfreeze($value);
                   14237: 	return '__FROZEN__'.&escape($value);
                   14238:     }
                   14239:     return &escape($value);
                   14240: }
                   14241: 
1.11      www      14242: 
1.557     albertel 14243: sub thaw_unescape {
                   14244:     my ($value)=@_;
                   14245:     if ($value =~ /^__FROZEN__/) {
                   14246: 	substr($value,0,10,undef);
                   14247: 	$value=&unescape($value);
                   14248: 	return &thaw($value);
                   14249:     }
                   14250:     return &unescape($value);
                   14251: }
                   14252: 
1.436     albertel 14253: sub correct_line_ends {
                   14254:     my ($result)=@_;
                   14255:     $$result =~s/\r\n/\n/mg;
                   14256:     $$result =~s/\r/\n/mg;
1.415     albertel 14257: }
1.1       albertel 14258: # ================================================================ Main Program
                   14259: 
1.184     www      14260: sub goodbye {
1.204     albertel 14261:    &logthis("Starting Shut down");
1.443     albertel 14262: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14263:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14264: #converted
1.599     albertel 14265: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14266:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14267: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14268: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14269: #1.1 only
1.870     albertel 14270: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14271: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14272: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14273: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14274:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14275:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14276:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14277:    &flushcourselogs();
                   14278:    &logthis("Shutting down");
                   14279: }
                   14280: 
1.852     albertel 14281: sub get_dns {
1.1210    raeburn  14282:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14283:     if (!$ignore_cache) {
                   14284: 	my ($content,$cached)=
                   14285: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14286: 	if ($cached) {
1.1210    raeburn  14287: 	    &$func($content,$hashref);
1.869     albertel 14288: 	    return;
                   14289: 	}
                   14290:     }
                   14291: 
                   14292:     my %alldns;
1.1379    raeburn  14293:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14294:         foreach my $dns (<$config>) {
                   14295: 	    next if ($dns !~ /^\^(\S*)/x);
                   14296:             my $line = $1;
                   14297:             my ($host,$protocol) = split(/:/,$line);
                   14298:             if ($protocol ne 'https') {
                   14299:                 $protocol = 'http';
                   14300:             }
                   14301: 	    $alldns{$host} = $protocol;
1.979     raeburn  14302:         }
1.1379    raeburn  14303:         close($config);
1.869     albertel 14304:     }
                   14305:     while (%alldns) {
1.1263    raeburn  14306: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  14307: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  14308:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  14309:         delete($alldns{$dns});
1.852     albertel 14310: 	next if ($response->is_error());
1.1379    raeburn  14311:         if ($url eq '/adm/dns/loncapaCRL') {
                   14312:             return &$func($response);
                   14313:         } else {
                   14314: 	    my @content = split("\n",$response->content);
                   14315: 	    unless ($nocache) {
                   14316: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14317: 	    }
                   14318: 	    &$func(\@content,$hashref);
                   14319:             return;
                   14320:         }
                   14321:     }
                   14322:     my $which = (split('/',$url,4))[3];
                   14323:     if ($which eq 'loncapaCRL') {
                   14324:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14325:         if (-e $diskfile) {
                   14326:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14327:         } else {
                   14328:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14329:         }
                   14330:     } else {
                   14331:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14332:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14333:             my @content = <$config>;
                   14334:             close($config);
                   14335:             &$func(\@content,$hashref);
                   14336:         }
1.852     albertel 14337:     }
1.1210    raeburn  14338:     return;
                   14339: }
                   14340: 
                   14341: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14342: sub parse_dns_checksums_tab {
1.1210    raeburn  14343:     my ($lines,$hashref) = @_;
1.1264    raeburn  14344:     my $lonhost = $perlvar{'lonHostID'};
                   14345:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14346:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14347:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14348:     my $webconfdir = '/etc/httpd/conf';
                   14349:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14350:         $webconfdir = '/etc/apache2';
                   14351:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14352:         if ($1 >= 10) {
                   14353:             $webconfdir = '/etc/apache2';
                   14354:         }
                   14355:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14356:         if ($1 >= 10.0) {
                   14357:             $webconfdir = '/etc/apache2';
                   14358:         }
                   14359:     }
1.1210    raeburn  14360:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14361:     my (%chksum,%revnum);
                   14362:     if (ref($lines) eq 'ARRAY') {
                   14363:         chomp(@{$lines});
1.1238    raeburn  14364:         my $version = shift(@{$lines});
                   14365:         if ($version eq $release) {  
1.1210    raeburn  14366:             foreach my $line (@{$lines}) {
1.1238    raeburn  14367:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14368:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14369:                     if ($webconfdir eq '/etc/apache2') {
                   14370:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14371:                     }
                   14372:                 }
1.1238    raeburn  14373:                 $chksum{$file} = $shasum;
                   14374:                 $revnum{$file} = $version;
1.1210    raeburn  14375:             }
                   14376:             if (ref($hashref) eq 'HASH') {
                   14377:                 %{$hashref} = (
                   14378:                                 sums     => \%chksum,
                   14379:                                 versions => \%revnum,
                   14380:                               );
                   14381:             }
                   14382:         }
                   14383:     }
1.869     albertel 14384:     return;
1.852     albertel 14385: }
1.1210    raeburn  14386: 
                   14387: sub fetch_dns_checksums {
1.1238    raeburn  14388:     my %checksums;
                   14389:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14390:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14391:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14392:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14393:              \%checksums);
1.1210    raeburn  14394:     return \%checksums;
                   14395: }
                   14396: 
1.1379    raeburn  14397: sub fetch_crl_pemfile {
                   14398:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14399: }
                   14400: 
                   14401: sub save_crl_pem {
                   14402:     my ($response) = @_;
1.1380    raeburn  14403:     my ($msg,$hadchanges);
1.1379    raeburn  14404:     if (ref($response)) {
                   14405:         my $now = time;
                   14406:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14407:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14408:         if (open(my $fh,'>',"$tmpcrl")) {
                   14409:             print $fh $response->content;
                   14410:             close($fh);
                   14411:             if (-e $lonca) {
                   14412:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14413:                     my $check = <PIPE>;
                   14414:                     close(PIPE);
                   14415:                     chomp($check);
                   14416:                     if ($check eq 'verify OK') {
                   14417:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  14418:                         my $backup;
1.1379    raeburn  14419:                         if (-e $dest) {
1.1380    raeburn  14420:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   14421:                                 $backup = 'ok';
                   14422:                             }
1.1379    raeburn  14423:                         }
                   14424:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   14425:                             $msg = 'ok';
1.1380    raeburn  14426:                             if ($backup) {
                   14427:                                 my (%oldnums,%newnums);
                   14428:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   14429:                                     while (<PIPE>) {
                   14430:                                         $oldnums{(split(/:/))[1]} = 1;
                   14431:                                     }
                   14432:                                     close(PIPE);
                   14433:                                 }
                   14434:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   14435:                                     while(<PIPE>) {
                   14436:                                         $newnums{(split(/:/))[1]} = 1;
                   14437:                                     }
                   14438:                                     close(PIPE);
                   14439:                                 }
                   14440:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   14441:                                     unless (exists($oldnums{$key})) {
                   14442:                                         $hadchanges = 1;
                   14443:                                         last;
                   14444:                                     }
                   14445:                                 }
                   14446:                                 unless ($hadchanges) {
                   14447:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   14448:                                         unless (exists($newnums{$key})) {
                   14449:                                             $hadchanges = 1;
                   14450:                                             last;
                   14451:                                         }
                   14452:                                     }
                   14453:                                 }
                   14454:                             }
1.1379    raeburn  14455:                         }
                   14456:                     } else {
                   14457:                         unlink($tmpcrl);
                   14458:                     }
                   14459:                 } else {
                   14460:                     unlink($tmpcrl);
                   14461:                 }
                   14462:             } else {
                   14463:                 unlink($tmpcrl);
                   14464:             }
                   14465:         }
                   14466:     }
1.1380    raeburn  14467:     return ($msg,$hadchanges);
1.1379    raeburn  14468: }
                   14469: 
1.327     albertel 14470: # ------------------------------------------------------------ Read domain file
                   14471: {
1.852     albertel 14472:     my $loaded;
1.846     albertel 14473:     my %domain;
                   14474: 
1.852     albertel 14475:     sub parse_domain_tab {
                   14476: 	my ($lines) = @_;
                   14477: 	foreach my $line (@$lines) {
                   14478: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14479: 
1.846     albertel 14480: 	    chomp($line);
1.852     albertel 14481: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14482: 	    my %this_domain;
                   14483: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14484: 			       'lang_def', 'city', 'longi', 'lati',
                   14485: 			       'primary') {
                   14486: 		$this_domain{$field} = shift(@elements);
                   14487: 	    }
                   14488: 	    $domain{$name} = \%this_domain;
1.852     albertel 14489: 	}
                   14490:     }
1.864     albertel 14491: 
                   14492:     sub reset_domain_info {
                   14493: 	undef($loaded);
                   14494: 	undef(%domain);
                   14495:     }
                   14496: 
1.852     albertel 14497:     sub load_domain_tab {
1.1293    raeburn  14498: 	my ($ignore_cache,$nocache) = @_;
                   14499: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14500: 	my $fh;
1.1359    raeburn  14501: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14502: 	    my @lines = <$fh>;
                   14503: 	    &parse_domain_tab(\@lines);
1.448     albertel 14504: 	}
1.852     albertel 14505: 	close($fh);
                   14506: 	$loaded = 1;
1.327     albertel 14507:     }
1.846     albertel 14508: 
                   14509:     sub domain {
1.852     albertel 14510: 	&load_domain_tab() if (!$loaded);
                   14511: 
1.846     albertel 14512: 	my ($name,$what) = @_;
                   14513: 	return if ( !exists($domain{$name}) );
                   14514: 
                   14515: 	if (!$what) {
                   14516: 	    return $domain{$name}{'description'};
                   14517: 	}
                   14518: 	return $domain{$name}{$what};
                   14519:     }
1.974     raeburn  14520: 
                   14521:     sub domain_info {
                   14522:         &load_domain_tab() if (!$loaded);
                   14523:         return %domain;
                   14524:     }
                   14525: 
1.327     albertel 14526: }
                   14527: 
                   14528: 
1.1       albertel 14529: # ------------------------------------------------------------- Read hosts file
                   14530: {
1.838     albertel 14531:     my %hostname;
1.844     albertel 14532:     my %hostdom;
1.845     albertel 14533:     my %libserv;
1.852     albertel 14534:     my $loaded;
1.888     albertel 14535:     my %name_to_host;
1.1074    raeburn  14536:     my %internetdom;
1.1107    raeburn  14537:     my %LC_dns_serv;
1.852     albertel 14538: 
                   14539:     sub parse_hosts_tab {
                   14540: 	my ($file) = @_;
                   14541: 	foreach my $configline (@$file) {
                   14542: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14543:             chomp($configline);
                   14544: 	    if ($configline =~ /^\^/) {
                   14545:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14546:                     $LC_dns_serv{$1} = 1;
                   14547:                 }
                   14548:                 next;
                   14549:             }
1.1074    raeburn  14550: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14551: 	    $name=~s/\s//g;
                   14552: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  14553:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14554:                     my $curr = $hostname{$id};
                   14555:                     my $skip;
                   14556:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14557:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14558:                             $skip = 1;
                   14559:                         } else {
                   14560:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14561:                         }
                   14562:                     }
                   14563:                     unless ($skip) {
                   14564:                         push(@{$name_to_host{$name}},$id);
                   14565:                     }
                   14566:                 } else {
                   14567:                     push(@{$name_to_host{$name}},$id);
                   14568:                 }
1.852     albertel 14569: 		$hostname{$id}=$name;
                   14570: 		$hostdom{$id}=$domain;
                   14571: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14572:                 if (defined($protocol)) {
                   14573:                     if ($protocol eq 'https') {
                   14574:                         $protocol{$id} = $protocol;
                   14575:                     } else {
                   14576:                         $protocol{$id} = 'http'; 
                   14577:                     }
1.968     raeburn  14578:                 } else {
1.969     raeburn  14579:                     $protocol{$id} = 'http';
1.968     raeburn  14580:                 }
1.1074    raeburn  14581:                 if (defined($intdom)) {
                   14582:                     $internetdom{$id} = $intdom;
                   14583:                 }
1.852     albertel 14584: 	    }
                   14585: 	}
                   14586:     }
1.864     albertel 14587:     
                   14588:     sub reset_hosts_info {
1.897     albertel 14589: 	&purge_remembered();
1.864     albertel 14590: 	&reset_domain_info();
                   14591: 	&reset_hosts_ip_info();
1.1339    raeburn  14592:         undef(%internetdom);
1.892     albertel 14593: 	undef(%name_to_host);
1.864     albertel 14594: 	undef(%hostname);
                   14595: 	undef(%hostdom);
                   14596: 	undef(%libserv);
                   14597: 	undef($loaded);
                   14598:     }
1.1       albertel 14599: 
1.852     albertel 14600:     sub load_hosts_tab {
1.1293    raeburn  14601: 	my ($ignore_cache,$nocache) = @_;
                   14602: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  14603: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14604: 	my @config = <$config>;
                   14605: 	&parse_hosts_tab(\@config);
                   14606: 	close($config);
                   14607: 	$loaded=1;
1.1       albertel 14608:     }
1.852     albertel 14609: 
1.838     albertel 14610:     sub hostname {
1.852     albertel 14611: 	&load_hosts_tab() if (!$loaded);
                   14612: 
1.838     albertel 14613: 	my ($lonid) = @_;
                   14614: 	return $hostname{$lonid};
                   14615:     }
1.845     albertel 14616: 
1.838     albertel 14617:     sub all_hostnames {
1.852     albertel 14618: 	&load_hosts_tab() if (!$loaded);
                   14619: 
1.838     albertel 14620: 	return %hostname;
                   14621:     }
1.845     albertel 14622: 
1.888     albertel 14623:     sub all_names {
1.1293    raeburn  14624:         my ($ignore_cache,$nocache) = @_;
                   14625: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14626: 
                   14627: 	return %name_to_host;
                   14628:     }
                   14629: 
1.974     raeburn  14630:     sub all_host_domain {
                   14631:         &load_hosts_tab() if (!$loaded);
                   14632:         return %hostdom;
                   14633:     }
                   14634: 
1.1339    raeburn  14635:     sub all_host_intdom {
                   14636:         &load_hosts_tab() if (!$loaded);
                   14637:         return %internetdom;
                   14638:     }
                   14639: 
1.845     albertel 14640:     sub is_library {
1.852     albertel 14641: 	&load_hosts_tab() if (!$loaded);
                   14642: 
1.845     albertel 14643: 	return exists($libserv{$_[0]});
                   14644:     }
                   14645: 
                   14646:     sub all_library {
1.852     albertel 14647: 	&load_hosts_tab() if (!$loaded);
                   14648: 
1.845     albertel 14649: 	return %libserv;
                   14650:     }
                   14651: 
1.1062    droeschl 14652:     sub unique_library {
                   14653: 	#2x reverse removes all hostnames that appear more than once
                   14654:         my %unique = reverse &all_library();
                   14655:         return reverse %unique;
                   14656:     }
                   14657: 
1.841     albertel 14658:     sub get_servers {
1.852     albertel 14659: 	&load_hosts_tab() if (!$loaded);
                   14660: 
1.841     albertel 14661: 	my ($domain,$type) = @_;
                   14662: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14663: 	                                          : %hostname;
                   14664: 	my %result;
1.842     albertel 14665: 	if (ref($domain) eq 'ARRAY') {
                   14666: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14667: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14668: 		    $result{$host} = $hostname;
                   14669: 		}
                   14670: 	    }
                   14671: 	} else {
                   14672: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14673: 		if ($hostdom{$host} eq $domain) {
                   14674: 		    $result{$host} = $hostname;
                   14675: 		}
1.841     albertel 14676: 	    }
                   14677: 	}
                   14678: 	return %result;
                   14679:     }
1.845     albertel 14680: 
1.1062    droeschl 14681:     sub get_unique_servers {
                   14682:         my %unique = reverse &get_servers(@_);
                   14683: 	return reverse %unique;
                   14684:     }
                   14685: 
1.844     albertel 14686:     sub host_domain {
1.852     albertel 14687: 	&load_hosts_tab() if (!$loaded);
                   14688: 
1.844     albertel 14689: 	my ($lonid) = @_;
                   14690: 	return $hostdom{$lonid};
                   14691:     }
                   14692: 
1.841     albertel 14693:     sub all_domains {
1.852     albertel 14694: 	&load_hosts_tab() if (!$loaded);
                   14695: 
1.841     albertel 14696: 	my %seen;
                   14697: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14698: 	return @uniq;
                   14699:     }
1.1074    raeburn  14700: 
                   14701:     sub internet_dom {
                   14702:         &load_hosts_tab() if (!$loaded);
                   14703: 
                   14704:         my ($lonid) = @_;
                   14705:         return $internetdom{$lonid};
                   14706:     }
1.1107    raeburn  14707: 
                   14708:     sub is_LC_dns {
                   14709:         &load_hosts_tab() if (!$loaded);
                   14710: 
                   14711:         my ($hostname) = @_;
                   14712:         return exists($LC_dns_serv{$hostname});
                   14713:     }
                   14714: 
1.1       albertel 14715: }
                   14716: 
1.847     albertel 14717: { 
                   14718:     my %iphost;
1.856     albertel 14719:     my %name_to_ip;
                   14720:     my %lonid_to_ip;
1.869     albertel 14721: 
1.847     albertel 14722:     sub get_hosts_from_ip {
                   14723: 	my ($ip) = @_;
                   14724: 	my %iphosts = &get_iphost();
                   14725: 	if (ref($iphosts{$ip})) {
                   14726: 	    return @{$iphosts{$ip}};
                   14727: 	}
                   14728: 	return;
1.839     albertel 14729:     }
1.864     albertel 14730:     
                   14731:     sub reset_hosts_ip_info {
                   14732: 	undef(%iphost);
                   14733: 	undef(%name_to_ip);
                   14734: 	undef(%lonid_to_ip);
                   14735:     }
1.856     albertel 14736: 
                   14737:     sub get_host_ip {
                   14738: 	my ($lonid) = @_;
                   14739: 	if (exists($lonid_to_ip{$lonid})) {
                   14740: 	    return $lonid_to_ip{$lonid};
                   14741: 	}
                   14742: 	my $name=&hostname($lonid);
                   14743:    	my $ip = gethostbyname($name);
                   14744: 	return if (!$ip || length($ip) ne 4);
                   14745: 	$ip=inet_ntoa($ip);
                   14746: 	$name_to_ip{$name}   = $ip;
                   14747: 	$lonid_to_ip{$lonid} = $ip;
                   14748: 	return $ip;
                   14749:     }
1.847     albertel 14750:     
                   14751:     sub get_iphost {
1.1293    raeburn  14752: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14753: 
1.869     albertel 14754: 	if (!$ignore_cache) {
                   14755: 	    if (%iphost) {
                   14756: 		return %iphost;
                   14757: 	    }
                   14758: 	    my ($ip_info,$cached)=
                   14759: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14760: 	    if ($cached) {
                   14761: 		%iphost      = %{$ip_info->[0]};
                   14762: 		%name_to_ip  = %{$ip_info->[1]};
                   14763: 		%lonid_to_ip = %{$ip_info->[2]};
                   14764: 		return %iphost;
                   14765: 	    }
                   14766: 	}
1.894     albertel 14767: 
                   14768: 	# get yesterday's info for fallback
                   14769: 	my %old_name_to_ip;
                   14770: 	my ($ip_info,$cached)=
                   14771: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14772: 	if ($cached) {
                   14773: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14774: 	}
                   14775: 
1.1293    raeburn  14776: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14777: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14778: 	    my $ip;
                   14779: 	    if (!exists($name_to_ip{$name})) {
                   14780: 		$ip = gethostbyname($name);
                   14781: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14782: 		    if (defined($old_name_to_ip{$name})) {
                   14783: 			$ip = $old_name_to_ip{$name};
                   14784: 			&logthis("Can't find $name defaulting to old $ip");
                   14785: 		    } else {
                   14786: 			&logthis("Name $name no IP found");
                   14787: 			next;
                   14788: 		    }
                   14789: 		} else {
                   14790: 		    $ip=inet_ntoa($ip);
1.847     albertel 14791: 		}
                   14792: 		$name_to_ip{$name} = $ip;
                   14793: 	    } else {
                   14794: 		$ip = $name_to_ip{$name};
1.653     albertel 14795: 	    }
1.888     albertel 14796: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14797: 		$lonid_to_ip{$id} = $ip;
                   14798: 	    }
                   14799: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14800: 	}
1.1293    raeburn  14801:         unless ($nocache) {
                   14802: 	    &do_cache_new('iphost','iphost',
                   14803: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14804: 		          48*60*60);
                   14805:         }
1.869     albertel 14806: 
1.847     albertel 14807: 	return %iphost;
1.598     albertel 14808:     }
                   14809: 
1.992     raeburn  14810:     #
                   14811:     #  Given a DNS returns the loncapa host name for that DNS 
                   14812:     # 
                   14813:     sub host_from_dns {
                   14814:         my ($dns) = @_;
                   14815:         my @hosts;
                   14816:         my $ip;
                   14817: 
1.993     raeburn  14818:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14819:             $ip = $name_to_ip{$dns};
                   14820:         }
                   14821:         if (!$ip) {
                   14822:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14823:             if (length($ip) == 4) { 
                   14824: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14825:             }
                   14826:         }
                   14827:         if ($ip) {
                   14828: 	    @hosts = get_hosts_from_ip($ip);
                   14829: 	    return $hosts[0];
                   14830:         }
                   14831:         return undef;
1.986     foxr     14832:     }
1.992     raeburn  14833: 
1.1074    raeburn  14834:     sub get_internet_names {
                   14835:         my ($lonid) = @_;
                   14836:         return if ($lonid eq '');
                   14837:         my ($idnref,$cached)=
                   14838:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14839:         if ($cached) {
                   14840:             return $idnref;
                   14841:         }
                   14842:         my $ip = &get_host_ip($lonid);
                   14843:         my @hosts = &get_hosts_from_ip($ip);
                   14844:         my %iphost = &get_iphost();
                   14845:         my (@idns,%seen);
                   14846:         foreach my $id (@hosts) {
                   14847:             my $dom = &host_domain($id);
                   14848:             my $prim_id = &domain($dom,'primary');
                   14849:             my $prim_ip = &get_host_ip($prim_id);
                   14850:             next if ($seen{$prim_ip});
                   14851:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14852:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14853:                     my $intdom = &internet_dom($id);
                   14854:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14855:                         push(@idns,$intdom);
                   14856:                     }
                   14857:                 }
                   14858:             }
                   14859:             $seen{$prim_ip} = 1;
                   14860:         }
1.1219    raeburn  14861:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14862:     }
                   14863: 
1.986     foxr     14864: }
                   14865: 
1.1079    raeburn  14866: sub all_loncaparevs {
1.1249    raeburn  14867:     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  14868: }
                   14869: 
1.1227    raeburn  14870: # ---------------------------------------------------------- Read loncaparev table
                   14871: {
                   14872:     sub load_loncaparevs { 
                   14873:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14874:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14875:                 while (my $configline=<$config>) {
                   14876:                     chomp($configline);
                   14877:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14878:                     $loncaparevs{$hostid}=$loncaparev;
                   14879:                 }
                   14880:                 close($config);
                   14881:             }
                   14882:         }
                   14883:     }
                   14884: }
                   14885: 
                   14886: # ---------------------------------------------------------- Read serverhostID table
                   14887: {
                   14888:     sub load_serverhomeIDs {
                   14889:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14890:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14891:                 while (my $configline=<$config>) {
                   14892:                     chomp($configline);
                   14893:                     my ($name,$id)=split(/:/,$configline);
                   14894:                     $serverhomeIDs{$name}=$id;
                   14895:                 }
                   14896:                 close($config);
                   14897:             }
                   14898:         }
                   14899:     }
                   14900: }
                   14901: 
                   14902: 
1.862     albertel 14903: BEGIN {
                   14904: 
                   14905: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14906:     unless ($readit) {
                   14907: {
                   14908:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14909:     %perlvar = (%perlvar,%{$configvars});
                   14910: }
                   14911: 
                   14912: 
1.1       albertel 14913: # ------------------------------------------------------ Read spare server file
                   14914: {
1.1359    raeburn  14915:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14916: 
                   14917:     while (my $configline=<$config>) {
                   14918:        chomp($configline);
1.284     matthew  14919:        if ($configline) {
1.784     albertel 14920: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14921: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14922: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14923:        }
                   14924:     }
1.448     albertel 14925:     close($config);
1.1       albertel 14926: }
1.11      www      14927: # ------------------------------------------------------------ Read permissions
                   14928: {
1.1359    raeburn  14929:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14930: 
                   14931:     while (my $configline=<$config>) {
1.448     albertel 14932: 	chomp($configline);
                   14933: 	if ($configline) {
                   14934: 	    my ($role,$perm)=split(/ /,$configline);
                   14935: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14936: 	}
1.11      www      14937:     }
1.448     albertel 14938:     close($config);
1.11      www      14939: }
                   14940: 
                   14941: # -------------------------------------------- Read plain texts for permissions
                   14942: {
1.1359    raeburn  14943:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14944: 
                   14945:     while (my $configline=<$config>) {
1.448     albertel 14946: 	chomp($configline);
                   14947: 	if ($configline) {
1.742     raeburn  14948: 	    my ($short,@plain)=split(/:/,$configline);
                   14949:             %{$prp{$short}} = ();
                   14950: 	    if (@plain > 0) {
                   14951:                 $prp{$short}{'std'} = $plain[0];
                   14952:                 for (my $i=1; $i<@plain; $i++) {
                   14953:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14954:                 }
                   14955:             }
1.448     albertel 14956: 	}
1.135     www      14957:     }
1.448     albertel 14958:     close($config);
1.135     www      14959: }
                   14960: 
                   14961: # ---------------------------------------------------------- Read package table
                   14962: {
1.1359    raeburn  14963:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14964: 
                   14965:     while (my $configline=<$config>) {
1.483     albertel 14966: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14967: 	chomp($configline);
                   14968: 	my ($short,$plain)=split(/:/,$configline);
                   14969: 	my ($pack,$name)=split(/\&/,$short);
                   14970: 	if ($plain ne '') {
                   14971: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14972: 	    $packagetab{$short}=$plain; 
                   14973: 	}
1.11      www      14974:     }
1.448     albertel 14975:     close($config);
1.329     matthew  14976: }
                   14977: 
1.1073    raeburn  14978: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14979: 
                   14980: &load_loncaparevs();
1.1073    raeburn  14981: 
1.1074    raeburn  14982: # ---------------------------------------------------------- Read serverhostID table
                   14983: 
1.1227    raeburn  14984: &load_serverhomeIDs();
                   14985: 
                   14986: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14987: {
                   14988:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14989:     if (-e $file) {
                   14990:         my $parser = HTML::LCParser->new($file);
                   14991:         while (my $token = $parser->get_token()) {
                   14992:             if ($token->[0] eq 'S') {
                   14993:                 my $item = $token->[1];
                   14994:                 my $name = $token->[2]{'name'};
                   14995:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14996:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14997:                 my $namematch = $token->[2]{'namematch'};
                   14998:                 if ($item eq 'parameter') {
                   14999:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   15000:                         my $release = $parser->get_text();
                   15001:                         $release =~ s/(^\s*|\s*$ )//gx;
                   15002:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   15003:                     }
                   15004:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  15005:                     my $release = $parser->get_text();
                   15006:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  15007:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  15008:                 }
                   15009:             }
                   15010:         }
                   15011:     }
1.1073    raeburn  15012: }
                   15013: 
1.1138    raeburn  15014: # ---------------------------------------------------------- Read managers table
                   15015: {
                   15016:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  15017:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15018:             while (my $configline=<$config>) {
                   15019:                 chomp($configline);
                   15020:                 next if ($configline =~ /^\#/);
                   15021:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15022:                     $managerstab{$configline} = 1;
                   15023:                 }
                   15024:             }
                   15025:             close($config);
                   15026:         }
                   15027:     }
                   15028: }
                   15029: 
1.329     matthew  15030: # ------------- set up temporary directory
                   15031: {
1.1117    foxr     15032:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15033: 
1.11      www      15034: }
                   15035: 
1.1405    raeburn  15036: # ------------- set default texengine (domain default overrides this)
                   15037: {
                   15038:     $deftex = LONCAPA::texengine();
                   15039: }
                   15040: 
1.1416    raeburn  15041: # ------------- set default minimum length for passwords for internal auth users
                   15042: {
                   15043:     $passwdmin = LONCAPA::passwd_min();
                   15044: }
                   15045: 
1.794     albertel 15046: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15047: 				'compress_threshold'=> 20_000,
                   15048:  			        });
1.185     www      15049: 
1.281     www      15050: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15051: $dumpcount=0;
1.958     www      15052: $locknum=0;
1.22      www      15053: 
1.163     harris41 15054: &logtouch();
1.672     albertel 15055: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15056: $readit=1;
1.564     albertel 15057:     {
                   15058: 	use integer;
                   15059: 	my $test=(2**32)+1;
1.568     albertel 15060: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15061: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15062:     }
1.195     www      15063: }
1.1       albertel 15064: }
1.179     www      15065: 
1.1       albertel 15066: 1;
1.191     harris41 15067: __END__
                   15068: 
1.243     albertel 15069: =pod
                   15070: 
1.191     harris41 15071: =head1 NAME
                   15072: 
1.243     albertel 15073: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15074: 
                   15075: =head1 SYNOPSIS
                   15076: 
1.243     albertel 15077: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15078: 
                   15079:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15080: 
1.243     albertel 15081: Common parameters:
                   15082: 
                   15083: =over 4
                   15084: 
                   15085: =item *
                   15086: 
                   15087: $uname : an internal username (if $cname expecting a course Id specifically)
                   15088: 
                   15089: =item *
                   15090: 
                   15091: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15092: 
                   15093: =item *
                   15094: 
                   15095: $symb : a resource instance identifier
                   15096: 
                   15097: =item *
                   15098: 
                   15099: $namespace : the name of a .db file that contains the data needed or
                   15100: being set.
                   15101: 
                   15102: =back
                   15103: 
1.394     bowersj2 15104: =head1 OVERVIEW
1.191     harris41 15105: 
1.394     bowersj2 15106: lonnet provides subroutines which interact with the
                   15107: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15108: about classes, users, and resources.
1.243     albertel 15109: 
                   15110: For many of these objects you can also use this to store data about
                   15111: them or modify them in various ways.
1.191     harris41 15112: 
1.394     bowersj2 15113: =head2 Symbs
1.191     harris41 15114: 
1.394     bowersj2 15115: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15116: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15117: map, the resource number of the resource in the map, and the URL of
                   15118: the resource itself. The latter is somewhat redundant, but might help
                   15119: if maps change.
                   15120: 
                   15121: An example is
                   15122: 
                   15123:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15124: 
                   15125: The respective map entry is
                   15126: 
                   15127:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15128:   title="Problem 2">
                   15129:  </resource>
                   15130: 
                   15131: Symbs are used by the random number generator, as well as to store and
                   15132: restore data specific to a certain instance of for example a problem.
                   15133: 
                   15134: =head2 Storing And Retrieving Data
                   15135: 
                   15136: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15137: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15138: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15139: is is the non-critical message twin of cstore. These functions are for
                   15140: handlers to store a perl hash to a user's permanent data space in an
                   15141: easy manner, and to retrieve it again on another call. It is expected
                   15142: that a handler would use this once at the beginning to retrieve data,
                   15143: and then again once at the end to send only the new data back.
                   15144: 
                   15145: The data is stored in the user's data directory on the user's
                   15146: homeserver under the ID of the course.
                   15147: 
                   15148: The hash that is returned by restore will have all of the previous
                   15149: value for all of the elements of the hash.
                   15150: 
                   15151: Example:
                   15152: 
                   15153:  #creating a hash
                   15154:  my %hash;
                   15155:  $hash{'foo'}='bar';
                   15156: 
                   15157:  #storing it
                   15158:  &Apache::lonnet::cstore(\%hash);
                   15159: 
                   15160:  #changing a value
                   15161:  $hash{'foo'}='notbar';
                   15162: 
                   15163:  #adding a new value
                   15164:  $hash{'bar'}='foo';
                   15165:  &Apache::lonnet::cstore(\%hash);
                   15166: 
                   15167:  #retrieving the hash
                   15168:  my %history=&Apache::lonnet::restore();
                   15169: 
                   15170:  #print the hash
                   15171:  foreach my $key (sort(keys(%history))) {
                   15172:    print("\%history{$key} = $history{$key}");
                   15173:  }
                   15174: 
                   15175: Will print out:
1.191     harris41 15176: 
1.394     bowersj2 15177:  %history{1:foo} = bar
                   15178:  %history{1:keys} = foo:timestamp
                   15179:  %history{1:timestamp} = 990455579
                   15180:  %history{2:bar} = foo
                   15181:  %history{2:foo} = notbar
                   15182:  %history{2:keys} = foo:bar:timestamp
                   15183:  %history{2:timestamp} = 990455580
                   15184:  %history{bar} = foo
                   15185:  %history{foo} = notbar
                   15186:  %history{timestamp} = 990455580
                   15187:  %history{version} = 2
                   15188: 
                   15189: Note that the special hash entries C<keys>, C<version> and
                   15190: C<timestamp> were added to the hash. C<version> will be equal to the
                   15191: total number of versions of the data that have been stored. The
                   15192: C<timestamp> attribute will be the UNIX time the hash was
                   15193: stored. C<keys> is available in every historical section to list which
                   15194: keys were added or changed at a specific historical revision of a
                   15195: hash.
                   15196: 
                   15197: B<Warning>: do not store the hash that restore returns directly. This
                   15198: will cause a mess since it will restore the historical keys as if the
                   15199: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15200: 
1.394     bowersj2 15201: Calling convention:
1.191     harris41 15202: 
1.1225    raeburn  15203:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15204:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15205: 
1.394     bowersj2 15206: For more detailed information, see lonnet specific documentation.
1.191     harris41 15207: 
1.394     bowersj2 15208: =head1 RETURN MESSAGES
1.191     harris41 15209: 
1.394     bowersj2 15210: =over 4
1.191     harris41 15211: 
1.394     bowersj2 15212: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15213: 
1.394     bowersj2 15214: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15215: when the connection is brought back up
1.191     harris41 15216: 
1.394     bowersj2 15217: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15218: for later delivery
1.191     harris41 15219: 
1.967     bisitz   15220: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15221: 
1.394     bowersj2 15222: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15223: that was requested
1.191     harris41 15224: 
1.243     albertel 15225: =back
1.191     harris41 15226: 
1.243     albertel 15227: =head1 PUBLIC SUBROUTINES
1.191     harris41 15228: 
1.243     albertel 15229: =head2 Session Environment Functions
1.191     harris41 15230: 
1.243     albertel 15231: =over 4
1.191     harris41 15232: 
1.394     bowersj2 15233: =item * 
                   15234: X<appenv()>
1.949     raeburn  15235: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15236: the user envirnoment file, and will be restored for each access this
1.620     albertel 15237: user makes during this session, also modifies the %env for the current
1.949     raeburn  15238: process. Optional rolesarrayref - if defined contains a reference to an array
                   15239: of roles which are exempt from the restriction on modifying user.role entries 
                   15240: in the user's environment.db and in %env.    
1.191     harris41 15241: 
                   15242: =item *
1.394     bowersj2 15243: X<delenv()>
1.987     raeburn  15244: B<delenv($delthis,$regexp)>: removes all items from the session
                   15245: environment file that begin with $delthis. If the 
                   15246: optional second arg - $regexp - is true, $delthis is treated as a 
                   15247: regular expression, otherwise \Q$delthis\E is used. 
                   15248: The values are also deleted from the current processes %env.
1.191     harris41 15249: 
1.795     albertel 15250: =item * get_env_multiple($name) 
                   15251: 
                   15252: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15253: values may be defined and end up as an array ref.
                   15254: 
                   15255: returns an array of values
                   15256: 
1.243     albertel 15257: =back
                   15258: 
                   15259: =head2 User Information
1.191     harris41 15260: 
1.243     albertel 15261: =over 4
1.191     harris41 15262: 
                   15263: =item *
1.394     bowersj2 15264: X<queryauthenticate()>
                   15265: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15266: authentication scheme
                   15267: 
                   15268: =item *
1.394     bowersj2 15269: X<authenticate()>
1.1073    raeburn  15270: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15271: authenticate user from domain's lib servers (first use the current
                   15272: one). C<$upass> should be the users password.
1.1073    raeburn  15273: $checkdefauth is optional (value is 1 if a check should be made to
                   15274:    authenticate user using default authentication method, and allow
                   15275:    account creation if username does not have account in the domain).
                   15276: $clientcancheckhost is optional (value is 1 if checking whether the
                   15277:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15278: 
                   15279: =item *
1.394     bowersj2 15280: X<homeserver()>
                   15281: B<homeserver($uname,$udom)>: find the server which has
                   15282: the user's directory and files (there must be only one), this caches
                   15283: the answer, and also caches if there is a borken connection.
1.191     harris41 15284: 
                   15285: =item *
1.394     bowersj2 15286: X<idget()>
1.1300    raeburn  15287: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   15288: a list of student/employee IDs or clicker IDs
                   15289: (student/employee IDs are a unique resource in a domain, there must be 
                   15290: only 1 ID per username, and only 1 username per ID in a specific domain).
                   15291: clickerIDs are not necessarily unique, as students might share clickers.
                   15292: (returns hash: id=>name,id=>name)
1.191     harris41 15293: 
                   15294: =item *
1.394     bowersj2 15295: X<idrget()>
                   15296: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15297: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15298: 
                   15299: =item *
1.394     bowersj2 15300: X<idput()>
1.1300    raeburn  15301: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   15302: names and associated student/employee IDs or clicker IDs.
                   15303: 
                   15304: =item *
                   15305: X<iddel()>
                   15306: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15307: student/employee ID or clicker ID username look-ups from domain.
                   15308: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15309: If no $uhome is provided, it will be determined usig &homeserver()
                   15310: for each user.  If no $namespace is provided, the default is ids.
                   15311: 
                   15312: =item *
                   15313: X<updateclickers()>
                   15314: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15315: clicker ID-to-username look-ups in clickers.db on library server.
                   15316: Permitted actions are add or del (i.e., add or delete). The 
                   15317: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15318: value is an escaped comma-separated list of usernames (for whom the
                   15319: library server is the homeserver), who registered that particular ID.
                   15320: If $critical is true, the update will be sent via &critical, otherwise
                   15321: &reply() will be used.
1.191     harris41 15322: 
                   15323: =item *
1.394     bowersj2 15324: X<rolesinit()>
1.1169    droeschl 15325: B<rolesinit($udom,$username)>: get user privileges.
                   15326: returns user role, first access and timer interval hashes
1.243     albertel 15327: 
                   15328: =item *
1.1171    droeschl 15329: X<privileged()>
                   15330: B<privileged($username,$domain)>: returns a true if user has a
                   15331: privileged and active role (i.e. su or dc), false otherwise.
                   15332: 
                   15333: =item *
1.551     albertel 15334: X<getsection()>
                   15335: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15336: course $cname, return section name/number or '' for "not in course"
                   15337: and '-1' for "no section"
                   15338: 
                   15339: =item *
1.394     bowersj2 15340: X<userenvironment()>
                   15341: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15342: passed in @what from the requested user's environment, returns a hash
                   15343: 
1.858     raeburn  15344: =item * 
                   15345: X<userlog_query()>
1.859     albertel 15346: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15347: activity.log file. %filters defines filters applied when parsing the
                   15348: log file. These can be start or end timestamps, or the type of action
                   15349: - log to look for Login or Logout events, check for Checkin or
                   15350: Checkout, role for role selection. The response is in the form
                   15351: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15352: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15353: 
1.243     albertel 15354: =back
                   15355: 
                   15356: =head2 User Roles
                   15357: 
                   15358: =over 4
                   15359: 
                   15360: =item *
                   15361: 
1.1284    raeburn  15362: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15363: returns codes for allowed actions.
                   15364: 
                   15365: The first argument is required, all others are optional.
                   15366: 
                   15367: $priv is the privilege being checked.
                   15368: $uri contains additional information about what is being checked for access (e.g.,
                   15369: URL, course ID etc.). 
                   15370: $symb is the unique resource instance identifier in a course; if needed,
                   15371: but not provided, it will be retrieved via a call to &symbread(). 
                   15372: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15373: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15374: files).
                   15375: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15376: prevents recursive calls to &allowed.
                   15377: 
1.243     albertel 15378:  F: full access
                   15379:  U,I,K: authentication modes (cxx only)
                   15380:  '': forbidden
                   15381:  1: user needs to choose course
                   15382:  2: browse allowed
1.766     albertel 15383:  A: passphrase authentication needed
1.1284    raeburn  15384:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  15385:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15386: 
                   15387: =item *
                   15388: 
1.1192    raeburn  15389: constructaccess($url,$setpriv) : check for access to construction space URL
                   15390: 
                   15391: See if the owner domain and name in the URL match those in the
                   15392: expected environment.  If so, return three element list
                   15393: ($ownername,$ownerdomain,$ownerhome).
                   15394: 
                   15395: Otherwise return the null string.
                   15396: 
                   15397: If second argument 'setpriv' is true, it assigns the privileges,
                   15398: and returns the same three element list, unless the owner has
                   15399: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15400: in which case the null string is returned.
                   15401: 
                   15402: =item *
                   15403: 
1.1326    raeburn  15404: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15405: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15406: for system, domain, and course level. $uname and $udom are optional (current
                   15407: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15408: 
                   15409: =item *
                   15410: 
1.988     raeburn  15411: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15412: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15413: $type is Course (default) or Community.
1.988     raeburn  15414: If $forcedefault evaluates to true, text returned will be default 
                   15415: text for $type. Otherwise, if this is a course, the text returned 
                   15416: will be a custom name for the role (if defined in the course's 
                   15417: environment).  If no custom name is defined the default is returned.
                   15418:    
1.832     raeburn  15419: =item *
                   15420: 
1.1219    raeburn  15421: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15422: All arguments are optional. Returns a hash of a roles, either for
                   15423: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15424: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15425: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15426: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15427: For each key, value is set to colon-separated start and end times for
                   15428: the role.  If no username and domain are specified, will default to
1.934     raeburn  15429: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15430: of role statuses (active, future or previous), roles 
                   15431: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15432: to restrict the list of roles reported. If no array ref is 
                   15433: provided for types, will default to return only active roles.
1.834     albertel 15434: 
1.1195    raeburn  15435: =item *
                   15436: 
                   15437: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  15438: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   15439: 
                   15440: Additional optional arguments are: $type (if role checking is to be restricted 
                   15441: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  15442: available roles) or future (roles available in the future), and
                   15443: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  15444: have active Domain Coordinator role in course's domain or in additional
                   15445: domains (specified in 'Domains to check for privileged users' in course
                   15446: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15447: 
                   15448: =item *
                   15449: 
                   15450: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15451: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15452: $possdomains and $possroles are optional array refs -- to domains to check and
                   15453: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15454: users' roles.db to check for a dc or su role in any domain. This can be
                   15455: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15456: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15457: this then allows &privileged_by_domain() to be used, which caches the identity
                   15458: of privileged users, eliminating the need for repeated calls to &dump().
                   15459: 
                   15460: =item *
                   15461: 
                   15462: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15463: where the outer hash keys are domains specified in the $possdomains array ref,
                   15464: next inner hash keys are privileged roles specified in the $roles array ref,
                   15465: and the innermost hash contains key = value pairs for username:domain = end:start
                   15466: for active or future "privileged" users with that role in that domain. To avoid
                   15467: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15468: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  15469: 
1.243     albertel 15470: =back
                   15471: 
                   15472: =head2 User Modification
                   15473: 
                   15474: =over 4
                   15475: 
                   15476: =item *
                   15477: 
1.957     raeburn  15478: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15479: user for the level given by URL.  Optional start and end dates (leave empty
                   15480: string or zero for "no date")
1.191     harris41 15481: 
                   15482: =item *
                   15483: 
1.243     albertel 15484: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15485: change a users, password, possible return values are: ok,
                   15486: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15487: refused
1.191     harris41 15488: 
                   15489: =item *
                   15490: 
1.243     albertel 15491: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15492: 
                   15493: =item *
                   15494: 
1.1058    raeburn  15495: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15496:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15497: 
                   15498: will update user information (firstname,middlename,lastname,generation,
                   15499: permanentemail), and if forceid is true, student/employee ID also.
                   15500: A user's institutional affiliation(s) can also be updated.
                   15501: User information fields will not be overwritten with empty entries 
                   15502: unless the field is included in the $candelete array reference.
                   15503: This array is included when a single user is modified via "Manage Users",
                   15504: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15505: 
                   15506: =item *
                   15507: 
1.286     matthew  15508: modifystudent
                   15509: 
1.957     raeburn  15510: modify a student's enrollment and identification information.
1.1235    raeburn  15511: The course id is resolved based on the current user's environment.  
                   15512: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15513: associated with a course.
                   15514: 
1.297     matthew  15515: This call is essentially a wrapper for lonnet::modifyuser and
                   15516: lonnet::modify_student_enrollment
1.286     matthew  15517: 
                   15518: Inputs: 
                   15519: 
                   15520: =over 4
                   15521: 
1.957     raeburn  15522: =item B<$udom> Student's loncapa domain
1.286     matthew  15523: 
1.957     raeburn  15524: =item B<$uname> Student's loncapa login name
1.286     matthew  15525: 
1.964     bisitz   15526: =item B<$uid> Student/Employee ID
1.286     matthew  15527: 
1.957     raeburn  15528: =item B<$umode> Student's authentication mode
1.286     matthew  15529: 
1.957     raeburn  15530: =item B<$upass> Student's password
1.286     matthew  15531: 
1.957     raeburn  15532: =item B<$first> Student's first name
1.286     matthew  15533: 
1.957     raeburn  15534: =item B<$middle> Student's middle name
1.286     matthew  15535: 
1.957     raeburn  15536: =item B<$last> Student's last name
1.286     matthew  15537: 
1.957     raeburn  15538: =item B<$gene> Student's generation
1.286     matthew  15539: 
1.957     raeburn  15540: =item B<$usec> Student's section in course
1.286     matthew  15541: 
                   15542: =item B<$end> Unix time of the roles expiration
                   15543: 
                   15544: =item B<$start> Unix time of the roles start date
                   15545: 
                   15546: =item B<$forceid> If defined, allow $uid to be changed
                   15547: 
                   15548: =item B<$desiredhome> server to use as home server for student
                   15549: 
1.957     raeburn  15550: =item B<$email> Student's permanent e-mail address
                   15551: 
                   15552: =item B<$type> Type of enrollment (auto or manual)
                   15553: 
1.963     raeburn  15554: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15555: 
                   15556: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15557: 
1.963     raeburn  15558: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15559: 
1.963     raeburn  15560: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15561: 
1.1216    raeburn  15562: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15563: 
                   15564: =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  15565: 
1.286     matthew  15566: =back
1.297     matthew  15567: 
                   15568: =item *
                   15569: 
                   15570: modify_student_enrollment
                   15571: 
1.1235    raeburn  15572: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15573: 'role.request.course' must be defined for this function to proceed.
                   15574: 
                   15575: Inputs:
                   15576: 
                   15577: =over 4
                   15578: 
1.1235    raeburn  15579: =item $udom, student's domain
1.297     matthew  15580: 
1.1235    raeburn  15581: =item $uname, student's name
1.297     matthew  15582: 
1.1235    raeburn  15583: =item $uid, student's user id
1.297     matthew  15584: 
1.1235    raeburn  15585: =item $first, student's first name
1.297     matthew  15586: 
                   15587: =item $middle
                   15588: 
                   15589: =item $last
                   15590: 
                   15591: =item $gene
                   15592: 
                   15593: =item $usec
                   15594: 
                   15595: =item $end
                   15596: 
                   15597: =item $start
                   15598: 
1.957     raeburn  15599: =item $type
                   15600: 
                   15601: =item $locktype
                   15602: 
                   15603: =item $cid
                   15604: 
                   15605: =item $selfenroll
                   15606: 
                   15607: =item $context
                   15608: 
1.1216    raeburn  15609: =item $credits, number of credits student will earn from this class
                   15610: 
1.1314    raeburn  15611: =item $instsec, institutional course section code for student
                   15612: 
1.297     matthew  15613: =back
                   15614: 
1.191     harris41 15615: 
                   15616: =item *
                   15617: 
1.243     albertel 15618: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15619: custom role; give a custom role to a user for the level given by URL.  Specify
                   15620: name and domain of role author, and role name
1.191     harris41 15621: 
                   15622: =item *
                   15623: 
1.243     albertel 15624: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15625: 
                   15626: =item *
                   15627: 
1.243     albertel 15628: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15629: 
                   15630: =back
                   15631: 
                   15632: =head2 Course Infomation
                   15633: 
                   15634: =over 4
1.191     harris41 15635: 
                   15636: =item *
                   15637: 
1.1118    foxr     15638: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15639: specified course id, including all environment settings for the
                   15640: course, the description of the course will be in the hash under the
                   15641: key 'description'
1.191     harris41 15642: 
1.1118    foxr     15643: $options is an optional parameter that if supplied is a hash reference that controls
                   15644: what how this function works.  It has the following key/values:
                   15645: 
                   15646: =over 4
                   15647: 
                   15648: =item freshen_cache
                   15649: 
                   15650: If defined, and the environment cache for the course is valid, it is 
                   15651: returned in the returned hash.
                   15652: 
                   15653: =item one_time
                   15654: 
                   15655: If defined, the last cache time is set to _now_
                   15656: 
                   15657: =item user
                   15658: 
                   15659: If defined, the supplied username is used instead of the current user.
                   15660: 
                   15661: 
                   15662: =back
                   15663: 
1.191     harris41 15664: =item *
                   15665: 
1.624     albertel 15666: resdata($name,$domain,$type,@which) : request for current parameter
                   15667: setting for a specific $type, where $type is either 'course' or 'user',
                   15668: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15669: answers for 10 minutes.
1.243     albertel 15670: 
1.877     foxr     15671: =item *
                   15672: 
                   15673: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15674: data base, returning a hash that is keyed by the resource name and has
                   15675: values that are the resource value.  I believe that the timestamps and
                   15676: versions are also returned.
                   15677: 
1.1236    raeburn  15678: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15679: supplemental content area. This routine caches the number of files for 
                   15680: 10 minutes.
                   15681: 
1.243     albertel 15682: =back
                   15683: 
                   15684: =head2 Course Modification
                   15685: 
                   15686: =over 4
1.191     harris41 15687: 
                   15688: =item *
                   15689: 
1.243     albertel 15690: writecoursepref($courseid,%prefs) : write preferences (environment
                   15691: database) for a course
1.191     harris41 15692: 
                   15693: =item *
                   15694: 
1.1011    raeburn  15695: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15696: 
                   15697: =item *
                   15698: 
1.1038    raeburn  15699: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15700: 
1.1167    droeschl 15701: =item *
                   15702: 
                   15703: is_course($courseid), is_course($cdom, $cnum)
                   15704: 
                   15705: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15706: two component version $cdom, $cnum. It checks if the specified course exists.
                   15707: 
                   15708: Returns:
                   15709:     undef if the course doesn't exist, otherwise
                   15710:     in scalar context the combined courseid.
                   15711:     in list context the two components of the course identifier, domain and 
                   15712:     courseid.    
                   15713: 
1.243     albertel 15714: =back
                   15715: 
1.1401    raeburn  15716: =head2 Bubblesheet Configuration
                   15717: 
                   15718: =over 4
                   15719: 
                   15720: =item *
                   15721: 
                   15722: get_scantron_config($which)
                   15723: 
                   15724: $which - the name of the configuration to parse from the file.
                   15725: 
                   15726: Parses and returns the bubblesheet configuration line selected as a
                   15727: hash of configuration file fields.
                   15728: 
                   15729: 
                   15730: Returns:
                   15731:     If the named configuration is not in the file, an empty
                   15732:     hash is returned.
                   15733: 
                   15734:     a hash with the fields
                   15735:       name         - internal name for the this configuration setup
                   15736:       description  - text to display to operator that describes this config
                   15737:       CODElocation - if 0 or the string 'none'
                   15738:                           - no CODE exists for this config
                   15739:                      if -1 || the string 'letter'
                   15740:                           - a CODE exists for this config and is
                   15741:                             a string of letters
                   15742:                      Unsupported value (but planned for future support)
                   15743:                           if a positive integer
                   15744:                                - The CODE exists as the first n items from
                   15745:                                  the question section of the form
                   15746:                           if the string 'number'
                   15747:                                - The CODE exists for this config and is
                   15748:                                  a string of numbers
                   15749:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15750:                      the CODE starts
                   15751:       CODElength  - length of the CODE
                   15752:       IDstart     - column where the student/employee ID starts
                   15753:       IDlength    - length of the student/employee ID info
                   15754:       Qstart      - column where the information from the bubbled
                   15755:                     'questions' start
                   15756:       Qlength     - number of columns comprising a single bubble line from
                   15757:                     the sheet. (usually either 1 or 10)
                   15758:       Qon         - either a single character representing the character used
                   15759:                     to signal a bubble was chosen in the positional setup, or
                   15760:                     the string 'letter' if the letter of the chosen bubble is
                   15761:                     in the final, or 'number' if a number representing the
                   15762:                     chosen bubble is in the file (1->A 0->J)
                   15763:       Qoff        - the character used to represent that a bubble was
                   15764:                     left blank
                   15765:       PaperID     - if the scanning process generates a unique number for each
                   15766:                     sheet scanned the column that this ID number starts in
                   15767:       PaperIDlength - number of columns that comprise the unique ID number
                   15768:                       for the sheet of paper
                   15769:       FirstName   - column that the first name starts in
                   15770:       FirstNameLength - number of columns that the first name spans
                   15771:       LastName    - column that the last name starts in
                   15772:       LastNameLength - number of columns that the last name spans
                   15773:       BubblesPerRow - number of bubbles available in each row used to
                   15774:                       bubble an answer. (If not specified, 10 assumed).
                   15775: 
                   15776: 
                   15777: =item *
                   15778: 
                   15779: get_scantronformat_file($cdom)
                   15780: 
                   15781: $cdom - the course's domain (optional); if not supplied, uses
                   15782: domain for current $env{'request.course.id'}.
                   15783: 
                   15784: Returns an array containing lines from the scantron format file for
                   15785: the domain of the course.
                   15786: 
                   15787: If a url for a custom.tab file is listed in domain's configuration.db,
                   15788: lines are from this file.
                   15789: 
                   15790: Otherwise, if a default.tab has been published in RES space by the
                   15791: domainconfig user, lines are from this file.
                   15792: 
                   15793: Otherwise, fall back to getting lines from the legacy file on the
                   15794: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15795: 
                   15796: =back
                   15797: 
1.243     albertel 15798: =head2 Resource Subroutines
                   15799: 
                   15800: =over 4
1.191     harris41 15801: 
                   15802: =item *
                   15803: 
1.243     albertel 15804: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15805: 
                   15806: =item *
                   15807: 
1.243     albertel 15808: repcopy($filename) : subscribes to the requested file, and attempts to
                   15809: replicate from the owning library server, Might return
1.607     raeburn  15810: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15811: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15812: resource. Expects the local filesystem pathname
                   15813: (/home/httpd/html/res/....)
                   15814: 
                   15815: =back
                   15816: 
                   15817: =head2 Resource Information
                   15818: 
                   15819: =over 4
1.191     harris41 15820: 
                   15821: =item *
                   15822: 
1.1228    raeburn  15823: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15824: and returns the value of a variety of different possible values,
                   15825: $varname should be a request string, and the other parameters can be
                   15826: used to specify who and what one is asking about. Ordinarily, $cid 
                   15827: does not need to be specified, as it is retrived from 
                   15828: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15829: within lonuserstate::loadmap() when initializing a course, before
                   15830: $env{'request.course.id'} has been set, so it needs to be provided
                   15831: in that one case.
1.243     albertel 15832: 
                   15833: Possible values for $varname are environment.lastname (or other item
                   15834: from the envirnment hash), user.name (or someother aspect about the
                   15835: user), resource.0.maxtries (or some other part and parameter of a
                   15836: resource)
1.204     albertel 15837: 
                   15838: =item *
                   15839: 
1.243     albertel 15840: directcondval($number) : get current value of a condition; reads from a state
                   15841: string
1.204     albertel 15842: 
                   15843: =item *
                   15844: 
1.243     albertel 15845: condval($condidx) : value of condition index based on state
1.204     albertel 15846: 
                   15847: =item *
                   15848: 
1.1362    raeburn  15849: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15850: resource's metadata, $what should be either a specific key, or either
                   15851: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15852: packages that this resource currently uses, the last 3 arguments are 
                   15853: only used internally for recursive metadata.
                   15854: 
                   15855: the toolsymb is only used where the uri is for an external tool (for which
                   15856: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15857: 
1.1371    raeburn  15858: this function automatically caches all requests except any made recursively
                   15859: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15860: defined).
1.191     harris41 15861: 
                   15862: =item *
                   15863: 
1.243     albertel 15864: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15865: network of library servers; returns file handle of where SQL and regex results
                   15866: will be stored for query
1.191     harris41 15867: 
                   15868: =item *
                   15869: 
1.1282    raeburn  15870: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15871: return symbolic list entry (all arguments optional). 
                   15872: 
                   15873: Args: filename is the filename (including path) for the file for which a symb 
                   15874: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15875: to check access status if more than one resource was found in the bighash 
                   15876: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15877: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15878: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15879: cause possible symbs to be checked to determine if they are subject to content
                   15880: blocking, if so they will not be included as possible symbs; possibles is a
                   15881: ref to a hash, which, as a side effect, will be populated with all possible 
                   15882: symbs (content blocking not tested).
                   15883:  
1.243     albertel 15884: returns the data handle
1.191     harris41 15885: 
                   15886: =item *
                   15887: 
1.1190    raeburn  15888: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15889: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15890: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15891: on failure, user must be in a course, as it assumes the existence of
                   15892: the course initial hash, and uses $env('request.course.id'}.  The third
                   15893: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15894: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15895: encrypted; otherwise it will be null.  
1.191     harris41 15896: 
                   15897: =item *
                   15898: 
1.243     albertel 15899: symbclean($symb) : removes versions numbers from a symb, returns the
                   15900: cleaned symb
1.191     harris41 15901: 
                   15902: =item *
                   15903: 
1.243     albertel 15904: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15905: course map, user must be in a course for it to work.
1.191     harris41 15906: 
                   15907: =item *
                   15908: 
1.243     albertel 15909: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15910: 
                   15911: =item *
                   15912: 
1.243     albertel 15913: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15914: a random seed, all arguments are optional, if they aren't sent it uses the
                   15915: environment to derive them. Note: if symb isn't sent and it can't get one
                   15916: from &symbread it will use the current time as its return value
1.191     harris41 15917: 
                   15918: =item *
                   15919: 
1.243     albertel 15920: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15921: unfakeable, receipt
1.191     harris41 15922: 
                   15923: =item *
                   15924: 
1.620     albertel 15925: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15926: 
                   15927: =item *
                   15928: 
1.243     albertel 15929: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15930: 
                   15931: =item *
                   15932: 
1.243     albertel 15933: 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 15934: 
                   15935: =item *
                   15936: 
1.243     albertel 15937: 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 15938: 
                   15939: =item *
                   15940: 
1.243     albertel 15941: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15942: 
                   15943: =item *
                   15944: 
1.243     albertel 15945: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15946: forcing spreadsheet to reevaluate the resource scores next time.
                   15947: 
1.1195    raeburn  15948: =item * 
                   15949: 
1.1196    raeburn  15950: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15951: when viewing in course context.
1.1195    raeburn  15952: 
1.1196    raeburn  15953:  input: six args -- filename (decluttered), course number, course domain,
                   15954:                     url, symb (if registered) and group (if this is a 
                   15955:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15956: 
1.1196    raeburn  15957:  output: array of five scalars --
1.1195    raeburn  15958:          $cfile -- url for file editing if editable on current server
                   15959:          $home -- homeserver of resource (i.e., for author if published,
                   15960:                                           or course if uploaded.).
                   15961:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15962:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15963:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15964: 
                   15965: =item *
                   15966: 
                   15967: is_course_upload($file,$cnum,$cdom)
                   15968: 
                   15969: Used in course context to determine if current file was uploaded to 
                   15970: the course (i.e., would be found in /userfiles/docs on the course's 
                   15971: homeserver.
                   15972: 
                   15973:   input: 3 args -- filename (decluttered), course number and course domain.
                   15974:   output: boolean -- 1 if file was uploaded.
                   15975: 
1.243     albertel 15976: =back
                   15977: 
                   15978: =head2 Storing/Retreiving Data
                   15979: 
                   15980: =over 4
1.191     harris41 15981: 
                   15982: =item *
                   15983: 
1.1269    raeburn  15984: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15985: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15986: the remaining args aren't required and if they aren't passed or are '' they will
                   15987: be derived from the env (with the exception of $laststore, which is an 
                   15988: optional arg used when a user's submission is stored in grading).
                   15989: $laststore is $version=$timestamp, where $version is the most recent version
                   15990: number retrieved for the corresponding $symb in the $namespace db file, and
                   15991: $timestamp is the timestamp for that transaction (UNIX time).
                   15992: $laststore is currently only passed when cstore() is called by 
                   15993: structuretags::finalize_storage().
1.191     harris41 15994: 
                   15995: =item *
                   15996: 
1.1269    raeburn  15997: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15998: but uses critical subroutine
1.191     harris41 15999: 
                   16000: =item *
                   16001: 
1.243     albertel 16002: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16003: all args are optional
1.191     harris41 16004: 
                   16005: =item *
                   16006: 
1.717     albertel 16007: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16008: dumps the complete (or key matching regexp) namespace into a hash
                   16009: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16010: normally &store()ed into
                   16011: 
                   16012: $range should be either an integer '100' (give me the first 100
                   16013:                                            matching records)
                   16014:               or be  two integers sperated by a - with no spaces
                   16015:                  '30-50' (give me the 30th through the 50th matching
                   16016:                           records)
                   16017: 
                   16018: 
                   16019: =item *
                   16020: 
1.1269    raeburn  16021: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16022: replaces a &store() version of data with a replacement set of data
                   16023: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  16024: reference. If $tolog is true, the transaction is logged in the courselog
                   16025: with an action=PUTSTORE.
1.717     albertel 16026: 
                   16027: =item *
                   16028: 
1.243     albertel 16029: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16030: works very similar to store/cstore, but all data is stored in a
                   16031: temporary location and can be reset using tmpreset, $storehash should
                   16032: be a hash reference, returns nothing on success
1.191     harris41 16033: 
                   16034: =item *
                   16035: 
1.243     albertel 16036: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16037: similar to restore, but all data is stored in a temporary location and
                   16038: can be reset using tmpreset. Returns a hash of values on success,
                   16039: error string otherwise.
1.191     harris41 16040: 
                   16041: =item *
                   16042: 
1.243     albertel 16043: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16044: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16045: 
                   16046: =item *
                   16047: 
1.243     albertel 16048: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16049: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16050: 
                   16051: =item *
                   16052: 
1.243     albertel 16053: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16054: namesp ($udom and $uname are optional)
1.191     harris41 16055: 
                   16056: =item *
                   16057: 
1.702     albertel 16058: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16059: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16060: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16061: 
1.702     albertel 16062: $range should be either an integer '100' (give me the first 100
                   16063:                                            matching records)
                   16064:               or be  two integers sperated by a - with no spaces
                   16065:                  '30-50' (give me the 30th through the 50th matching
                   16066:                           records)
1.449     matthew  16067: =item *
                   16068: 
                   16069: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16070: $store can be a scalar, an array reference, or if the amount to be 
                   16071: incremented is > 1, a hash reference.
                   16072: 
                   16073: ($udom and $uname are optional)
1.191     harris41 16074: 
                   16075: =item *
                   16076: 
1.243     albertel 16077: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16078: ($udom and $uname are optional)
1.191     harris41 16079: 
                   16080: =item *
                   16081: 
1.243     albertel 16082: cput($namespace,$storehash,$udom,$uname) : critical put
                   16083: ($udom and $uname are optional)
1.191     harris41 16084: 
                   16085: =item *
                   16086: 
1.748     albertel 16087: newput($namespace,$storehash,$udom,$uname) :
                   16088: 
                   16089: Attempts to store the items in the $storehash, but only if they don't
                   16090: currently exist, if this succeeds you can be certain that you have 
                   16091: successfully created a new key value pair in the $namespace db.
                   16092: 
                   16093: 
                   16094: Args:
                   16095:  $namespace: name of database to store values to
                   16096:  $storehash: hashref to store to the db
                   16097:  $udom: (optional) domain of user containing the db
                   16098:  $uname: (optional) name of user caontaining the db
                   16099: 
                   16100: Returns:
                   16101:  'ok' -> succeeded in storing all keys of $storehash
                   16102:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16103:                         least <key> already existed in the db (other
                   16104:                         requested keys may also already exist)
1.967     bisitz   16105:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16106:  'con_lost' -> unable to contact request server
                   16107:  'refused' -> action was not allowed by remote machine
                   16108: 
                   16109: 
                   16110: =item *
                   16111: 
1.243     albertel 16112: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16113: reference filled in from namesp (encrypts the return communication)
                   16114: ($udom and $uname are optional)
1.191     harris41 16115: 
                   16116: =item *
                   16117: 
1.243     albertel 16118: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16119: critical subroutine
                   16120: 
1.806     raeburn  16121: =item *
                   16122: 
1.860     raeburn  16123: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16124: array reference filled in from namespace found in domain level on either
                   16125: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16126: 
                   16127: =item *
                   16128: 
1.860     raeburn  16129: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16130: domain level either on specified domain server ($uhome) or primary domain 
                   16131: server ($udom and $uhome are optional)
1.806     raeburn  16132: 
1.943     raeburn  16133: =item * 
                   16134: 
1.1240    raeburn  16135: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16136: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16137: the target domain.
                   16138: 
                   16139: May also include additional key => value pairs for the following groups:
                   16140: 
                   16141: =over
                   16142: 
                   16143: =item
                   16144: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16145: 
                   16146: =over
                   16147: 
                   16148: =item defaultquota, authorquota
                   16149: 
                   16150: =back
                   16151: 
                   16152: =item
                   16153: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16154: portfolio for users).
                   16155: 
                   16156: =over
                   16157: 
                   16158: =item
                   16159: aboutme, blog, webdav, portfolio
                   16160: 
                   16161: =back
                   16162: 
                   16163: =item
                   16164: requestcourses: ability to request courses, and how requests are processed.
                   16165: 
                   16166: =over
                   16167: 
                   16168: =item
1.1305    raeburn  16169: official, unofficial, community, textbook, placement
1.1240    raeburn  16170: 
                   16171: =back
                   16172: 
                   16173: =item
                   16174: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16175: 
                   16176: =over
                   16177: 
                   16178: =item
1.1256    raeburn  16179: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16180: 
                   16181: =back
                   16182: 
                   16183: =item
                   16184: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16185: for course's uploaded content.
                   16186: 
                   16187: =over
                   16188: 
                   16189: =item
1.1246    raeburn  16190: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16191: communityquota, textbookquota, placementquota
1.1240    raeburn  16192: 
                   16193: =back
                   16194: 
                   16195: =item
                   16196: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16197: on your servers.
                   16198: 
                   16199: =over
                   16200: 
                   16201: =item 
                   16202: remotesessions, hostedsessions
                   16203: 
                   16204: =back
                   16205: 
                   16206: =back
                   16207: 
                   16208: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16209: utility to create a configuration.db file on a domain's primary library server 
                   16210: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16211: -- corresponding values are authentication type (internal, krb4, krb5,
                   16212: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16213: will be available. Values are retrieved from cache (if current), unless the
                   16214: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16215: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16216: 
                   16217: Typical usage:
1.943     raeburn  16218: 
1.1240    raeburn  16219: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16220: 
1.243     albertel 16221: =back
                   16222: 
                   16223: =head2 Network Status Functions
                   16224: 
                   16225: =over 4
1.191     harris41 16226: 
                   16227: =item *
                   16228: 
1.1137    raeburn  16229: dirlist() : return directory list based on URI (first arg).
                   16230: 
                   16231: Inputs: 1 required, 5 optional.
                   16232: 
                   16233: =over
                   16234: 
                   16235: =item 
                   16236: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16237: 
                   16238: =item
                   16239: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16240: 
                   16241: =item
                   16242: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16243: 
                   16244: =item
                   16245: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16246: 
                   16247: =item
                   16248: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16249: 
                   16250: =item 
                   16251: $alternateRoot - path to prepend in place of path from $uri.
                   16252: 
                   16253: =back
                   16254: 
                   16255: Returns: Array of up to two items.
                   16256: 
                   16257: =over
                   16258: 
                   16259: a reference to an array of files/subdirectories
                   16260: 
                   16261: =over
                   16262: 
                   16263: Each element in the array of files/subdirectories is a & separated list of
                   16264: item name and the result of running stat on the item.  If dirlist was requested
                   16265: for a file instead of a directory, the item name will be ''. For a directory 
                   16266: listing, if the item is a metadata file, the element will end &N&M 
                   16267: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16268: default copyright set (1).  
                   16269: 
                   16270: =back
                   16271: 
                   16272: a scalar containing error condition (if encountered).
                   16273: 
                   16274: =over
                   16275: 
                   16276: =item 
                   16277: no_host (no homeserver identified for $username:$domain).
                   16278: 
                   16279: =item 
                   16280: no_such_host (server contacted for listing not identified as valid host).
                   16281: 
                   16282: =item 
                   16283: con_lost (connection to remote server failed).
                   16284: 
                   16285: =item 
                   16286: refused (invalid $username:$domain received on lond side).
                   16287: 
                   16288: =item 
                   16289: no_such_dir (directory at specified path on lond side does not exist). 
                   16290: 
                   16291: =item 
                   16292: empty (directory at specified path on lond side is empty).
                   16293: 
                   16294: =over
                   16295: 
                   16296: This is currently not encountered because the &ls3, &ls2, 
                   16297: &ls (_handler) routines on the lond side do not filter out
                   16298: . and .. from a directory listing. 
                   16299: 
                   16300: =back
                   16301: 
                   16302: =back
                   16303: 
                   16304: =back
1.191     harris41 16305: 
                   16306: =item *
                   16307: 
1.243     albertel 16308: spareserver() : find server with least workload from spare.tab
                   16309: 
1.986     foxr     16310: 
                   16311: =item *
                   16312: 
                   16313: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16314: if there is no corresponding loncapa host.
                   16315: 
1.243     albertel 16316: =back
                   16317: 
1.986     foxr     16318: 
1.243     albertel 16319: =head2 Apache Request
                   16320: 
                   16321: =over 4
1.191     harris41 16322: 
                   16323: =item *
                   16324: 
1.243     albertel 16325: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16326: localhost, posts hash
                   16327: 
                   16328: =back
                   16329: 
                   16330: =head2 Data to String to Data
                   16331: 
                   16332: =over 4
1.191     harris41 16333: 
                   16334: =item *
                   16335: 
1.243     albertel 16336: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16337: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16338: 
                   16339: =item *
                   16340: 
1.243     albertel 16341: hashref2str($hashref) : convert a hashref into a string complete with
                   16342: escaping and '=' and '&' separators, supports elements that are
                   16343: arrayrefs and hashrefs
1.191     harris41 16344: 
                   16345: =item *
                   16346: 
1.243     albertel 16347: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16348: with escaping and '&' separators, supports elements that are arrayrefs
                   16349: and hashrefs
1.191     harris41 16350: 
                   16351: =item *
                   16352: 
1.243     albertel 16353: str2hash($string) : convert string to hash using unescaping and
                   16354: splitting on '=' and '&', supports elements that are arrayrefs and
                   16355: hashrefs
1.191     harris41 16356: 
                   16357: =item *
                   16358: 
1.243     albertel 16359: str2array($string) : convert string to hash using unescaping and
                   16360: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16361: 
                   16362: =back
                   16363: 
                   16364: =head2 Logging Routines
                   16365: 
                   16366: 
                   16367: These routines allow one to make log messages in the lonnet.log and
                   16368: lonnet.perm logfiles.
1.191     harris41 16369: 
1.1119    foxr     16370: =over 4
                   16371: 
1.191     harris41 16372: =item *
                   16373: 
1.243     albertel 16374: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16375: 
                   16376: =item *
                   16377: 
1.243     albertel 16378: logthis() : append message to the normal lonnet.log file, it gets
                   16379: preiodically rolled over and deleted.
1.191     harris41 16380: 
                   16381: =item *
                   16382: 
1.243     albertel 16383: logperm() : append a permanent message to lonnet.perm.log, this log
                   16384: file never gets deleted by any automated portion of the system, only
                   16385: messages of critical importance should go in here.
                   16386: 
1.1119    foxr     16387: 
1.243     albertel 16388: =back
                   16389: 
                   16390: =head2 General File Helper Routines
                   16391: 
                   16392: =over 4
1.191     harris41 16393: 
                   16394: =item *
                   16395: 
1.481     raeburn  16396: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16397: (a) files in /uploaded
                   16398:   (i) If a local copy of the file exists - 
                   16399:       compares modification date of local copy with last-modified date for 
                   16400:       definitive version stored on home server for course. If local copy is 
                   16401:       stale, requests a new version from the home server and stores it. 
                   16402:       If the original has been removed from the home server, then local copy 
                   16403:       is unlinked.
                   16404:   (ii) If local copy does not exist -
                   16405:       requests the file from the home server and stores it. 
                   16406:   
                   16407:   If $caller is 'uploadrep':  
                   16408:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16409:     for request for files originally uploaded via DOCS. 
                   16410:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16411:   
                   16412:   Otherwise:
                   16413:      This indicates a call from the content generation phase of the request.
                   16414:      -  returns the entire contents of the file or -1.
                   16415:      
                   16416: (b) files in /res
                   16417:    - returns the entire contents of a file or -1; 
                   16418:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16419: 
1.712     albertel 16420: 
                   16421: =item *
                   16422: 
                   16423: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16424:                   reference
                   16425: 
                   16426: returns either a stat() list of data about the file or an empty list
                   16427: if the file doesn't exist or couldn't find out about it (connection
                   16428: problems or user unknown)
                   16429: 
1.191     harris41 16430: =item *
                   16431: 
1.243     albertel 16432: filelocation($dir,$file) : returns file system location of a file
                   16433: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16434: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16435: and a file of ../bob will become /a/bob)
1.191     harris41 16436: 
                   16437: =item *
                   16438: 
                   16439: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16440: filelocation except for hrefs
                   16441: 
                   16442: =item *
                   16443: 
1.1261    raeburn  16444: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16445: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16446: 
1.243     albertel 16447: =back
                   16448: 
1.608     albertel 16449: =head2 Usererfile file routines (/uploaded*)
                   16450: 
                   16451: =over 4
                   16452: 
                   16453: =item *
                   16454: 
                   16455: userfileupload(): main rotine for putting a file in a user or course's
                   16456:                   filespace, arguments are,
                   16457: 
1.620     albertel 16458:  formname - required - this is the name of the element in $env where the
1.608     albertel 16459:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16460:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16461:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16462:  context - if coursedoc, store the file in the course of the active role
                   16463:              of the current user; 
                   16464:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16465:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16466:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16467:          if undefined, it will be placed in "unknown"
                   16468: 
                   16469:  (This routine calls clean_filename() to remove any dangerous
                   16470:  characters from the filename, and then calls finuserfileupload() to
                   16471:  complete the transaction)
                   16472: 
                   16473:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16474:  and /adm/notfound.html if unsuccessful
                   16475: 
                   16476: =item *
                   16477: 
                   16478: clean_filename(): routine for cleaing a filename up for storage in
                   16479:                  userfile space, argument is:
                   16480: 
                   16481:  filename - proposed filename
                   16482: 
                   16483: returns: the new clean filename
                   16484: 
                   16485: =item *
                   16486: 
1.1090    raeburn  16487: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16488: userspace, probably shouldn't be called directly
                   16489: 
                   16490:   docuname: username or courseid of destination for the file
                   16491:   docudom: domain of user/course of destination for the file
                   16492:   formname: same as for userfileupload()
1.1090    raeburn  16493:   fname: filename (including subdirectories) for the file
                   16494:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  16495:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16496:   allfiles: reference to hash used to store objects found by parser
                   16497:   codebase: reference to hash used for codebases of java objects found by parser
                   16498:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16499:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16500:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16501:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16502:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16503:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16504:   mimetype: reference to scalar to accommodate mime type determined
                   16505:             from File::MMagic if $parser = parse.
1.608     albertel 16506: 
                   16507:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16508:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16509:  was 'overwrite').
                   16510:  
1.608     albertel 16511: 
                   16512: =item *
                   16513: 
                   16514: renameuserfile(): renames an existing userfile to a new name
                   16515: 
                   16516:   Args:
                   16517:    docuname: username or courseid of destination for the file
                   16518:    docudom: domain of user/course of destination for the file
                   16519:    old: current file name (including any subdirs under userfiles)
                   16520:    new: desired file name (including any subdirs under userfiles)
                   16521: 
                   16522: =item *
                   16523: 
                   16524: mkdiruserfile(): creates a directory is a userfiles dir
                   16525: 
                   16526:   Args:
                   16527:    docuname: username or courseid of destination for the file
                   16528:    docudom: domain of user/course of destination for the file
                   16529:    dir: dir to create (including any subdirs under userfiles)
                   16530: 
                   16531: =item *
                   16532: 
                   16533: removeuserfile(): removes a file that exists in userfiles
                   16534: 
                   16535:   Args:
                   16536:    docuname: username or courseid of destination for the file
                   16537:    docudom: domain of user/course of destination for the file
                   16538:    fname: filname to delete (including any subdirs under userfiles)
                   16539: 
                   16540: =item *
                   16541: 
                   16542: removeuploadedurl(): convience function for removeuserfile()
                   16543: 
                   16544:   Args:
                   16545:    url:  a full /uploaded/... url to delete
                   16546: 
1.747     albertel 16547: =item * 
                   16548: 
                   16549: get_portfile_permissions():
                   16550:   Args:
                   16551:     domain: domain of user or course contain the portfolio files
                   16552:     user: name of user or num of course contain the portfolio files
                   16553:   Returns:
                   16554:     hashref of a dump of the proper file_permissions.db
                   16555:    
                   16556: 
                   16557: =item * 
                   16558: 
                   16559: get_access_controls():
                   16560: 
                   16561: Args:
                   16562:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16563:   group: (optional) the group you want the files associated with
                   16564:   file: (optional) the file you want access info on
                   16565: 
                   16566: Returns:
1.749     raeburn  16567:     a hash (keys are file names) of hashes containing
                   16568:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16569:         values are XML containing access control settings (see below) 
1.747     albertel 16570: 
                   16571: Internal notes:
                   16572: 
1.749     raeburn  16573:  access controls are stored in file_permissions.db as key=value pairs.
                   16574:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16575:         where scope -> public,guest,course,group,domains or users.
                   16576:               end -> UNIX time for end of access (0 -> no end date)
                   16577:               start -> UNIX time for start of access
                   16578: 
                   16579:     value -> XML description of access control
                   16580:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16581:             <start></start>
                   16582:             <end></end>
                   16583: 
                   16584:             <password></password>  for scope type = guest
                   16585: 
                   16586:             <domain></domain>     for scope type = course or group
                   16587:             <number></number>
                   16588:             <roles id="">
                   16589:              <role></role>
                   16590:              <access></access>
                   16591:              <section></section>
                   16592:              <group></group>
                   16593:             </roles>
                   16594: 
                   16595:             <dom></dom>         for scope type = domains
                   16596: 
                   16597:             <users>             for scope type = users
                   16598:              <user>
                   16599:               <uname></uname>
                   16600:               <udom></udom>
                   16601:              </user>
                   16602:             </users>
                   16603:            </scope> 
                   16604:               
                   16605:  Access data is also aggregated for each file in an additional key=value pair:
                   16606:  key -> path to file/file_name\0accesscontrol 
                   16607:  value -> reference to hash
                   16608:           hash contains key = value pairs
                   16609:           where key = uniqueID:scope_end_start
                   16610:                 value = UNIX time record was last updated
                   16611: 
                   16612:           Used to improve speed of look-ups of access controls for each file.  
                   16613:  
                   16614:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16615: 
1.1198    raeburn  16616: =item *
                   16617: 
1.749     raeburn  16618: modify_access_controls():
                   16619: 
                   16620: Modifies access controls for a portfolio file
                   16621: Args
                   16622: 1. file name
                   16623: 2. reference to hash of required changes,
                   16624: 3. domain
                   16625: 4. username
                   16626:   where domain,username are the domain of the portfolio owner 
                   16627:   (either a user or a course) 
                   16628: 
                   16629: Returns:
                   16630: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16631: 2. result of deletions ('ok' or 'error', with error message).
                   16632: 3. reference to hash of any new or updated access controls.
                   16633: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16634:    key = integer (inbound ID)
1.1198    raeburn  16635:    value = uniqueID
                   16636: 
                   16637: =item *
                   16638: 
                   16639: get_timebased_id():
                   16640: 
                   16641: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   16642: course via the Course Editor (e.g., folders, composite pages, 
                   16643: group bulletin boards).
                   16644: 
                   16645: Args: (first three required; six others optional)
                   16646: 
                   16647: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16648:    docssequence, or name of group
                   16649: 
                   16650: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16651:    e.g., num, boardids
                   16652: 
                   16653: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   16654:    file will be named nohist_namespace.db
                   16655: 
                   16656: 4. cdom: domain of course; default is current course domain from %env
                   16657: 
                   16658: 5. cnum: course number; default is current course number from %env
                   16659: 
                   16660: 6. idtype: set to concat if an additional digit is to be appended to the 
                   16661:    unix timestamp to form the suffix, if the plain timestamp is already
                   16662:    in use.  Default is to not do this, but simply increment the unix 
                   16663:    timestamp by 1 until a unique key is obtained.
                   16664: 
                   16665: 7. who: holder of locking key; defaults to user:domain for user.
                   16666: 
                   16667: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   16668:    retrying); default is 3.
                   16669: 
                   16670: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   16671: 
                   16672: Returns:
                   16673: 
                   16674: 1. suffix obtained (numeric)
                   16675: 
                   16676: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16677: 
                   16678: 3. error: contains (localized) error message if an error occurred.
                   16679: 
1.747     albertel 16680: 
1.608     albertel 16681: =back
                   16682: 
1.243     albertel 16683: =head2 HTTP Helper Routines
                   16684: 
                   16685: =over 4
                   16686: 
1.191     harris41 16687: =item *
                   16688: 
                   16689: escape() : unpack non-word characters into CGI-compatible hex codes
                   16690: 
                   16691: =item *
                   16692: 
                   16693: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16694: 
1.243     albertel 16695: =back
                   16696: 
                   16697: =head1 PRIVATE SUBROUTINES
                   16698: 
                   16699: =head2 Underlying communication routines (Shouldn't call)
                   16700: 
                   16701: =over 4
                   16702: 
                   16703: =item *
                   16704: 
                   16705: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16706: 
                   16707: =item *
                   16708: 
                   16709: reply() : uses subreply to send a message to remote machine, logs all failures
                   16710: 
                   16711: =item *
                   16712: 
                   16713: critical() : passes a critical message to another server; if cannot
                   16714: get through then place message in connection buffer directory and
                   16715: returns con_delayed, if incapable of saving message, returns
                   16716: con_failed
                   16717: 
                   16718: =item *
                   16719: 
                   16720: reconlonc() : tries to reconnect lonc client processes.
                   16721: 
                   16722: =back
                   16723: 
                   16724: =head2 Resource Access Logging
                   16725: 
                   16726: =over 4
                   16727: 
                   16728: =item *
                   16729: 
                   16730: flushcourselogs() : flush (save) buffer logs and access logs
                   16731: 
                   16732: =item *
                   16733: 
                   16734: courselog($what) : save message for course in hash
                   16735: 
                   16736: =item *
                   16737: 
                   16738: courseacclog($what) : save message for course using &courselog().  Perform
                   16739: special processing for specific resource types (problems, exams, quizzes, etc).
                   16740: 
1.191     harris41 16741: =item *
                   16742: 
                   16743: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16744: as a PerlChildExitHandler
1.243     albertel 16745: 
                   16746: =back
                   16747: 
                   16748: =head2 Other
                   16749: 
                   16750: =over 4
                   16751: 
                   16752: =item *
                   16753: 
                   16754: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16755: 
                   16756: =back
                   16757: 
                   16758: =cut
1.877     foxr     16759: 

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