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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1406  ! raeburn     4: # $Id: lonnet.pm,v 1.1405 2019/02/15 20:56:18 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
                     82:             %managerstab);
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.1389    raeburn  1085: # check if user's browser sent load balancer cookie and server still has session
                   1086: # and is not overloaded.
                   1087: sub check_for_balancer_cookie {
                   1088:     my ($r,$update_mtime) = @_;
                   1089:     my ($otherserver,$cookie);
                   1090:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1091:     if (exists($cookies{'balanceID'})) {
                   1092:         my $balid = $cookies{'balanceID'};
                   1093:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1094:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1095:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1096:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1097:                 my ($possudom,$possuname) = ($1,$2);
                   1098:                 my $has_session = 0;
                   1099:                 if ((&domain($possudom) ne '') &&
                   1100:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1101:                     my $try_server;
                   1102:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1103:                     if ($opened) {
                   1104:                         flock($idf,LOCK_SH);
                   1105:                         while (my $line = <$idf>) {
                   1106:                             chomp($line);
                   1107:                             if (&hostname($line) ne '') {
                   1108:                                 $try_server = $line;
                   1109:                                 last;
                   1110:                             }
                   1111:                         }
                   1112:                         close($idf);
                   1113:                         if (($try_server) &&
                   1114:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1115:                             my $lowest_load = 30000;
                   1116:                             ($otherserver,$lowest_load) =
                   1117:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1118:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1119:                                 $has_session = 1;
                   1120:                             } else {
                   1121:                                 undef($otherserver);
                   1122:                             }
                   1123:                         }
                   1124:                     }
                   1125:                 }
                   1126:                 if ($has_session) {
                   1127:                     if ($update_mtime) {
                   1128:                         my $atime = my $mtime = time;
                   1129:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1130:                     }
                   1131:                 } else {
                   1132:                     unlink("$balancedir/$cookie.id");
                   1133:                 }
                   1134:             }
                   1135:         }
                   1136:     }
                   1137:     return ($otherserver,$cookie);
                   1138: }
                   1139: 
                   1140: sub delbalcookie {
                   1141:     my ($cookie,$balancer) =@_;
                   1142:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1143:         my ($udom,$uname) = ($1,$2);
                   1144:         my $uprimary_id = &domain($udom,'primary');
                   1145:         my $uintdom = &internet_dom($uprimary_id);
                   1146:         my $intdom = &internet_dom($balancer);
                   1147:         my $serverhomedom = &host_domain($balancer);
                   1148:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1149:             return &reply("delbalcookie:$cookie",$balancer);
                   1150:         }
                   1151:     }
                   1152: }
                   1153: 
1.914     albertel 1154: # -------------------------------- ask if server already has a session for user
                   1155: sub has_user_session {
                   1156:     my ($lonid,$udom,$uname) = @_;
                   1157:     my $result = &reply(join(':','userhassession',
                   1158: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1159:     return 1 if ($result eq 'ok');
                   1160: 
                   1161:     return 0;
                   1162: }
                   1163: 
1.1076    raeburn  1164: # --------- determine least loaded server in a user's domain which allows login
                   1165: 
                   1166: sub choose_server {
1.1259    raeburn  1167:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1168:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1169:     my %servers = &get_servers($udom);
1.1076    raeburn  1170:     my $lowest_load = 30000;
1.1259    raeburn  1171:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1172:     if ($skiploadbal) {
                   1173:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1174:         unless (defined($cached)) {
                   1175:             my $cachetime = 60*60*24;
                   1176:             my %domconfig =
                   1177:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1178:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1179:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1180:                                            $cachetime);
                   1181:             }
                   1182:         }
                   1183:     }
1.1076    raeburn  1184:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1185:         if ($skiploadbal) {
                   1186:             if (ref($balancers) eq 'HASH') {
                   1187:                 next if (exists($balancers->{$lonhost}));
                   1188:             }
1.1389    raeburn  1189:         }
1.1115    raeburn  1190:         my $loginvia;
                   1191:         if ($checkloginvia) {
                   1192:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1193:             if ($loginvia) {
                   1194:                 my ($server,$path) = split(/:/,$loginvia);
                   1195:                 ($login_host, $lowest_load) =
1.1253    raeburn  1196:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1197:                 if ($login_host eq $server) {
                   1198:                     $portal_path = $path;
1.1151    raeburn  1199:                     $isredirect = 1;
1.1116    raeburn  1200:                 }
                   1201:             } else {
                   1202:                 ($login_host, $lowest_load) =
1.1253    raeburn  1203:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1204:                 if ($login_host eq $lonhost) {
                   1205:                     $portal_path = '';
1.1151    raeburn  1206:                     $isredirect = ''; 
1.1116    raeburn  1207:                 }
                   1208:             }
                   1209:         } else {
1.1076    raeburn  1210:             ($login_host, $lowest_load) =
1.1253    raeburn  1211:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1212:         }
                   1213:     }
                   1214:     if ($login_host ne '') {
1.1116    raeburn  1215:         $hostname = &hostname($login_host);
1.1076    raeburn  1216:     }
1.1331    raeburn  1217:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1218: }
                   1219: 
1.202     matthew  1220: # --------------------------------------------- Try to change a user's password
                   1221: 
                   1222: sub changepass {
1.799     raeburn  1223:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1224:     $currentpass = &escape($currentpass);
                   1225:     $newpass     = &escape($newpass);
1.1030    raeburn  1226:     my $lonhost = $perlvar{'lonHostID'};
                   1227:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1228: 		       $server);
                   1229:     if (! $answer) {
                   1230: 	&logthis("No reply on password change request to $server ".
                   1231: 		 "by $uname in domain $udom.");
                   1232:     } elsif ($answer =~ "^ok") {
                   1233:         &logthis("$uname in $udom successfully changed their password ".
                   1234: 		 "on $server.");
                   1235:     } elsif ($answer =~ "^pwchange_failure") {
                   1236: 	&logthis("$uname in $udom was unable to change their password ".
                   1237: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1238: 		 "or pwchange");
                   1239:     } elsif ($answer =~ "^non_authorized") {
                   1240:         &logthis("$uname in $udom did not get their password correct when ".
                   1241: 		 "attempting to change it on $server.");
                   1242:     } elsif ($answer =~ "^auth_mode_error") {
                   1243:         &logthis("$uname in $udom attempted to change their password despite ".
                   1244: 		 "not being locally or internally authenticated on $server.");
                   1245:     } elsif ($answer =~ "^unknown_user") {
                   1246:         &logthis("$uname in $udom attempted to change their password ".
                   1247: 		 "on $server but were unable to because $server is not ".
                   1248: 		 "their home server.");
                   1249:     } elsif ($answer =~ "^refused") {
                   1250: 	&logthis("$server refused to change $uname in $udom password because ".
                   1251: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1252:     } elsif ($answer =~ "invalid_client") {
                   1253:         &logthis("$server refused to change $uname in $udom password because ".
                   1254:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1255:     }
                   1256:     return $answer;
1.1       albertel 1257: }
                   1258: 
1.169     harris41 1259: # ----------------------- Try to determine user's current authentication scheme
                   1260: 
                   1261: sub queryauthenticate {
                   1262:     my ($uname,$udom)=@_;
1.456     albertel 1263:     my $uhome=&homeserver($uname,$udom);
                   1264:     if (!$uhome) {
                   1265: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1266: 	return 'no_host';
                   1267:     }
                   1268:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1269:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1270: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1271:     }
1.456     albertel 1272:     return $answer;
1.169     harris41 1273: }
                   1274: 
1.1       albertel 1275: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1276: 
1.1       albertel 1277: sub authenticate {
1.1073    raeburn  1278:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1279:     $upass=&escape($upass);
                   1280:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1281:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1282:     my $newhome;
1.836     www      1283:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1284: # Maybe the machine was offline and only re-appeared again recently?
                   1285:         &reconlonc();
                   1286: # One more
1.952     raeburn  1287: 	$uhome=&homeserver($uname,$udom,1);
                   1288:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1289:             if (defined(&domain($udom,'primary'))) {
                   1290:                 $newhome=&domain($udom,'primary');
                   1291:             }
                   1292:             if ($newhome ne '') {
                   1293:                 $uhome = $newhome;
                   1294:             }
                   1295:         }
1.836     www      1296: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1297: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1298: 	    return 'no_host';
                   1299:         }
1.1       albertel 1300:     }
1.1073    raeburn  1301:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1302:     if ($answer eq 'authorized') {
1.952     raeburn  1303:         if ($newhome) {
                   1304:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1305:             return 'no_account_on_host'; 
                   1306:         } else {
                   1307:             &logthis("User $uname at $udom authorized by $uhome");
                   1308:             return $uhome;
                   1309:         }
1.471     albertel 1310:     }
                   1311:     if ($answer eq 'non_authorized') {
                   1312: 	&logthis("User $uname at $udom rejected by $uhome");
                   1313: 	return 'no_host'; 
1.9       www      1314:     }
1.471     albertel 1315:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1316:     return 'no_host';
                   1317: }
                   1318: 
1.1073    raeburn  1319: sub can_host_session {
1.1074    raeburn  1320:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1321:     my $canhost = 1;
1.1074    raeburn  1322:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1323:     if (ref($remotesessions) eq 'HASH') {
                   1324:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1325:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1326:                 $canhost = 0;
                   1327:             } else {
                   1328:                 $canhost = 1;
                   1329:             }
                   1330:         }
                   1331:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1332:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1333:                 $canhost = 1;
                   1334:             } else {
                   1335:                 $canhost = 0;
                   1336:             }
                   1337:         }
                   1338:         if ($canhost) {
                   1339:             if ($remotesessions->{'version'} ne '') {
                   1340:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1341:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1342:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1343:                         my $major = $1;
                   1344:                         my $minor = $2;
                   1345:                         if (($major < $reqmajor ) ||
                   1346:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1347:                             $canhost = 0;
                   1348:                         }
                   1349:                     } else {
                   1350:                         $canhost = 0;
                   1351:                     }
                   1352:                 }
                   1353:             }
                   1354:         }
                   1355:     }
                   1356:     if ($canhost) {
                   1357:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1358:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1359:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1360:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1361:                 if (($uint_dom ne '') && 
                   1362:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1363:                     $canhost = 0;
                   1364:                 } else {
                   1365:                     $canhost = 1;
                   1366:                 }
                   1367:             }
                   1368:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1369:                 if (($uint_dom ne '') && 
                   1370:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1371:                     $canhost = 1;
                   1372:                 } else {
                   1373:                     $canhost = 0;
                   1374:                 }
                   1375:             }
                   1376:         }
                   1377:     }
                   1378:     return $canhost;
                   1379: }
                   1380: 
1.1083    raeburn  1381: sub spare_can_host {
                   1382:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1383:     my $canhost=1;
1.1279    raeburn  1384:     my $try_server_hostname = &hostname($try_server);
                   1385:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1386:     my $serverhomedom = &host_domain($serverhomeID);
                   1387:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1388:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1389:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1390:             $canhost = 0;
                   1391:         }
                   1392:     }
                   1393:     if (($canhost) && ($uint_dom)) {
                   1394:         my @intdoms;
                   1395:         my $internet_names = &get_internet_names($try_server);
                   1396:         if (ref($internet_names) eq 'ARRAY') {
                   1397:             @intdoms = @{$internet_names};
                   1398:         }
                   1399:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1400:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1401:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1402:                                          $remotesessions,
                   1403:                                          $defdomdefaults{'hostedsessions'});
                   1404:         }
1.1083    raeburn  1405:     }
                   1406:     return $canhost;
                   1407: }
                   1408: 
1.1123    raeburn  1409: sub this_host_spares {
                   1410:     my ($dom) = @_;
1.1126    raeburn  1411:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1412:     my @hosts = &current_machine_ids();
                   1413:     foreach my $lonhost (@hosts) {
                   1414:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1415:             $dom_in_use = $dom;
                   1416:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1417:             last;
                   1418:         }
                   1419:     }
1.1126    raeburn  1420:     if ($dom_in_use ne '') {
                   1421:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1422:     }
                   1423:     if (ref($result) ne 'HASH') {
                   1424:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1425:         $dom_in_use = &host_domain($lonhost_in_use);
                   1426:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1427:         if (ref($result) ne 'HASH') {
                   1428:             $result = \%spareid;
                   1429:         }
                   1430:     }
                   1431:     return $result;
                   1432: }
                   1433: 
                   1434: sub spares_for_offload  {
                   1435:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1436:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1437:     if (defined($cached)) {
                   1438:         return $result;
                   1439:     } else {
1.1126    raeburn  1440:         my $cachetime = 60*60*24;
                   1441:         my %domconfig =
                   1442:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1443:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1444:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1445:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1446:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1447:                 }
                   1448:             }
                   1449:         }
                   1450:     }
1.1126    raeburn  1451:     return;
1.1123    raeburn  1452: }
                   1453: 
1.1129    raeburn  1454: sub get_lonbalancer_config {
                   1455:     my ($servers) = @_;
                   1456:     my ($currbalancer,$currtargets);
                   1457:     if (ref($servers) eq 'HASH') {
                   1458:         foreach my $server (keys(%{$servers})) {
                   1459:             my %what = (
                   1460:                          spareid => 1,
                   1461:                          perlvar => 1,
                   1462:                        );
                   1463:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1464:             if ($result eq 'ok') {
                   1465:                 if (ref($returnhash) eq 'HASH') {
                   1466:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1467:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1468:                             $currbalancer = $server;
                   1469:                             $currtargets = {};
                   1470:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1471:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1472:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1473:                                 }
                   1474:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1475:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1476:                                 }
                   1477:                             }
                   1478:                             last;
                   1479:                         }
                   1480:                     }
                   1481:                 }
                   1482:             }
                   1483:         }
                   1484:     }
                   1485:     return ($currbalancer,$currtargets);
                   1486: }
                   1487: 
                   1488: sub check_loadbalancing {
1.1331    raeburn  1489:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1490:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1491:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1492:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1493:     my @hosts = &current_machine_ids();
1.1129    raeburn  1494:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1495:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1496:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1497:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1498:     my $domneedscache;
1.1129    raeburn  1499:     my $cachetime = 60*60*24;
                   1500: 
                   1501:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1502:         $dom_in_use = $udom;
                   1503:         $homeintdom = 1;
                   1504:     } else {
                   1505:         $dom_in_use = $serverhomedom;
                   1506:     }
                   1507:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1508:     unless (defined($cached)) {
                   1509:         my %domconfig =
                   1510:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1511:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1512:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1513:         } else {
                   1514:             $domneedscache = $dom_in_use;
1.1129    raeburn  1515:         }
                   1516:     }
                   1517:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1518:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1519:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1520:         if ($is_balancer) {
                   1521:             if (ref($currrules) eq 'HASH') {
                   1522:                 if ($homeintdom) {
                   1523:                     if ($uname ne '') {
                   1524:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1525:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1526:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1527:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1528:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1529:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1530:                             }
                   1531:                         }
                   1532:                         if ($rule_in_effect eq '') {
                   1533:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1534:                             if ($userenv{'inststatus'} ne '') {
                   1535:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1536:                                 my ($othertitle,$usertypes,$types) =
                   1537:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1538:                                 if (ref($types) eq 'ARRAY') {
                   1539:                                     foreach my $type (@{$types}) {
                   1540:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1541:                                             if (exists($currrules->{$type})) {
                   1542:                                                 $rule_in_effect = $currrules->{$type};
                   1543:                                             }
                   1544:                                         }
                   1545:                                     }
                   1546:                                 }
                   1547:                             } else {
                   1548:                                 if (exists($currrules->{'default'})) {
                   1549:                                     $rule_in_effect = $currrules->{'default'};
                   1550:                                 }
                   1551:                             }
                   1552:                         }
                   1553:                     } else {
                   1554:                         if (exists($currrules->{'default'})) {
                   1555:                             $rule_in_effect = $currrules->{'default'};
                   1556:                         }
                   1557:                     }
                   1558:                 } else {
                   1559:                     if ($currrules->{'_LC_external'} ne '') {
                   1560:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1561:                     }
                   1562:                 }
                   1563:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1564:                                                        $uname,$udom);
                   1565:             }
                   1566:         }
                   1567:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1568:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1569:         unless (defined($cached)) {
                   1570:             my %domconfig =
                   1571:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1572:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1573:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1574:             } else {
                   1575:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1576:             }
                   1577:         }
                   1578:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1579:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1580:                 &check_balancer_result($result,@hosts);
                   1581:             if ($is_balancer) {
1.1129    raeburn  1582:                 if (ref($currrules) eq 'HASH') {
                   1583:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1584:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1585:                     }
                   1586:                 }
                   1587:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1588:                                                        $uname,$udom);
                   1589:             }
                   1590:         } else {
                   1591:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1592:                 $is_balancer = 1;
                   1593:                 $offloadto = &this_host_spares($dom_in_use);
                   1594:             }
1.1307    raeburn  1595:             unless (defined($cached)) {
                   1596:                 $domneedscache = $serverhomedom;
                   1597:             }
1.1129    raeburn  1598:         }
                   1599:     } else {
                   1600:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1601:             $is_balancer = 1;
                   1602:             $offloadto = &this_host_spares($dom_in_use);
                   1603:         }
1.1307    raeburn  1604:         unless (defined($cached)) {
                   1605:             $domneedscache = $serverhomedom;
                   1606:         }
                   1607:     }
                   1608:     if ($domneedscache) {
                   1609:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1610:     }
1.1176    raeburn  1611:     if ($is_balancer) {
                   1612:         my $lowest_load = 30000;
                   1613:         if (ref($offloadto) eq 'HASH') {
                   1614:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1615:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1616:                     ($otherserver,$lowest_load) =
                   1617:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1618:                 }
1.1129    raeburn  1619:             }
1.1176    raeburn  1620:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1621: 
1.1176    raeburn  1622:             if (!$found_server) {
                   1623:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1624:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1625:                         ($otherserver,$lowest_load) =
                   1626:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1627:                     }
                   1628:                 }
                   1629:             }
                   1630:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1631:             if (@{$offloadto} == 1) {
                   1632:                 $otherserver = $offloadto->[0];
                   1633:             } elsif (@{$offloadto} > 1) {
                   1634:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1635:                     ($otherserver,$lowest_load) =
                   1636:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1637:                 }
                   1638:             }
                   1639:         }
1.1331    raeburn  1640:         unless ($caller eq 'login') {
                   1641:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1642:                 $is_balancer = 0;
                   1643:                 if ($uname ne '' && $udom ne '') {
                   1644:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1645:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1646:                                  'user.loadbalcheck.time' => time});
                   1647:                     }
1.1176    raeburn  1648:                 }
1.1129    raeburn  1649:             }
                   1650:         }
1.1389    raeburn  1651:         unless ($homeintdom) {
                   1652:             undef($setcookie);
                   1653:         }
1.1129    raeburn  1654:     }
1.1391    raeburn  1655:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1656: }
                   1657: 
1.1191    raeburn  1658: sub check_balancer_result {
                   1659:     my ($result,@hosts) = @_;
1.1391    raeburn  1660:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1661:     if (ref($result) eq 'HASH') {
                   1662:         if ($result->{'lonhost'} ne '') {
                   1663:             my $currbalancer = $result->{'lonhost'};
                   1664:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1665:                 $is_balancer = 1;
                   1666:                 $currtargets = $result->{'targets'};
                   1667:                 $currrules = $result->{'rules'};
                   1668:             }
1.1391    raeburn  1669:             $dom_balancers = $currbalancer;
1.1191    raeburn  1670:         } else {
1.1391    raeburn  1671:             if (keys(%{$result})) {
                   1672:                 foreach my $key (keys(%{$result})) {
                   1673:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1674:                         (ref($result->{$key}) eq 'HASH')) {
                   1675:                         $is_balancer = 1;
                   1676:                         $currrules = $result->{$key}{'rules'};
                   1677:                         $currtargets = $result->{$key}{'targets'};
                   1678:                         $setcookie = $result->{$key}{'cookie'};
                   1679:                         last;
                   1680:                     }
1.1191    raeburn  1681:                 }
1.1391    raeburn  1682:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1683:             }
                   1684:         }
                   1685:     }
1.1391    raeburn  1686:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1687: }
                   1688: 
1.1129    raeburn  1689: sub get_loadbalancer_targets {
                   1690:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1691:     my $offloadto;
1.1175    raeburn  1692:     if ($rule_in_effect eq 'none') {
                   1693:         return [$perlvar{'lonHostID'}];
                   1694:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1695:         $offloadto = $currtargets;
                   1696:     } else {
                   1697:         if ($rule_in_effect eq 'homeserver') {
                   1698:             my $homeserver = &homeserver($uname,$udom);
                   1699:             if ($homeserver ne 'no_host') {
                   1700:                 $offloadto = [$homeserver];
                   1701:             }
                   1702:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1703:             my %domconfig =
                   1704:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1705:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1706:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1707:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1708:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1709:                     }
                   1710:                 }
                   1711:             } else {
1.1178    raeburn  1712:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1713:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1714:                 if (&hostname($remotebalancer) ne '') {
                   1715:                     $offloadto = [$remotebalancer];
                   1716:                 }
                   1717:             }
                   1718:         } elsif (&hostname($rule_in_effect) ne '') {
                   1719:             $offloadto = [$rule_in_effect];
                   1720:         }
                   1721:     }
                   1722:     return $offloadto;
                   1723: }
                   1724: 
1.1127    raeburn  1725: sub internet_dom_servers {
                   1726:     my ($dom) = @_;
                   1727:     my (%uniqservers,%servers);
                   1728:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1729:     my @machinedoms = &machine_domains($primaryserver);
                   1730:     foreach my $mdom (@machinedoms) {
                   1731:         my %currservers = %servers;
                   1732:         my %server = &get_servers($mdom);
                   1733:         %servers = (%currservers,%server);
                   1734:     }
                   1735:     my %by_hostname;
                   1736:     foreach my $id (keys(%servers)) {
                   1737:         push(@{$by_hostname{$servers{$id}}},$id);
                   1738:     }
                   1739:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1740:         if (@{$by_hostname{$hostname}} > 1) {
                   1741:             my $match = 0;
                   1742:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1743:                 if (&host_domain($id) eq $dom) {
                   1744:                     $uniqservers{$id} = $hostname;
                   1745:                     $match = 1;
                   1746:                 }
                   1747:             }
                   1748:             unless ($match) {
                   1749:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1750:             }
                   1751:         } else {
                   1752:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1753:         }
                   1754:     }
                   1755:     return %uniqservers;
                   1756: }
                   1757: 
1.1347    raeburn  1758: sub trusted_domains {
                   1759:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1760:     my ($trusted,$untrusted);
1.1347    raeburn  1761:     if (&domain($calldom) eq '') {
1.1349    raeburn  1762:         return ($trusted,$untrusted);
1.1347    raeburn  1763:     }
1.1395    raeburn  1764:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1765:         return ($trusted,$untrusted);
1.1347    raeburn  1766:     }
                   1767:     my $callprimary = &domain($calldom,'primary');
                   1768:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1769:     if ($intcalldom eq '') {
1.1349    raeburn  1770:         return ($trusted,$untrusted);
1.1347    raeburn  1771:     }
                   1772: 
                   1773:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1774:     unless (defined($cached)) {
                   1775:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1776:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1777:         $trustconfig = $domconfig{'trust'};
                   1778:     }
                   1779:     if (ref($trustconfig)) {
                   1780:         my (%possexc,%possinc,@allexc,@allinc); 
                   1781:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1782:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1783:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1784:             }
                   1785:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1786:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1787:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1788:             }
                   1789:         }
                   1790:         if (keys(%possexc)) {
                   1791:             if (keys(%possinc)) {
                   1792:                 foreach my $key (sort(keys(%possexc))) {
                   1793:                     next if ($key eq $intcalldom);
                   1794:                     unless ($possinc{$key}) {
                   1795:                         push(@allexc,$key);
                   1796:                     }
                   1797:                 }
                   1798:             } else {
                   1799:                 @allexc = sort(keys(%possexc));
                   1800:             }
                   1801:         }
                   1802:         if (keys(%possinc)) {
                   1803:             $possinc{$intcalldom} = 1;
                   1804:             @allinc = sort(keys(%possinc));
                   1805:         }
                   1806:         if ((@allexc > 0) || (@allinc > 0)) {
                   1807:             my %doms_by_intdom;
                   1808:             my %allintdoms = &all_host_intdom();
                   1809:             my %alldoms = &all_host_domain();
                   1810:             foreach my $key (%allintdoms) {
                   1811:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1812:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1813:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1814:                     }
                   1815:                 } else {
                   1816:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1817:                 }
                   1818:             }
                   1819:             foreach my $exc (@allexc) {
                   1820:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1821:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1822:                 }
                   1823:             }
                   1824:             foreach my $inc (@allinc) {
                   1825:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1826:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1827:                 }
                   1828:             }
                   1829:         }
                   1830:     }
1.1349    raeburn  1831:     return ($trusted,$untrusted);
1.1347    raeburn  1832: }
                   1833: 
                   1834: sub will_trust {
                   1835:     my ($cmdtype,$domain,$possdom) = @_;
                   1836:     return 1 if ($domain eq $possdom);
                   1837:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1838:     my $willtrust; 
                   1839:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1840:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1841:             $willtrust = 1;
                   1842:         }
                   1843:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1844:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1845:             $willtrust = 1;
                   1846:         }
                   1847:     } else {
                   1848:         $willtrust = 1;
                   1849:     }
                   1850:     return $willtrust;
                   1851: }
                   1852: 
1.1       albertel 1853: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1854: 
1.599     albertel 1855: my %homecache;
1.1       albertel 1856: sub homeserver {
1.230     stredwic 1857:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1858:     my $index="$uname:$udom";
1.426     albertel 1859: 
1.599     albertel 1860:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1861: 
                   1862:     my %servers = &get_servers($udom,'library');
                   1863:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1864:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1865: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1866: 
                   1867: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1868: 	if ($answer eq 'found') {
                   1869: 	    delete($badServerCache{$tryserver}); 
                   1870: 	    return $homecache{$index}=$tryserver;
                   1871: 	} elsif ($answer eq 'no_host') {
                   1872: 	    $badServerCache{$tryserver}=1;
                   1873: 	}
1.1       albertel 1874:     }    
                   1875:     return 'no_host';
1.70      www      1876: }
                   1877: 
1.1300    raeburn  1878: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1879: 
                   1880: sub idget {
1.1300    raeburn  1881:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1882:     my %returnhash=();
1.1300    raeburn  1883:     my @ids=(); 
                   1884:     if (ref($idsref) eq 'ARRAY') {
                   1885:         @ids = @{$idsref};
                   1886:     } else {
                   1887:         return %returnhash; 
                   1888:     }
                   1889:     if ($namespace eq '') {
                   1890:         $namespace = 'ids';
                   1891:     }
1.70      www      1892:     
1.841     albertel 1893:     my %servers = &get_servers($udom,'library');
                   1894:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1895: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1896: 	if ($namespace eq 'ids') {
                   1897: 	    $idlist=~tr/A-Z/a-z/;
                   1898: 	}
                   1899: 	my $reply;
                   1900: 	if ($namespace eq 'ids') {
                   1901: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1902: 	} else {
                   1903: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1904: 	}
1.841     albertel 1905: 	my @answer=();
                   1906: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1907: 	    @answer=split(/\&/,$reply);
                   1908: 	}                    ;
                   1909: 	my $i;
                   1910: 	for ($i=0;$i<=$#ids;$i++) {
                   1911: 	    if ($answer[$i]) {
1.1299    raeburn  1912: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1913: 	    }
1.841     albertel 1914: 	}
1.1300    raeburn  1915:     }
1.70      www      1916:     return %returnhash;
                   1917: }
                   1918: 
                   1919: # ------------------------------------- Find the IDs behind a list of usernames
                   1920: 
                   1921: sub idrget {
                   1922:     my ($udom,@unames)=@_;
                   1923:     my %returnhash=();
1.800     albertel 1924:     foreach my $uname (@unames) {
                   1925:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1926:     }
1.70      www      1927:     return %returnhash;
                   1928: }
                   1929: 
1.1300    raeburn  1930: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1931: 
                   1932: sub idput {
1.1300    raeburn  1933:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1934:     my %servers=();
1.1300    raeburn  1935:     my %ids=();
                   1936:     my %byid = ();
                   1937:     if (ref($idsref) eq 'HASH') {
                   1938:         %ids=%{$idsref};
                   1939:     }
                   1940:     if ($namespace eq '') {
                   1941:         $namespace = 'ids'; 
                   1942:     }
1.800     albertel 1943:     foreach my $uname (keys(%ids)) {
                   1944: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1945:         if ($uhom eq '') {
                   1946:             $uhom=&homeserver($uname,$udom);
                   1947:         }
1.70      www      1948:         if ($uhom ne 'no_host') {
1.800     albertel 1949:             my $esc_unam=&escape($uname);
1.1300    raeburn  1950:             if ($namespace eq 'ids') {
                   1951:                 my $id=&escape($ids{$uname});
                   1952:                 $id=~tr/A-Z/a-z/;
                   1953:                 my $esc_unam=&escape($uname);
                   1954:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1955:             } else {
1.1300    raeburn  1956:                 my @currids = split(/,/,$ids{$uname});
                   1957:                 foreach my $id (@currids) {
                   1958:                     $byid{$uhom}{$id} .= $uname.',';
                   1959:                 }
                   1960:             }
                   1961:         }
                   1962:     }
                   1963:     if ($namespace eq 'clickers') {
                   1964:         foreach my $server (keys(%byid)) {
                   1965:             if (ref($byid{$server}) eq 'HASH') {
                   1966:                 foreach my $id (keys(%{$byid{$server}})) {
                   1967:                     $byid{$server} =~ s/,$//;
                   1968:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1969:                 }
1.70      www      1970:             }
                   1971:         }
1.191     harris41 1972:     }
1.800     albertel 1973:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1974:         $servers{$server} =~ s/\&$//;
                   1975:         if ($namespace eq 'ids') {     
                   1976:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1977:         } else {
                   1978:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1979:         }
1.191     harris41 1980:     }
1.344     www      1981: }
                   1982: 
1.1300    raeburn  1983: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1984: 
                   1985: sub iddel {
1.1300    raeburn  1986:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1987:     my %result=();
1.1300    raeburn  1988:     my %ids=();
                   1989:     my %byid = ();
                   1990:     if (ref($idshashref) eq 'HASH') {
                   1991:         %ids=%{$idshashref};
                   1992:     } else {
1.1231    raeburn  1993:         return %result;
                   1994:     }
1.1300    raeburn  1995:     if ($namespace eq '') {
                   1996:         $namespace = 'ids';
                   1997:     }
1.1231    raeburn  1998:     my %servers=();
1.1300    raeburn  1999:     while (my ($id,$unamestr) = each(%ids)) {
                   2000:         if ($namespace eq 'ids') {
                   2001:             my $uhom = $uhome;
                   2002:             if ($uhom eq '') { 
                   2003:                 $uhom=&homeserver($unamestr,$udom);
                   2004:             }
                   2005:             if ($uhom ne 'no_host') {
                   2006:                 $servers{$uhom}.='&'.&escape($id);
                   2007:             }
                   2008:          } else {
                   2009:             my @curritems = split(/,/,$ids{$id});
                   2010:             foreach my $uname (@curritems) {
                   2011:                 my $uhom = $uhome;
                   2012:                 if ($uhom eq '') {
                   2013:                     $uhom=&homeserver($uname,$udom);
                   2014:                 }
                   2015:                 if ($uhom ne 'no_host') { 
                   2016:                     $byid{$uhom}{$id} .= $uname.',';
                   2017:                 }
                   2018:             }
1.1231    raeburn  2019:         }
1.1300    raeburn  2020:     }
                   2021:     if ($namespace eq 'clickers') {
                   2022:         foreach my $server (keys(%byid)) {
                   2023:             if (ref($byid{$server}) eq 'HASH') {
                   2024:                 foreach my $id (keys(%{$byid{$server}})) {
                   2025:                     $byid{$server}{$id} =~ s/,$//;
                   2026:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2027:                 }
1.1231    raeburn  2028:             }
                   2029:         }
                   2030:     }
                   2031:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2032:         $servers{$server} =~ s/\&$//;
                   2033:         if ($namespace eq 'ids') {
                   2034:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2035:         } elsif ($namespace eq 'clickers') {
                   2036:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2037:         }
1.1231    raeburn  2038:     }
                   2039:     return %result;
                   2040: }
                   2041: 
1.1300    raeburn  2042: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2043: 
                   2044: sub updateclickers {
                   2045:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2046:     my %clickers;
                   2047:     if (ref($idshashref) eq 'HASH') {
                   2048:         %clickers=%{$idshashref};
                   2049:     } else {
                   2050:         return;
                   2051:     }
                   2052:     my $items='';
                   2053:     foreach my $item (keys(%clickers)) {
                   2054:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2055:     }
                   2056:     $items=~s/\&$//;
                   2057:     my $request = "updateclickers:$udom:$action:$items";
                   2058:     if ($critical) {
                   2059:         return &critical($request,$uhome);
                   2060:     } else {
                   2061:         return &reply($request,$uhome);
                   2062:     }
                   2063: }
                   2064: 
1.1023    raeburn  2065: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2066: sub dump_dom {
1.1165    droeschl 2067:     my ($namespace, $udom, $regexp) = @_;
                   2068: 
                   2069:     $udom ||= $env{'user.domain'};
                   2070: 
                   2071:     return () unless $udom;
                   2072: 
                   2073:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2074: }
                   2075: 
1.1023    raeburn  2076: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2077: 
                   2078: sub get_dom {
1.860     raeburn  2079:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2080:     return if ($udom eq 'public');
1.806     raeburn  2081:     my $items='';
                   2082:     foreach my $item (@$storearr) {
                   2083:         $items.=&escape($item).'&';
                   2084:     }
                   2085:     $items=~s/\&$//;
1.860     raeburn  2086:     if (!$udom) {
                   2087:         $udom=$env{'user.domain'};
1.1267    raeburn  2088:         return if ($udom eq 'public');
1.860     raeburn  2089:         if (defined(&domain($udom,'primary'))) {
                   2090:             $uhome=&domain($udom,'primary');
                   2091:         } else {
1.874     albertel 2092:             undef($uhome);
1.860     raeburn  2093:         }
                   2094:     } else {
                   2095:         if (!$uhome) {
                   2096:             if (defined(&domain($udom,'primary'))) {
                   2097:                 $uhome=&domain($udom,'primary');
                   2098:             }
                   2099:         }
                   2100:     }
                   2101:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2102:         my $rep;
                   2103:         if ($namespace =~ /^enc/) {
                   2104:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2105:         } else {
                   2106:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2107:         }
1.866     raeburn  2108:         my %returnhash;
1.875     albertel 2109:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2110:             return %returnhash;
                   2111:         }
1.806     raeburn  2112:         my @pairs=split(/\&/,$rep);
                   2113:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2114:             return @pairs;
                   2115:         }
                   2116:         my $i=0;
                   2117:         foreach my $item (@$storearr) {
                   2118:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2119:             $i++;
                   2120:         }
                   2121:         return %returnhash;
                   2122:     } else {
1.880     banghart 2123:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2124:     }
                   2125: }
                   2126: 
                   2127: # -------------------------------------------- put items in domain db files 
                   2128: 
                   2129: sub put_dom {
1.860     raeburn  2130:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2131:     if (!$udom) {
                   2132:         $udom=$env{'user.domain'};
                   2133:         if (defined(&domain($udom,'primary'))) {
                   2134:             $uhome=&domain($udom,'primary');
                   2135:         } else {
1.874     albertel 2136:             undef($uhome);
1.860     raeburn  2137:         }
                   2138:     } else {
                   2139:         if (!$uhome) {
                   2140:             if (defined(&domain($udom,'primary'))) {
                   2141:                 $uhome=&domain($udom,'primary');
                   2142:             }
                   2143:         }
                   2144:     } 
                   2145:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2146:         my $items='';
                   2147:         foreach my $item (keys(%$storehash)) {
                   2148:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2149:         }
                   2150:         $items=~s/\&$//;
1.1344    raeburn  2151:         if ($namespace =~ /^enc/) {
                   2152:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2153:         } else {
                   2154:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2155:         }
1.806     raeburn  2156:     } else {
1.860     raeburn  2157:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2158:     }
                   2159: }
                   2160: 
1.1023    raeburn  2161: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2162: sub newput_dom {
1.1023    raeburn  2163:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2164:     my $result;
                   2165:     if (!$udom) {
                   2166:         $udom=$env{'user.domain'};
                   2167:     }
1.1023    raeburn  2168:     if ($udom) {
                   2169:         my $uname = &get_domainconfiguser($udom);
                   2170:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2171:     }
                   2172:     return $result;
                   2173: }
                   2174: 
1.1023    raeburn  2175: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2176: sub del_dom {
1.1023    raeburn  2177:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2178:     if (ref($storearr) eq 'ARRAY') {
                   2179:         if (!$udom) {
                   2180:             $udom=$env{'user.domain'};
                   2181:         }
1.1023    raeburn  2182:         if ($udom) {
                   2183:             my $uname = &get_domainconfiguser($udom); 
                   2184:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2185:         }
                   2186:     }
                   2187: }
                   2188: 
1.1023    raeburn  2189: # ----------------------------------construct domainconfig user for a domain 
                   2190: sub get_domainconfiguser {
                   2191:     my ($udom) = @_;
                   2192:     return $udom.'-domainconfig';
                   2193: }
                   2194: 
1.837     raeburn  2195: sub retrieve_inst_usertypes {
                   2196:     my ($udom) = @_;
                   2197:     my (%returnhash,@order);
1.989     raeburn  2198:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2199:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2200:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2201:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2202:     } else {
                   2203:         if (defined(&domain($udom,'primary'))) {
                   2204:             my $uhome=&domain($udom,'primary');
                   2205:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2206:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2207:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2208:                 return (\%returnhash,\@order);
                   2209:             }
                   2210:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2211:             my @pairs=split(/\&/,$hashitems);
                   2212:             foreach my $item (@pairs) {
                   2213:                 my ($key,$value)=split(/=/,$item,2);
                   2214:                 $key = &unescape($key);
                   2215:                 next if ($key =~ /^error: 2 /);
                   2216:                 $returnhash{$key}=&thaw_unescape($value);
                   2217:             }
                   2218:             my @esc_order = split(/\&/,$orderitems);
                   2219:             foreach my $item (@esc_order) {
                   2220:                 push(@order,&unescape($item));
                   2221:             }
                   2222:         } else {
1.1256    raeburn  2223:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2224:         }
1.1256    raeburn  2225:         return (\%returnhash,\@order);
1.837     raeburn  2226:     }
                   2227: }
                   2228: 
1.868     raeburn  2229: sub is_domainimage {
                   2230:     my ($url) = @_;
1.1306    raeburn  2231:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2232:         if (&domain($1) ne '') {
                   2233:             return '1';
                   2234:         }
                   2235:     }
                   2236:     return;
                   2237: }
                   2238: 
1.899     raeburn  2239: sub inst_directory_query {
                   2240:     my ($srch) = @_;
                   2241:     my $udom = $srch->{'srchdomain'};
                   2242:     my %results;
                   2243:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2244:     my $outcome;
1.899     raeburn  2245:     if ($homeserver ne '') {
1.1357    raeburn  2246:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2247:             if ($srch->{'srchby'} eq 'email') {
                   2248:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2249:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2250:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2251:                     (($major == 2) && ($minor < 12))) {
                   2252:                     return;
                   2253:                 }
                   2254:             }
                   2255:         }
1.904     albertel 2256: 	my $queryid=&reply("querysend:instdirsearch:".
                   2257: 			   &escape($srch->{'srchby'}).':'.
                   2258: 			   &escape($srch->{'srchterm'}).':'.
                   2259: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2260: 	my $host=&hostname($homeserver);
                   2261: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2262: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2263: 	    return;
                   2264: 	}
                   2265: 	my $response = &get_query_reply($queryid);
                   2266: 	my $maxtries = 5;
                   2267: 	my $tries = 1;
                   2268: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2269: 	    $response = &get_query_reply($queryid);
                   2270: 	    $tries ++;
                   2271: 	}
                   2272: 
                   2273:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2274:             if ($response eq 'unavailable') {
                   2275:                 $outcome = $response;
                   2276:             } else {
                   2277:                 $outcome = 'ok';
                   2278:                 my @matches = split(/\n/,$response);
                   2279:                 foreach my $match (@matches) {
                   2280:                     my ($key,$value) = split(/=/,$match);
                   2281:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2282:                 }
1.899     raeburn  2283:             }
                   2284:         }
                   2285:     }
1.909     raeburn  2286:     return ($outcome,%results);
1.899     raeburn  2287: }
                   2288: 
                   2289: sub usersearch {
                   2290:     my ($srch) = @_;
                   2291:     my $dom = $srch->{'srchdomain'};
                   2292:     my %results;
                   2293:     my %libserv = &all_library();
                   2294:     my $query = 'usersearch';
                   2295:     foreach my $tryserver (keys(%libserv)) {
                   2296:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2297:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2298:                 if ($srch->{'srchby'} eq 'email') {
                   2299:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2300:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2301:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2302:                              (($major == 2) && ($minor < 12)));
                   2303:                 }
                   2304:             }
1.899     raeburn  2305:             my $host=&hostname($tryserver);
                   2306:             my $queryid=
1.911     raeburn  2307:                 &reply("querysend:".&escape($query).':'.
                   2308:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2309:                        &escape($srch->{'srchtype'}).':'.
                   2310:                        &escape($srch->{'srchterm'}),$tryserver);
                   2311:             if ($queryid !~/^\Q$host\E\_/) {
                   2312:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2313:                 next;
1.899     raeburn  2314:             }
                   2315:             my $reply = &get_query_reply($queryid);
                   2316:             my $maxtries = 1;
                   2317:             my $tries = 1;
                   2318:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2319:                 $reply = &get_query_reply($queryid);
                   2320:                 $tries ++;
                   2321:             }
                   2322:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2323:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2324:             } else {
1.911     raeburn  2325:                 my @matches;
                   2326:                 if ($reply =~ /\n/) {
                   2327:                     @matches = split(/\n/,$reply);
                   2328:                 } else {
                   2329:                     @matches = split(/\&/,$reply);
                   2330:                 }
1.899     raeburn  2331:                 foreach my $match (@matches) {
                   2332:                     my ($uname,$udom,%userhash);
1.911     raeburn  2333:                     foreach my $entry (split(/:/,$match)) {
                   2334:                         my ($key,$value) =
                   2335:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2336:                         $userhash{$key} = $value;
                   2337:                         if ($key eq 'username') {
                   2338:                             $uname = $value;
                   2339:                         } elsif ($key eq 'domain') {
                   2340:                             $udom = $value;
1.911     raeburn  2341:                         }
1.899     raeburn  2342:                     }
                   2343:                     $results{$uname.':'.$udom} = \%userhash;
                   2344:                 }
                   2345:             }
                   2346:         }
                   2347:     }
                   2348:     return %results;
                   2349: }
                   2350: 
1.912     raeburn  2351: sub get_instuser {
                   2352:     my ($udom,$uname,$id) = @_;
                   2353:     my $homeserver = &domain($udom,'primary');
                   2354:     my ($outcome,%results);
                   2355:     if ($homeserver ne '') {
                   2356:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2357:                            &escape($id).':'.&escape($udom),$homeserver);
                   2358:         my $host=&hostname($homeserver);
                   2359:         if ($queryid !~/^\Q$host\E\_/) {
                   2360:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2361:             return;
                   2362:         }
                   2363:         my $response = &get_query_reply($queryid);
                   2364:         my $maxtries = 5;
                   2365:         my $tries = 1;
                   2366:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2367:             $response = &get_query_reply($queryid);
                   2368:             $tries ++;
                   2369:         }
                   2370:         if (!&error($response) && $response ne 'refused') {
                   2371:             if ($response eq 'unavailable') {
                   2372:                 $outcome = $response;
                   2373:             } else {
                   2374:                 $outcome = 'ok';
                   2375:                 my @matches = split(/\n/,$response);
                   2376:                 foreach my $match (@matches) {
                   2377:                     my ($key,$value) = split(/=/,$match);
                   2378:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2379:                 }
                   2380:             }
                   2381:         }
                   2382:     }
                   2383:     my %userinfo;
                   2384:     if (ref($results{$uname}) eq 'HASH') {
                   2385:         %userinfo = %{$results{$uname}};
                   2386:     } 
                   2387:     return ($outcome,%userinfo);
                   2388: }
                   2389: 
1.1290    raeburn  2390: sub get_multiple_instusers {
                   2391:     my ($udom,$users,$caller) = @_;
                   2392:     my ($outcome,$results);
                   2393:     if (ref($users) eq 'HASH') {
                   2394:         my $count = keys(%{$users}); 
                   2395:         my $requested = &freeze_escape($users);
                   2396:         my $homeserver = &domain($udom,'primary');
                   2397:         if ($homeserver ne '') {
                   2398:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2399:             my $host=&hostname($homeserver);
                   2400:             if ($queryid !~/^\Q$host\E\_/) {
                   2401:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2402:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2403:                 return ($outcome,$results);
                   2404:             }
                   2405:             my $response = &get_query_reply($queryid);
                   2406:             my $maxtries = 5;
                   2407:             if ($count > 100) {
                   2408:                 $maxtries = 1+int($count/20);
                   2409:             }
                   2410:             my $tries = 1;
                   2411:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2412:                 $response = &get_query_reply($queryid);
                   2413:                 $tries ++;
                   2414:             }
                   2415:             if ($response eq '') {
                   2416:                 $results = {};
                   2417:                 foreach my $key (keys(%{$users})) {
                   2418:                     my ($uname,$id);
                   2419:                     if ($caller eq 'id') {
                   2420:                         $id = $key;
                   2421:                     } else {
                   2422:                         $uname = $key;
                   2423:                     }
                   2424:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2425:                     $outcome = $resp;
1.1290    raeburn  2426:                     if ($resp eq 'ok') {
                   2427:                         %{$results} = (%{$results}, %info);
                   2428:                     } else {
                   2429:                         last;
                   2430:                     }
                   2431:                 }
                   2432:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2433:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2434:                     $outcome = $response;
                   2435:                 } else {
1.1291    raeburn  2436:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2437:                     if ($outcome eq 'ok') {
                   2438:                         $results = &thaw_unescape($userdata); 
                   2439:                     }
                   2440:                 }
                   2441:             }
                   2442:         }
                   2443:     }
                   2444:     return ($outcome,$results);
                   2445: }
                   2446: 
1.912     raeburn  2447: sub inst_rulecheck {
1.923     raeburn  2448:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2449:     my %returnhash;
                   2450:     if ($udom ne '') {
                   2451:         if (ref($rules) eq 'ARRAY') {
                   2452:             @{$rules} = map {&escape($_);} (@{$rules});
                   2453:             my $rulestr = join(':',@{$rules});
                   2454:             my $homeserver=&domain($udom,'primary');
                   2455:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2456:                 my $response;
                   2457:                 if ($item eq 'username') {                
                   2458:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2459:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2460:                                               $homeserver));
1.923     raeburn  2461:                 } elsif ($item eq 'id') {
                   2462:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2463:                                               ':'.&escape($id).':'.$rulestr,
                   2464:                                               $homeserver));
1.945     raeburn  2465:                 } elsif ($item eq 'selfcreate') {
                   2466:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2467:                                                &escape($udom).':'.&escape($uname).
                   2468:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2469:                 }
1.912     raeburn  2470:                 if ($response ne 'refused') {
                   2471:                     my @pairs=split(/\&/,$response);
                   2472:                     foreach my $item (@pairs) {
                   2473:                         my ($key,$value)=split(/=/,$item,2);
                   2474:                         $key = &unescape($key);
                   2475:                         next if ($key =~ /^error: 2 /);
                   2476:                         $returnhash{$key}=&thaw_unescape($value);
                   2477:                     }
                   2478:                 }
                   2479:             }
                   2480:         }
                   2481:     }
                   2482:     return %returnhash;
                   2483: }
                   2484: 
                   2485: sub inst_userrules {
1.923     raeburn  2486:     my ($udom,$check) = @_;
1.912     raeburn  2487:     my (%ruleshash,@ruleorder);
                   2488:     if ($udom ne '') {
                   2489:         my $homeserver=&domain($udom,'primary');
                   2490:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2491:             my $response;
                   2492:             if ($check eq 'id') {
                   2493:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2494:                                  $homeserver);
1.943     raeburn  2495:             } elsif ($check eq 'email') {
                   2496:                 $response=&reply('instemailrules:'.&escape($udom),
                   2497:                                  $homeserver);
1.923     raeburn  2498:             } else {
                   2499:                 $response=&reply('instuserrules:'.&escape($udom),
                   2500:                                  $homeserver);
                   2501:             }
1.912     raeburn  2502:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2503:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2504:                 ($response ne 'no_such_host')) {
                   2505:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2506:                 my @pairs=split(/\&/,$hashitems);
                   2507:                 foreach my $item (@pairs) {
                   2508:                     my ($key,$value)=split(/=/,$item,2);
                   2509:                     $key = &unescape($key);
                   2510:                     next if ($key =~ /^error: 2 /);
                   2511:                     $ruleshash{$key}=&thaw_unescape($value);
                   2512:                 }
                   2513:                 my @esc_order = split(/\&/,$orderitems);
                   2514:                 foreach my $item (@esc_order) {
                   2515:                     push(@ruleorder,&unescape($item));
                   2516:                 }
                   2517:             }
                   2518:         }
                   2519:     }
                   2520:     return (\%ruleshash,\@ruleorder);
                   2521: }
                   2522: 
1.976     raeburn  2523: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2524: 
                   2525: sub get_domain_defaults {
1.1240    raeburn  2526:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2527:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2528:     my $cachetime = 60*60*24;
1.1240    raeburn  2529:     unless ($ignore_cache) {
                   2530:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2531:         if (defined($cached)) {
                   2532:             if (ref($result) eq 'HASH') {
                   2533:                 return %{$result};
                   2534:             }
1.943     raeburn  2535:         }
                   2536:     }
                   2537:     my %domdefaults;
                   2538:     my %domconfig =
1.989     raeburn  2539:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2540:                                   'requestcourses','inststatus',
1.1183    raeburn  2541:                                   'coursedefaults','usersessions',
1.1258    raeburn  2542:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2543:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2544:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2545:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2546:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2547:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2548:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2549:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2550:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2551:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2552:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2553:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2554:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2555:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2556:     } else {
                   2557:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2558:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2559:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2560:     }
1.976     raeburn  2561:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2562:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2563:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2564:         } else {
                   2565:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2566:         }
1.1177    raeburn  2567:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2568:         foreach my $item (@usertools) {
                   2569:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2570:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2571:             }
                   2572:         }
1.1229    raeburn  2573:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2574:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2575:         }
1.976     raeburn  2576:     }
1.985     raeburn  2577:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2578:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2579:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2580:         }
                   2581:     }
1.1183    raeburn  2582:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2583:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2584:     }
1.989     raeburn  2585:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2586:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2587:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2588:         }
                   2589:     }
1.1047    raeburn  2590:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2591:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2592:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2593:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2594:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2595:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2596:         }
1.1254    raeburn  2597:         foreach my $type (@coursetypes) {
                   2598:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2599:                 unless ($type eq 'community') {
                   2600:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2601:                 }
                   2602:             }
                   2603:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2604:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2605:             }
1.1277    raeburn  2606:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2607:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2608:                     $domdefaults{$type.'postsubtimeout'} = 
                   2609:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2610:                 }
                   2611:             }
1.1230    raeburn  2612:         }
1.1286    raeburn  2613:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2614:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2615:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2616:                 if (@clonecodes) {
                   2617:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2618:                 }
                   2619:             }
                   2620:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2621:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2622:         }
1.1356    raeburn  2623:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2624:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2625:         } 
1.1047    raeburn  2626:     }
1.1073    raeburn  2627:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2628:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2629:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2630:         }
                   2631:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2632:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2633:         }
1.1279    raeburn  2634:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2635:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2636:         }
1.1073    raeburn  2637:     }
1.1254    raeburn  2638:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2639:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2640:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2641:                             'approval','limit');
                   2642:             foreach my $type (@coursetypes) {
                   2643:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2644:                     my @mgrdc = ();
                   2645:                     foreach my $item (@settings) {
                   2646:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2647:                             push(@mgrdc,$item);
                   2648:                         }
                   2649:                     }
                   2650:                     if (@mgrdc) {
                   2651:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2652:                     }
                   2653:                 }
                   2654:             }
                   2655:         }
                   2656:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2657:             foreach my $type (@coursetypes) {
                   2658:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2659:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2660:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2661:                     }
                   2662:                 }
                   2663:             }
                   2664:         }
                   2665:     }
1.1258    raeburn  2666:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2667:         $domdefaults{'catauth'} = 'std';
                   2668:         $domdefaults{'catunauth'} = 'std';
                   2669:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2670:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2671:         }
                   2672:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2673:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2674:         }
                   2675:     }
1.1315    raeburn  2676:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2677:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2678:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2679:         }
1.1338    raeburn  2680:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2681:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2682:         }
                   2683:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2684:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2685:         }
                   2686:     }
1.1320    raeburn  2687:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2688:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2689:         foreach my $prefix (@prefixes) {
                   2690:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2691:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2692:             }
                   2693:         }
                   2694:     }
1.1314    raeburn  2695:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2696:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2697:     }
1.1332    raeburn  2698:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2699:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2700:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2701:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2702:         }
                   2703:     }
1.1219    raeburn  2704:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2705:     return %domdefaults;
                   2706: }
                   2707: 
1.1311    raeburn  2708: sub course_portal_url {
                   2709:     my ($cnum,$cdom) = @_;
                   2710:     my $chome = &homeserver($cnum,$cdom);
                   2711:     my $hostname = &hostname($chome);
                   2712:     my $protocol = $protocol{$chome};
                   2713:     $protocol = 'http' if ($protocol ne 'https');
                   2714:     my %domdefaults = &get_domain_defaults($cdom);
                   2715:     my $firsturl;
                   2716:     if ($domdefaults{'portal_def'}) {
                   2717:         $firsturl = $domdefaults{'portal_def'};
                   2718:     } else {
                   2719:         $firsturl = $protocol.'://'.$hostname;
                   2720:     }
                   2721:     return $firsturl;
                   2722: }
                   2723: 
1.344     www      2724: # --------------------------------------------------- Assign a key to a student
                   2725: 
                   2726: sub assign_access_key {
1.364     www      2727: #
                   2728: # a valid key looks like uname:udom#comments
                   2729: # comments are being appended
                   2730: #
1.498     www      2731:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2732:     $kdom=
1.620     albertel 2733:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2734:     $knum=
1.620     albertel 2735:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2736:     $cdom=
1.620     albertel 2737:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2738:     $cnum=
1.620     albertel 2739:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2740:     $udom=$env{'user.name'} unless (defined($udom));
                   2741:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2742:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2743:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2744:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2745:                                                   # assigned to this person
                   2746:                                                   # - this should not happen,
1.345     www      2747:                                                   # unless something went wrong
                   2748:                                                   # the first time around
                   2749: # ready to assign
1.364     www      2750:         $logentry=$1.'; '.$logentry;
1.496     www      2751:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2752:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2753: # key now belongs to user
1.346     www      2754: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2755:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2756:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2757:                 return 'ok';
                   2758:             } else {
                   2759:                 return 
                   2760:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2761: 	    }
                   2762:         } else {
                   2763:             return 'error: Could not assign key, try again later.';
                   2764:         }
1.364     www      2765:     } elsif (!$existing{$ckey}) {
1.345     www      2766: # the key does not exist
                   2767: 	return 'error: The key does not exist';
                   2768:     } else {
                   2769: # the key is somebody else's
                   2770: 	return 'error: The key is already in use';
                   2771:     }
1.344     www      2772: }
                   2773: 
1.364     www      2774: # ------------------------------------------ put an additional comment on a key
                   2775: 
                   2776: sub comment_access_key {
                   2777: #
                   2778: # a valid key looks like uname:udom#comments
                   2779: # comments are being appended
                   2780: #
                   2781:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2782:     $cdom=
1.620     albertel 2783:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2784:     $cnum=
1.620     albertel 2785:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2786:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2787:     if ($existing{$ckey}) {
                   2788:         $existing{$ckey}.='; '.$logentry;
                   2789: # ready to assign
1.367     www      2790:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2791:                                                  $cdom,$cnum) eq 'ok') {
                   2792: 	    return 'ok';
                   2793:         } else {
                   2794: 	    return 'error: Count not store comment.';
                   2795:         }
                   2796:     } else {
                   2797: # the key does not exist
                   2798: 	return 'error: The key does not exist';
                   2799:     }
                   2800: }
                   2801: 
1.344     www      2802: # ------------------------------------------------------ Generate a set of keys
                   2803: 
                   2804: sub generate_access_keys {
1.364     www      2805:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2806:     $cdom=
1.620     albertel 2807:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2808:     $cnum=
1.620     albertel 2809:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2810:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2811:     unless (($cdom) && ($cnum)) { return 0; }
                   2812:     if ($number>10000) { return 0; }
                   2813:     sleep(2); # make sure don't get same seed twice
                   2814:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2815:     my $total=0;
                   2816:     for (my $i=1;$i<=$number;$i++) {
                   2817:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2818:                   sprintf("%lx",int(100000*rand)).'-'.
                   2819:                   sprintf("%lx",int(100000*rand));
                   2820:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2821:        $newkey=~s/0/h/g; # and also 0 and O
                   2822:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2823:        if ($existing{$newkey}) {
                   2824:            $i--;
                   2825:        } else {
1.364     www      2826: 	  if (&put('accesskeys',
                   2827:               { $newkey => '# generated '.localtime().
1.620     albertel 2828:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2829:                            '; '.$logentry },
                   2830: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2831:               $total++;
                   2832: 	  }
                   2833:        }
                   2834:     }
1.620     albertel 2835:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2836:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2837:     return $total;
                   2838: }
                   2839: 
                   2840: # ------------------------------------------------------- Validate an accesskey
                   2841: 
                   2842: sub validate_access_key {
                   2843:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2844:     $cdom=
1.620     albertel 2845:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2846:     $cnum=
1.620     albertel 2847:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2848:     $udom=$env{'user.domain'} unless (defined($udom));
                   2849:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2850:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2851:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2852: }
                   2853: 
                   2854: # ------------------------------------- Find the section of student in a course
1.652     albertel 2855: sub devalidate_getsection_cache {
                   2856:     my ($udom,$unam,$courseid)=@_;
                   2857:     my $hashid="$udom:$unam:$courseid";
                   2858:     &devalidate_cache_new('getsection',$hashid);
                   2859: }
1.298     matthew  2860: 
1.815     albertel 2861: sub courseid_to_courseurl {
                   2862:     my ($courseid) = @_;
                   2863:     #already url style courseid
                   2864:     return $courseid if ($courseid =~ m{^/});
                   2865: 
                   2866:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2867: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2868: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2869: 	return "/$cdom/$cnum";
                   2870:     }
                   2871: 
                   2872:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2873:     if (exists($courseinfo{'num'})) {
                   2874: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2875:     }
                   2876: 
                   2877:     return undef;
                   2878: }
                   2879: 
1.298     matthew  2880: sub getsection {
                   2881:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2882:     my $cachetime=1800;
1.551     albertel 2883: 
                   2884:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2885:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2886:     if (defined($cached)) { return $result; }
                   2887: 
1.298     matthew  2888:     my %Pending; 
                   2889:     my %Expired;
                   2890:     #
                   2891:     # Each role can either have not started yet (pending), be active, 
                   2892:     #    or have expired.
                   2893:     #
                   2894:     # If there is an active role, we are done.
                   2895:     #
                   2896:     # If there is more than one role which has not started yet, 
                   2897:     #     choose the one which will start sooner
                   2898:     # If there is one role which has not started yet, return it.
                   2899:     #
                   2900:     # If there is more than one expired role, choose the one which ended last.
                   2901:     # If there is a role which has expired, return it.
                   2902:     #
1.815     albertel 2903:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2904:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2905:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2906:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2907:         my $section=$1;
                   2908:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2909:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2910:         my $now=time;
1.548     albertel 2911:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2912:             $Expired{$end}=$section;
                   2913:             next;
                   2914:         }
1.548     albertel 2915:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2916:             $Pending{$start}=$section;
                   2917:             next;
                   2918:         }
1.599     albertel 2919:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2920:     }
                   2921:     #
                   2922:     # Presumedly there will be few matching roles from the above
                   2923:     # loop and the sorting time will be negligible.
                   2924:     if (scalar(keys(%Pending))) {
                   2925:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2926:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2927:     } 
                   2928:     if (scalar(keys(%Expired))) {
                   2929:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2930:         my $time = pop(@sorted);
1.599     albertel 2931:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2932:     }
1.599     albertel 2933:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2934: }
1.70      www      2935: 
1.599     albertel 2936: sub save_cache {
                   2937:     &purge_remembered();
1.722     albertel 2938:     #&Apache::loncommon::validate_page();
1.620     albertel 2939:     undef(%env);
1.780     albertel 2940:     undef($env_loaded);
1.599     albertel 2941: }
1.452     albertel 2942: 
1.599     albertel 2943: my $to_remember=-1;
                   2944: my %remembered;
                   2945: my %accessed;
                   2946: my $kicks=0;
                   2947: my $hits=0;
1.849     albertel 2948: sub make_key {
                   2949:     my ($name,$id) = @_;
1.872     albertel 2950:     if (length($id) > 65 
                   2951: 	&& length(&escape($id)) > 200) {
                   2952: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2953:     }
1.849     albertel 2954:     return &escape($name.':'.$id);
                   2955: }
                   2956: 
1.599     albertel 2957: sub devalidate_cache_new {
                   2958:     my ($name,$id,$debug) = @_;
                   2959:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2960:     my $remembered_id=$name.':'.$id;
1.849     albertel 2961:     $id=&make_key($name,$id);
1.599     albertel 2962:     $memcache->delete($id);
1.1319    damieng  2963:     delete($remembered{$remembered_id});
                   2964:     delete($accessed{$remembered_id});
1.599     albertel 2965: }
                   2966: 
                   2967: sub is_cached_new {
                   2968:     my ($name,$id,$debug) = @_;
1.1319    damieng  2969:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2970:     if (exists($remembered{$remembered_id})) {
                   2971: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2972: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2973: 	$hits++;
1.1319    damieng  2974: 	return ($remembered{$remembered_id},1);
1.599     albertel 2975:     }
1.1319    damieng  2976:     $id=&make_key($name,$id);
1.599     albertel 2977:     my $value = $memcache->get($id);
                   2978:     if (!(defined($value))) {
                   2979: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2980: 	return (undef,undef);
1.416     albertel 2981:     }
1.599     albertel 2982:     if ($value eq '__undef__') {
                   2983: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2984: 	$value=undef;
                   2985:     }
1.1319    damieng  2986:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2987:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2988:     return ($value,1);
                   2989: }
                   2990: 
                   2991: sub do_cache_new {
                   2992:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2993:     my $remembered_id=$name.':'.$id;
1.849     albertel 2994:     $id=&make_key($name,$id);
1.599     albertel 2995:     my $setvalue=$value;
                   2996:     if (!defined($setvalue)) {
                   2997: 	$setvalue='__undef__';
                   2998:     }
1.623     albertel 2999:     if (!defined($time) ) {
                   3000: 	$time=600;
                   3001:     }
1.599     albertel 3002:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3003:     my $result = $memcache->set($id,$setvalue,$time);
                   3004:     if (! $result) {
1.872     albertel 3005: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3006: 	$memcache->disconnect_all();
1.872     albertel 3007:     }
1.600     albertel 3008:     # need to make a copy of $value
1.1319    damieng  3009:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3010:     return $value;
                   3011: }
                   3012: 
                   3013: sub make_room {
1.1319    damieng  3014:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3015: 
1.1319    damieng  3016:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3017:                                     : $value;
1.599     albertel 3018:     if ($to_remember<0) { return; }
1.1319    damieng  3019:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3020:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3021:     my $to_kick;
                   3022:     my $max_time=0;
                   3023:     foreach my $other (keys(%accessed)) {
                   3024: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3025: 	    $to_kick=$other;
                   3026: 	    $max_time=&tv_interval($accessed{$other});
                   3027: 	}
                   3028:     }
                   3029:     delete($remembered{$to_kick});
                   3030:     delete($accessed{$to_kick});
                   3031:     $kicks++;
                   3032:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3033:     return;
                   3034: }
                   3035: 
1.599     albertel 3036: sub purge_remembered {
1.604     albertel 3037:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3038:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3039:     undef(%remembered);
                   3040:     undef(%accessed);
1.428     albertel 3041: }
1.70      www      3042: # ------------------------------------- Read an entry from a user's environment
                   3043: 
                   3044: sub userenvironment {
                   3045:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3046:     my $items;
                   3047:     foreach my $item (@what) {
                   3048:         $items.=&escape($item).'&';
                   3049:     }
                   3050:     $items=~s/\&$//;
1.70      www      3051:     my %returnhash=();
1.1009    raeburn  3052:     my $uhome = &homeserver($unam,$udom);
                   3053:     unless ($uhome eq 'no_host') {
                   3054:         my @answer=split(/\&/, 
                   3055:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3056:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3057:             return %returnhash;
                   3058:         }
1.1009    raeburn  3059:         my $i;
                   3060:         for ($i=0;$i<=$#what;$i++) {
                   3061: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3062:         }
1.70      www      3063:     }
                   3064:     return %returnhash;
1.1       albertel 3065: }
                   3066: 
1.617     albertel 3067: # ---------------------------------------------------------- Get a studentphoto
                   3068: sub studentphoto {
                   3069:     my ($udom,$unam,$ext) = @_;
                   3070:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3071:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3072:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3073:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3074:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3075:             } else {
                   3076:                 my ($result,$perm_reqd)=
1.707     albertel 3077: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3078:                 if ($result eq 'ok') {
                   3079:                     if (!($perm_reqd eq 'yes')) {
                   3080:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3081:                     }
                   3082:                 }
                   3083:             }
                   3084:         }
                   3085:     } else {
                   3086:         my ($result,$perm_reqd) = 
1.707     albertel 3087: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3088:         if ($result eq 'ok') {
                   3089:             if (!($perm_reqd eq 'yes')) {
                   3090:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3091:             }
                   3092:         }
                   3093:     }
                   3094:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3095: }
                   3096: 
                   3097: sub retrievestudentphoto {
                   3098:     my ($udom,$unam,$ext,$type) = @_;
                   3099:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3100:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3101:     if ($ret eq 'ok') {
                   3102:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3103:         if ($type eq 'thumbnail') {
                   3104:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3105:         }
                   3106:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3107:         return $tokenurl;
                   3108:     } else {
                   3109:         if ($type eq 'thumbnail') {
                   3110:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3111:         } else { 
                   3112:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3113:         }
1.617     albertel 3114:     }
                   3115: }
                   3116: 
1.263     www      3117: # -------------------------------------------------------------------- New chat
                   3118: 
                   3119: sub chatsend {
1.724     raeburn  3120:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3121:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3122:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3123:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3124:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3125: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3126: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3127: }
                   3128: 
                   3129: # ------------------------------------------ Find current version of a resource
                   3130: 
                   3131: sub getversion {
                   3132:     my $fname=&clutter(shift);
1.1189    raeburn  3133:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3134:     return &currentversion(&filelocation('',$fname));
                   3135: }
                   3136: 
                   3137: sub currentversion {
                   3138:     my $fname=shift;
                   3139:     my $author=$fname;
                   3140:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3141:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3142:     my $home=&homeserver($uname,$udom);
1.292     www      3143:     if ($home eq 'no_host') { 
                   3144:         return -1; 
                   3145:     }
1.1112    www      3146:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3147:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3148: 	return -1;
                   3149:     }
1.1112    www      3150:     return $answer;
1.263     www      3151: }
                   3152: 
1.1111    www      3153: #
                   3154: # Return special version number of resource if set by override, empty otherwise
                   3155: #
                   3156: sub usedversion {
                   3157:     my $fname=shift;
                   3158:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3159:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3160:     if ($urlversion) { return $urlversion; }
                   3161:     return '';
                   3162: }
                   3163: 
1.1       albertel 3164: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3165: 
1.1       albertel 3166: sub subscribe {
                   3167:     my $fname=shift;
1.761     raeburn  3168:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3169:     $fname=~s/[\n\r]//g;
1.1       albertel 3170:     my $author=$fname;
                   3171:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3172:     my ($udom,$uname)=split(/\//,$author);
                   3173:     my $home=homeserver($uname,$udom);
1.335     albertel 3174:     if ($home eq 'no_host') {
                   3175:         return 'not_found';
1.1       albertel 3176:     }
                   3177:     my $answer=reply("sub:$fname",$home);
1.64      www      3178:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3179: 	$answer.=' by '.$home;
                   3180:     }
1.1       albertel 3181:     return $answer;
                   3182: }
                   3183:     
1.8       www      3184: # -------------------------------------------------------------- Replicate file
                   3185: 
                   3186: sub repcopy {
                   3187:     my $filename=shift;
1.23      www      3188:     $filename=~s/\/+/\//g;
1.1142    raeburn  3189:     my $londocroot = $perlvar{'lonDocRoot'};
                   3190:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3191:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3192:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3193: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3194: 	return &repcopy_userfile($filename);
                   3195:     }
1.532     albertel 3196:     $filename=~s/[\n\r]//g;
1.8       www      3197:     my $transname="$filename.in.transfer";
1.828     www      3198: # FIXME: this should flock
1.607     raeburn  3199:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3200:     my $remoteurl=subscribe($filename);
1.64      www      3201:     if ($remoteurl =~ /^con_lost by/) {
                   3202: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3203:            return 'unavailable';
1.8       www      3204:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3205: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3206: 	   return 'not_found';
1.64      www      3207:     } elsif ($remoteurl =~ /^rejected by/) {
                   3208: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3209:            return 'forbidden';
1.20      www      3210:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3211:            return 'ok';
1.8       www      3212:     } else {
1.290     www      3213:         my $author=$filename;
                   3214:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3215:         my ($udom,$uname)=split(/\//,$author);
                   3216:         my $home=homeserver($uname,$udom);
                   3217:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3218:            my @parts=split(/\//,$filename);
                   3219:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3220:            if ($path ne "$londocroot/res") {
1.8       www      3221:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3222: 	       return 'bad_request';
1.8       www      3223:            }
                   3224:            my $count;
                   3225:            for ($count=5;$count<$#parts;$count++) {
                   3226:                $path.="/$parts[$count]";
                   3227:                if ((-e $path)!=1) {
                   3228: 		   mkdir($path,0777);
                   3229:                }
                   3230:            }
                   3231:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3232:            my $response;
                   3233:            if ($remoteurl =~ m{/raw/}) {
                   3234:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3235:            } else {
                   3236:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3237:            }
1.8       www      3238:            if ($response->is_error()) {
                   3239: 	       unlink($transname);
                   3240:                my $message=$response->status_line;
1.672     albertel 3241:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3242:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3243:                return 'unavailable';
1.8       www      3244:            } else {
1.16      www      3245: 	       if ($remoteurl!~/\.meta$/) {
                   3246:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3247:                   my $mresponse;
                   3248:                   if ($remoteurl =~ m{/raw/}) {
                   3249:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3250:                   } else {
                   3251:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3252:                   }
1.16      www      3253:                   if ($mresponse->is_error()) {
                   3254: 		      unlink($filename.'.meta');
                   3255:                       &logthis(
1.672     albertel 3256:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3257:                   }
                   3258: 	       }
1.8       www      3259:                rename($transname,$filename);
1.607     raeburn  3260:                return 'ok';
1.8       www      3261:            }
1.290     www      3262:        }
1.8       www      3263:     }
1.330     www      3264: }
                   3265: 
                   3266: # ------------------------------------------------ Get server side include body
                   3267: sub ssi_body {
1.381     albertel 3268:     my ($filelink,%form)=@_;
1.606     matthew  3269:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3270:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3271:     }
1.953     www      3272:     my $output='';
                   3273:     my $response;
1.980     raeburn  3274:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3275:        ($output,$response)=&externalssi($filelink);
1.953     www      3276:     } else {
1.1004    droeschl 3277:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3278:        $filelink .= 'inhibitmenu=yes';
1.953     www      3279:        ($output,$response)=&ssi($filelink,%form);
                   3280:     }
1.778     albertel 3281:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3282:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3283:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3284:     if (wantarray) {
                   3285:         return ($output, $response);
                   3286:     } else {
                   3287:         return $output;
                   3288:     }
1.8       www      3289: }
                   3290: 
1.15      www      3291: # --------------------------------------------------------- Server Side Include
                   3292: 
1.782     albertel 3293: sub absolute_url {
                   3294:     my ($host_name) = @_;
                   3295:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3296:     if ($host_name eq '') {
                   3297: 	$host_name = $ENV{'SERVER_NAME'};
                   3298:     }
                   3299:     return $protocol.$host_name;
                   3300: }
                   3301: 
1.942     foxr     3302: #
                   3303: #   Server side include.
                   3304: # Parameters:
                   3305: #  fn     Possibly encrypted resource name/id.
                   3306: #  form   Hash that describes how the rendering should be done
                   3307: #         and other things.
1.944     foxr     3308: # Returns:
1.950     raeburn  3309: #   Scalar context: The content of the response.
                   3310: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3311: #     
1.15      www      3312: sub ssi {
                   3313: 
1.944     foxr     3314:     my ($fn,%form)=@_;
1.23      www      3315:     my $request;
1.711     albertel 3316: 
                   3317:     $form{'no_update_last_known'}=1;
1.895     albertel 3318:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3319:     if (%form) {
1.782     albertel 3320:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3321:       $request->content(join('&',map { 
                   3322:             my $name = escape($_);
                   3323:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3324:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3325:             : &escape($form{$_}) );    
                   3326:         } keys(%form)));
1.23      www      3327:     } else {
1.782     albertel 3328:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3329:     }
                   3330: 
1.15      www      3331:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3332:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3333:     my $islocal;
                   3334:     if (($env{'request.course.id'}) &&
                   3335:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3336:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3337:         ($form{'grade_symb'} ne '') &&
                   3338:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3339:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3340:         $islocal = 1;
                   3341:     }
1.1384    raeburn  3342:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3343:                                                 '','','',$islocal);
1.1182    foxr     3344: 
1.944     foxr     3345:     if (wantarray) {
1.1345    raeburn  3346: 	return ($response->content, $response);
1.944     foxr     3347:     } else {
1.1345    raeburn  3348: 	return $response->content;
1.942     foxr     3349:     }
1.324     www      3350: }
                   3351: 
                   3352: sub externalssi {
                   3353:     my ($url)=@_;
                   3354:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3355:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3356:     if (wantarray) {
                   3357:         return ($response->content, $response);
                   3358:     } else {
                   3359:         return $response->content;
                   3360:     }
1.15      www      3361: }
1.254     www      3362: 
1.1354    raeburn  3363: 
                   3364: # If the local copy of a replicated resource is outdated, trigger a  
                   3365: # connection from the homeserver to flush the delayed queue. If no update 
                   3366: # happens, remove local copies of outdated resource (and corresponding
                   3367: # metadata file).
                   3368: 
1.1352    raeburn  3369: sub remove_stale_resfile {
                   3370:     my ($url) = @_;
1.1354    raeburn  3371:     my $removed;
1.1352    raeburn  3372:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3373:         my $audom = $1;
                   3374:         my $auname = $2;
1.1353    raeburn  3375:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3376:             my $homeserver = &homeserver($auname,$audom);
                   3377:             unless (($homeserver eq 'no_host') ||
                   3378:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3379:                 my $fname = &filelocation('',$url);
                   3380:                 if (-e $fname) {
                   3381:                     my $hostname = &hostname($homeserver);
                   3382:                     if ($hostname) {
1.1397    raeburn  3383:                         my $protocol = $protocol{$homeserver};
                   3384:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3385:                         my $uri = &declutter($url);
                   3386:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3387:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3388:                         if ($response->is_success()) {
                   3389:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3390:                             my $locmodtime = (stat($fname))[9];
                   3391:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3392:                                 my $stale;
                   3393:                                 my $answer = &reply('pong',$homeserver);
                   3394:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3395:                                     sleep(0.2);
                   3396:                                     $locmodtime = (stat($fname))[9];
                   3397:                                     if ($locmodtime < $remmodtime) {
                   3398:                                         my $posstransfer = $fname.'.in.transfer';
                   3399:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3400:                                             $removed = 1;
                   3401:                                         } else {
                   3402:                                             $stale = 1;
                   3403:                                         }
                   3404:                                     } else {
                   3405:                                         $removed = 1;
                   3406:                                     }
                   3407:                                 } else {
                   3408:                                     $stale = 1;
                   3409:                                 }
                   3410:                                 if ($stale) {
                   3411:                                     unlink($fname);
                   3412:                                     if ($uri!~/\.meta$/) {
                   3413:                                         unlink($fname.'.meta');
                   3414:                                     }
                   3415:                                     &reply("unsub:$fname",$homeserver);
                   3416:                                     $removed = 1;
1.1352    raeburn  3417:                                 }
                   3418:                             }
                   3419:                         }
                   3420:                     }
                   3421:                 }
                   3422:             }
                   3423:         }
                   3424:     }
1.1354    raeburn  3425:     return $removed;
1.1352    raeburn  3426: }
                   3427: 
1.492     albertel 3428: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3429: 
                   3430: sub allowuploaded {
                   3431:     my ($srcurl,$url)=@_;
                   3432:     $url=&clutter(&declutter($url));
                   3433:     my $dir=$url;
                   3434:     $dir=~s/\/[^\/]+$//;
                   3435:     my %httpref=();
                   3436:     my $httpurl=&hreflocation('',$url);
                   3437:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3438:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3439: }
1.477     raeburn  3440: 
1.1193    raeburn  3441: #
                   3442: # Determine if the current user should be able to edit a particular resource,
                   3443: # when viewing in course context.
                   3444: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3445: #     Functions.
                   3446: # (b) When displaying folder contents in course editor, used to determine if
                   3447: #     "Edit" link will be displayed alongside resource.
                   3448: #
1.1196    raeburn  3449: #  input: six args -- filename (decluttered), course number, course domain,
                   3450: #                   url, symb (if registered) and group (if this is a group
                   3451: #                   item -- e.g., bulletin board, group page etc.).
                   3452: #  output: array of five scalars -- 
1.1193    raeburn  3453: #          $cfile -- url for file editing if editable on current server
                   3454: #          $home -- homeserver of resource (i.e., for author if published,
                   3455: #                                           or course if uploaded.).
                   3456: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3457: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3458: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3459: #
                   3460: 
                   3461: sub can_edit_resource {
1.1194    raeburn  3462:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3463:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3464: #
                   3465: # For aboutme pages user can only edit his/her own.
                   3466: #
1.1199    raeburn  3467:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3468:         my ($sdom,$sname) = ($1,$2);
                   3469:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3470:             $home = $env{'user.home'};
                   3471:             $cfile = $resurl;
                   3472:             if ($env{'form.forceedit'}) {
                   3473:                 $forceview = 1;
                   3474:             } else {
                   3475:                 $forceedit = 1;
                   3476:             }
                   3477:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3478:         } else {
                   3479:             return;
                   3480:         }
                   3481:     }
                   3482: 
                   3483:     if ($env{'request.course.id'}) {
                   3484:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3485:         if ($group ne '') {
                   3486: # if this is a group homepage or group bulletin board, check group privs
                   3487:             my $allowed = 0;
1.1197    raeburn  3488:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3489:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3490:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3491:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3492:                     $allowed = 1;
                   3493:                 }
1.1197    raeburn  3494:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3495:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3496:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3497:                     $allowed = 1;
                   3498:                 }
                   3499:             }
                   3500:             if ($allowed) {
                   3501:                 $home=&homeserver($cnum,$cdom);
                   3502:                 if ($env{'form.forceedit'}) {
                   3503:                     $forceview = 1;
                   3504:                 } else {
                   3505:                     $forceedit = 1;
                   3506:                 }
                   3507:                 $cfile = $resurl;
                   3508:             } else {
                   3509:                 return;
                   3510:             }
                   3511:         } else {
1.1208    raeburn  3512:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3513:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3514:                     return;
                   3515:                 }
                   3516:             } elsif (!$crsedit) {
1.1194    raeburn  3517: #
                   3518: # No edit allowed where CC has switched to student role.
                   3519: #
                   3520:                 return;
                   3521:             }
                   3522:         }
                   3523:     }
                   3524: 
1.1193    raeburn  3525:     if ($file ne '') {
                   3526:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3527:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3528:                 $uploaded = 1;
                   3529:                 $incourse = 1;
1.1193    raeburn  3530:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3531:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3532:                     if ($env{'form.forceedit'}) {
                   3533:                         $forceview = 1;
                   3534:                     } else {
                   3535:                         $forceedit = 1;
                   3536:                     }
1.1194    raeburn  3537:                 }
                   3538:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3539:                 $incourse = 1;
                   3540:                 if ($env{'form.forceedit'}) {
                   3541:                     $forceview = 1;
                   3542:                 } else {
                   3543:                     $forceedit = 1;
                   3544:                 }
                   3545:                 $cfile = $resurl;
                   3546:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3547:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3548:                     $incourse = 1;
                   3549:                     if ($env{'form.forceedit'}) {
                   3550:                         $forceview = 1;
                   3551:                     } else {
                   3552:                         $forceedit = 1;
                   3553:                     }
                   3554:                     $cfile = $resurl;
1.1199    raeburn  3555:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3556:                     $incourse = 1;
                   3557:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3558:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3559:                     $incourse = 1;
1.1199    raeburn  3560:                     if ($env{'form.forceedit'}) {
                   3561:                         $forceview = 1;
                   3562:                     } else {
                   3563:                         $forceedit = 1;
                   3564:                     }
                   3565:                     $cfile = $resurl;
1.1343    raeburn  3566:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3567:                     $incourse = 1;
                   3568:                     if ($env{'form.forceedit'}) {
                   3569:                         $forceview = 1;
                   3570:                     } else {
                   3571:                         $forceedit = 1;
                   3572:                     }
                   3573:                     $cfile = $resurl;
1.1208    raeburn  3574:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3575:                     $incourse = 1;
                   3576:                     if ($env{'form.forceedit'}) {
                   3577:                         $forceview = 1;
                   3578:                     } else {
                   3579:                         $forceedit = 1;
                   3580:                     }
                   3581:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3582:                 }
                   3583:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3584:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3585:                 if (&is_on_map($template)) { 
                   3586:                     $incourse = 1;
                   3587:                     $forceview = 1;
                   3588:                     $cfile = $template;
1.1193    raeburn  3589:                 }
1.1199    raeburn  3590:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3591:                     $incourse = 1;
                   3592:                     if ($env{'form.forceedit'}) {
                   3593:                         $forceview = 1;
                   3594:                     } else {
                   3595:                         $forceedit = 1;
                   3596:                     }
                   3597:                     $cfile = $resurl;
1.1343    raeburn  3598:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3599:                 $incourse = 1;
                   3600:                 if ($env{'form.forceedit'}) {
                   3601:                     $forceview = 1;
                   3602:                 } else {
                   3603:                     $forceedit = 1;
                   3604:                 }
                   3605:                 $cfile = $resurl;
1.1199    raeburn  3606:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3607:                 $incourse = 1;
                   3608:                 $forceview = 1;
                   3609:                 if ($symb) {
                   3610:                     my ($map,$id,$res)=&decode_symb($symb);
                   3611:                     $env{'request.symb'} = $symb;
                   3612:                     $cfile = &clutter($res);
                   3613:                 } else {
                   3614:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3615:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3616:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3617:                         $cfile = '/adm/wrapper'.$escfile;
                   3618:                     } else {
                   3619:                         $escfile =~ s{^http://}{};
                   3620:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3621:                     }
1.1199    raeburn  3622:                 }
1.1234    raeburn  3623:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3624:                 if ($env{'form.forceedit'}) {
                   3625:                     $forceview = 1;
                   3626:                 } else {
                   3627:                     $forceedit = 1;
                   3628:                 }
                   3629:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3630:             }
                   3631:         }
1.1194    raeburn  3632:         if ($uploaded || $incourse) {
                   3633:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3634:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3635:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3636:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3637:             # Check that the user has permission to edit this resource
                   3638:             my $setpriv = 1;
                   3639:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3640:             if (defined($cfudom)) {
                   3641:                 $home=&homeserver($cfuname,$cfudom);
                   3642:                 $cfile=$file;
                   3643:             }
                   3644:         }
1.1194    raeburn  3645:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3646:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3647:             my @ids=&current_machine_ids();
                   3648:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3649:                 $switchserver=1;
                   3650:             }
                   3651:         }
                   3652:     }
1.1194    raeburn  3653:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3654: }
                   3655: 
                   3656: sub is_course_upload {
                   3657:     my ($file,$cnum,$cdom) = @_;
                   3658:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3659:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3660:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3661:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3662:         return 1;
                   3663:     }
                   3664:     return;
                   3665: }
                   3666: 
1.1194    raeburn  3667: sub in_course {
1.1195    raeburn  3668:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3669:     if ($hideprivileged) {
                   3670:         my $skipuser;
1.1219    raeburn  3671:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3672:         my @possdoms = ($cdom);  
                   3673:         if ($coursehash{'checkforpriv'}) { 
                   3674:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3675:         }
                   3676:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3677:             $skipuser = 1;
                   3678:             if ($coursehash{'nothideprivileged'}) {
                   3679:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3680:                     my $user;
                   3681:                     if ($item =~ /:/) {
                   3682:                         $user = $item;
                   3683:                     } else {
                   3684:                         $user = join(':',split(/[\@]/,$item));
                   3685:                     }
                   3686:                     if ($user eq $uname.':'.$udom) {
                   3687:                         undef($skipuser);
                   3688:                         last;
                   3689:                     }
                   3690:                 }
                   3691:             }
                   3692:             if ($skipuser) {
                   3693:                 return 0;
                   3694:             }
                   3695:         }
                   3696:     }
1.1194    raeburn  3697:     $type ||= 'any';
                   3698:     if (!defined($cdom) || !defined($cnum)) {
                   3699:         my $cid  = $env{'request.course.id'};
                   3700:         $cdom = $env{'course.'.$cid.'.domain'};
                   3701:         $cnum = $env{'course.'.$cid.'.num'};
                   3702:     }
                   3703:     my $typesref;
1.1195    raeburn  3704:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3705:         $typesref = ['active','previous','future'];
                   3706:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3707:         $typesref = [$type];
                   3708:     }
                   3709:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3710:                               $typesref,undef,[$cdom]);
                   3711:     my ($tmp) = keys(%roles);
                   3712:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3713:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3714:     if (@course_roles > 0) {
                   3715:         return 1;
                   3716:     }
                   3717:     return 0;
                   3718: }
                   3719: 
1.478     albertel 3720: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3721: # input: action, courseID, current domain, intended
1.637     raeburn  3722: #        path to file, source of file, instruction to parse file for objects,
                   3723: #        ref to hash for embedded objects,
                   3724: #        ref to hash for codebase of java objects.
1.1095    raeburn  3725: #        reference to scalar to accommodate mime type determined
                   3726: #          from File::MMagic if $parser = parse.
1.637     raeburn  3727: #
1.485     raeburn  3728: # output: url to file (if action was uploaddoc), 
                   3729: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3730: #
1.478     albertel 3731: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3732: # course.
1.477     raeburn  3733: #
1.478     albertel 3734: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3735: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3736: #          course's home server.
1.477     raeburn  3737: #
1.478     albertel 3738: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3739: #          be copied from $source (current location) to 
                   3740: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3741: #         and will then be copied to
                   3742: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3743: #         course's home server.
1.485     raeburn  3744: #
1.481     raeburn  3745: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3746: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3747: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3748: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3749: #         in course's home server.
1.637     raeburn  3750: #
1.477     raeburn  3751: 
                   3752: sub process_coursefile {
1.1095    raeburn  3753:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3754:         $mimetype)=@_;
1.477     raeburn  3755:     my $fetchresult;
1.638     albertel 3756:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3757:     if ($action eq 'propagate') {
1.638     albertel 3758:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3759: 			     $home);
1.481     raeburn  3760:     } else {
1.477     raeburn  3761:         my $fpath = '';
                   3762:         my $fname = $file;
1.478     albertel 3763:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3764:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3765:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3766:         if ($action eq 'copy') {
                   3767:             if ($source eq '') {
                   3768:                 $fetchresult = 'no source file';
                   3769:                 return $fetchresult;
                   3770:             } else {
                   3771:                 my $destination = $filepath.'/'.$fname;
                   3772:                 rename($source,$destination);
                   3773:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3774:                                  $home);
1.481     raeburn  3775:             }
                   3776:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3777:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3778:             print $fh $env{'form.'.$source};
1.481     raeburn  3779:             close($fh);
1.637     raeburn  3780:             if ($parser eq 'parse') {
1.1024    raeburn  3781:                 my $mm = new File::MMagic;
1.1095    raeburn  3782:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3783:                 if ($type eq 'text/html') {
1.1024    raeburn  3784:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3785:                     unless ($parse_result eq 'ok') {
                   3786:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3787:                     }
1.637     raeburn  3788:                 }
1.1095    raeburn  3789:                 if (ref($mimetype)) {
                   3790:                     $$mimetype = $type;
                   3791:                 } 
1.637     raeburn  3792:             }
1.477     raeburn  3793:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3794:                                  $home);
1.481     raeburn  3795:             if ($fetchresult eq 'ok') {
                   3796:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3797:             } else {
                   3798:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3799:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3800:                 return '/adm/notfound.html';
                   3801:             }
1.477     raeburn  3802:         }
                   3803:     }
1.485     raeburn  3804:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3805:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3806:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3807:     }
                   3808:     return $fetchresult;
                   3809: }
                   3810: 
1.637     raeburn  3811: sub build_filepath {
                   3812:     my ($fpath) = @_;
                   3813:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3814:     unless ($fpath eq '') {
                   3815:         my @parts=split('/',$fpath);
                   3816:         foreach my $part (@parts) {
                   3817:             $filepath.= '/'.$part;
                   3818:             if ((-e $filepath)!=1) {
                   3819:                 mkdir($filepath,0777);
                   3820:             }
                   3821:         }
                   3822:     }
                   3823:     return $filepath;
                   3824: }
                   3825: 
                   3826: sub store_edited_file {
1.638     albertel 3827:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3828:     my $file = $primary_url;
                   3829:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3830:     my $fpath = '';
                   3831:     my $fname = $file;
                   3832:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3833:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3834:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3835:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3836:     print $fh $content;
                   3837:     close($fh);
1.638     albertel 3838:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3839:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3840: 			  $home);
1.637     raeburn  3841:     if ($$fetchresult eq 'ok') {
                   3842:         return '/uploaded/'.$fpath.'/'.$fname;
                   3843:     } else {
1.638     albertel 3844:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3845: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3846:         return '/adm/notfound.html';
                   3847:     }
                   3848: }
                   3849: 
1.531     albertel 3850: sub clean_filename {
1.831     albertel 3851:     my ($fname,$args)=@_;
1.315     www      3852: # Replace Windows backslashes by forward slashes
1.257     www      3853:     $fname=~s/\\/\//g;
1.831     albertel 3854:     if (!$args->{'keep_path'}) {
                   3855:         # Get rid of everything but the actual filename
                   3856: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3857:     }
1.315     www      3858: # Replace spaces by underscores
                   3859:     $fname=~s/\s+/\_/g;
1.1406  ! raeburn  3860: # Transliterate non-ascii text to ascii
        !          3861:     my $lang = &Apache::lonlocal::current_language();
        !          3862:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3863: # Replace all other weird characters by nothing
1.831     albertel 3864:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3865: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3866: # numbers
                   3867:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3868:     return $fname;
                   3869: }
1.1406  ! raeburn  3870: 
1.1051    raeburn  3871: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3872: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3873: # image with the same aspect ratio as the original, but with dimensions which do 
                   3874: # not exceed $resizewidth and $resizeheight.
                   3875:  
1.984     neumanie 3876: sub resizeImage {
1.1051    raeburn  3877:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3878:     my $ima = Image::Magick->new;
                   3879:     my $resized;
                   3880:     if (-e $img_path) {
                   3881:         $ima->Read($img_path);
                   3882:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3883:             my $width = $ima->Get('width');
                   3884:             my $height = $ima->Get('height');
                   3885:             if ($width > $resizewidth) {
                   3886: 	        my $factor = $width/$resizewidth;
                   3887:                 my $newheight = $height/$factor;
                   3888:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3889:                 $resized = 1;
                   3890:             }
                   3891:         }
                   3892:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3893:             my $width = $ima->Get('width');
                   3894:             my $height = $ima->Get('height');
                   3895:             if ($height > $resizeheight) {
                   3896:                 my $factor = $height/$resizeheight;
                   3897:                 my $newwidth = $width/$factor;
                   3898:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3899:                 $resized = 1;
                   3900:             }
                   3901:         }
                   3902:         if ($resized) {
                   3903:             $ima->Write($img_path);
                   3904:         }
                   3905:     }
                   3906:     return;
1.977     amueller 3907: }
                   3908: 
1.608     albertel 3909: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3910: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3911: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3912: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  3913: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  3914: #                   if 'coursedoc': upload to the current course
                   3915: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3916: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3917: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3918: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  3919: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3920: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3921: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   3922: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3923: #        $allfiles - reference to hash for embedded objects
                   3924: #        $codebase - reference to hash for codebase of java objects
                   3925: #        $desuname - username for permanent storage of uploaded file
                   3926: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3927: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3928: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3929: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3930: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3931: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3932: #                    from File::MMagic.
1.858     raeburn  3933: # 
1.686     albertel 3934: # output: url of file in userspace, or error: <message> 
                   3935: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3936: 
1.531     albertel 3937: sub userfileupload {
1.1090    raeburn  3938:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3939:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3940:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3941:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3942:     $fname=&clean_filename($fname);
1.1090    raeburn  3943:     # See if there is anything left
1.257     www      3944:     unless ($fname) { return 'error: no uploaded file'; }
1.1406  ! raeburn  3945:     # If filename now begins with a . prepend unix timestamp _ milliseconds
        !          3946:     if ($fname =~ /^\./) {
        !          3947:         my ($s,$usec) = &gettimeofday();
        !          3948:         while (length($usec) < 6) {
        !          3949:             $usec = '0'.$usec;
        !          3950:         }
        !          3951:         $fname = $s.'_'.substr($usec,0,3).$fname;
        !          3952:     }
1.1090    raeburn  3953:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3954:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3955:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3956:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3957:         my $now = time;
1.1090    raeburn  3958:         my $filepath;
1.1095    raeburn  3959:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3960:              $filepath = 'tmp/helprequests/'.$now;
                   3961:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3962:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3963:                          '_'.$env{'user.domain'}.'/pending';
                   3964:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3965:             my ($docuname,$docudom);
1.1350    raeburn  3966:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3967:                 $docudom = $destudom;
                   3968:             } else {
                   3969:                 $docudom = $env{'user.domain'};
                   3970:             }
1.1350    raeburn  3971:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3972:                 $docuname = $destuname;
                   3973:             } else {
                   3974:                 $docuname = $env{'user.name'};
                   3975:             }
                   3976:             if (exists($env{'form.group'})) {
                   3977:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3978:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3979:             }
                   3980:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3981:             if ($context eq 'canceloverwrite') {
                   3982:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3983:                 if (-e  $tempfile) {
                   3984:                     my @info = stat($tempfile);
                   3985:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3986:                         unlink($tempfile);
                   3987:                     }
                   3988:                 }
                   3989:                 return;
1.523     raeburn  3990:             }
                   3991:         }
1.1090    raeburn  3992:         # Create the directory if not present
1.741     raeburn  3993:         my @parts=split(/\//,$filepath);
                   3994:         my $fullpath = $perlvar{'lonDaemons'};
                   3995:         for (my $i=0;$i<@parts;$i++) {
                   3996:             $fullpath .= '/'.$parts[$i];
                   3997:             if ((-e $fullpath)!=1) {
                   3998:                 mkdir($fullpath,0777);
                   3999:             }
                   4000:         }
1.1359    raeburn  4001:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4002:         print $fh $env{'form.'.$formname};
                   4003:         close($fh);
1.1090    raeburn  4004:         if ($context eq 'existingfile') {
                   4005:             my @info = stat($fullpath.'/'.$fname);
                   4006:             return ($fullpath.'/'.$fname,$info[9]);
                   4007:         } else {
                   4008:             return $fullpath.'/'.$fname;
                   4009:         }
1.523     raeburn  4010:     }
1.995     raeburn  4011:     if ($subdir eq 'scantron') {
                   4012:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4013:     } else {
1.995     raeburn  4014:         $fname="$subdir/$fname";
                   4015:     }
1.1090    raeburn  4016:     if ($context eq 'coursedoc') {
1.638     albertel 4017: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4018: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4019:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4020:             return &finishuserfileupload($docuname,$docudom,
                   4021: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4022: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4023:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4024:         } else {
1.1218    raeburn  4025:             if ($env{'form.folder'}) {
                   4026:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4027:             }
1.638     albertel 4028:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4029: 				       $fname,$formname,$parser,
1.1095    raeburn  4030: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4031:         }
1.719     banghart 4032:     } elsif (defined($destuname)) {
                   4033:         my $docuname=$destuname;
                   4034:         my $docudom=$destudom;
1.860     raeburn  4035: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4036: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4037:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4038:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4039:     } else {
1.638     albertel 4040:         my $docuname=$env{'user.name'};
                   4041:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4042:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4043:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4044:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4045:         }
1.860     raeburn  4046: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4047: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4048:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4049:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4050:     }
1.271     www      4051: }
                   4052: 
                   4053: sub finishuserfileupload {
1.860     raeburn  4054:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4055:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4056:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4057:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4058:   
1.860     raeburn  4059:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4060:     $file=$fname;
                   4061:     if ($fname=~m|/|) {
                   4062:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4063: 	$path.=$fnamepath.'/';
                   4064:     }
1.259     www      4065:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4066:     my $count;
                   4067:     for ($count=4;$count<=$#parts;$count++) {
                   4068:         $filepath.="/$parts[$count]";
                   4069:         if ((-e $filepath)!=1) {
                   4070: 	    mkdir($filepath,0777);
                   4071:         }
                   4072:     }
1.984     neumanie 4073: 
1.258     www      4074: # Save the file
                   4075:     {
1.1359    raeburn  4076: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4077: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4078: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4079: 	    return '/adm/notfound.html';
                   4080: 	}
1.1090    raeburn  4081:         if ($context eq 'overwrite') {
1.1117    foxr     4082:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4083:             my $target = $filepath.'/'.$file;
                   4084:             if (-e $source) {
                   4085:                 my @info = stat($source);
                   4086:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4087:                     unless (&File::Copy::move($source,$target)) {
                   4088:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4089:                         return "Moving from $source failed";
                   4090:                     }
                   4091:                 } else {
                   4092:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4093:                 }
                   4094:             } else {
                   4095:                 return "Temporary file: $source missing";
                   4096:             }
                   4097:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4098: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4099: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4100: 	    return '/adm/notfound.html';
                   4101: 	}
1.570     albertel 4102: 	close(FH);
1.1051    raeburn  4103:         if ($resizewidth && $resizeheight) {
                   4104:             my $mm = new File::MMagic;
                   4105:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4106:             if ($mime_type =~ m{^image/}) {
                   4107: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4108:             }  
1.977     amueller 4109: 	}
1.258     www      4110:     }
1.1152    raeburn  4111:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4112:         if (ref($mimetype)) {
                   4113:             if ($$mimetype eq '') {
                   4114:                 my $mm = new File::MMagic;
                   4115:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4116:                 $$mimetype = $type;
                   4117:             }
                   4118:         }
                   4119:     }
1.1401    raeburn  4120:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4121:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4122:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4123:                                                        $allfiles,$codebase);
                   4124:             unless ($parse_result eq 'ok') {
                   4125:                 &logthis('Failed to parse '.$filepath.$file.
                   4126: 	   	         ' for embedded media: '.$parse_result); 
                   4127:             }
1.637     raeburn  4128:         }
1.1401    raeburn  4129:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4130:         my $format = $env{'form.scantron_format'};
                   4131:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4132:     }
1.860     raeburn  4133:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4134:         my $input = $filepath.'/'.$file;
                   4135:         my $output = $filepath.'/'.'tn-'.$file;
                   4136:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4137:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4138:         system({$args[0]} @args);
1.860     raeburn  4139:         if (-e $filepath.'/'.'tn-'.$file) {
                   4140:             $fetchthumb  = 1; 
                   4141:         }
                   4142:     }
1.858     raeburn  4143:  
1.259     www      4144: # Notify homeserver to grep it
                   4145: #
1.984     neumanie 4146:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4147:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4148:     if ($fetchresult eq 'ok') {
1.860     raeburn  4149:         if ($fetchthumb) {
                   4150:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4151:             if ($thumbresult ne 'ok') {
                   4152:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4153:                          $docuhome.': '.$thumbresult);
                   4154:             }
                   4155:         }
1.259     www      4156: #
1.258     www      4157: # Return the URL to it
1.494     albertel 4158:         return '/uploaded/'.$path.$file;
1.263     www      4159:     } else {
1.494     albertel 4160:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4161: 		 ': '.$fetchresult);
1.263     www      4162:         return '/adm/notfound.html';
1.858     raeburn  4163:     }
1.493     albertel 4164: }
                   4165: 
1.637     raeburn  4166: sub extract_embedded_items {
1.961     raeburn  4167:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4168:     my @state = ();
1.1164    raeburn  4169:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4170:     my %javafiles = (
                   4171:                       codebase => '',
                   4172:                       code => '',
                   4173:                       archive => ''
                   4174:                     );
                   4175:     my %mediafiles = (
                   4176:                       src => '',
                   4177:                       movie => '',
                   4178:                      );
1.648     raeburn  4179:     my $p;
                   4180:     if ($content) {
                   4181:         $p = HTML::LCParser->new($content);
                   4182:     } else {
1.961     raeburn  4183:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4184:     }
1.641     albertel 4185:     while (my $t=$p->get_token()) {
1.640     albertel 4186: 	if ($t->[0] eq 'S') {
                   4187: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4188: 	    push(@state, $tagname);
1.648     raeburn  4189:             if (lc($tagname) eq 'allow') {
                   4190:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4191:             }
1.640     albertel 4192: 	    if (lc($tagname) eq 'img') {
                   4193: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4194: 	    }
1.886     albertel 4195: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4196:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4197:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4198:                 }
1.886     albertel 4199: 	    }
1.645     raeburn  4200:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4201:                 my $src;
1.645     raeburn  4202:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4203:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4204:                 } else {
1.1164    raeburn  4205:                     if ($attr->{'src'} ne '') {
                   4206:                         $src = $attr->{'src'};
                   4207:                         &add_filetype($allfiles,$src,'src');
                   4208:                     }
                   4209:                 }
                   4210:                 my $text = $p->get_trimmed_text();
                   4211:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4212:                     my @swfargs = split(/,/,$1);
                   4213:                     foreach my $item (@swfargs) {
                   4214:                         $item =~ s/["']//g;
                   4215:                         $item =~ s/^\s+//;
                   4216:                         $item =~ s/\s+$//;
                   4217:                     }
                   4218:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4219:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4220:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4221:                         } else {
                   4222:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4223:                         }
                   4224:                     }
1.645     raeburn  4225:                 }
                   4226:             }
                   4227:             if (lc($tagname) eq 'link') {
                   4228:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4229:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4230:                 }
                   4231:             }
1.640     albertel 4232: 	    if (lc($tagname) eq 'object' ||
                   4233: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4234: 		foreach my $item (keys(%javafiles)) {
                   4235: 		    $javafiles{$item} = '';
                   4236: 		}
1.1164    raeburn  4237:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4238:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4239:                 }
1.640     albertel 4240: 	    }
                   4241: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4242: 		my $name = lc($attr->{'name'});
                   4243: 		foreach my $item (keys(%javafiles)) {
                   4244: 		    if ($name eq $item) {
                   4245: 			$javafiles{$item} = $attr->{'value'};
                   4246: 			last;
                   4247: 		    }
                   4248: 		}
1.1164    raeburn  4249:                 my $pathfrom;
1.640     albertel 4250: 		foreach my $item (keys(%mediafiles)) {
                   4251: 		    if ($name eq $item) {
1.1164    raeburn  4252:                         $pathfrom = $attr->{'value'};
                   4253:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4254: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4255: 			last;
                   4256: 		    }
                   4257: 		}
1.1164    raeburn  4258:                 if ($name eq 'flashvars') {
                   4259:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4260:                 }
                   4261:                 if ($pathfrom ne '') {
                   4262:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4263:                                          $pathfrom);
                   4264:                 }
1.640     albertel 4265: 	    }
                   4266: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4267: 		foreach my $item (keys(%javafiles)) {
                   4268: 		    if ($attr->{$item}) {
                   4269: 			$javafiles{$item} = $attr->{$item};
                   4270: 			last;
                   4271: 		    }
                   4272: 		}
                   4273: 		foreach my $item (keys(%mediafiles)) {
                   4274: 		    if ($attr->{$item}) {
                   4275: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4276: 			last;
                   4277: 		    }
                   4278: 		}
1.1164    raeburn  4279:                 if (lc($tagname) eq 'embed') {
                   4280:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4281:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4282:                                              $attr->{'src'});
                   4283:                     }
                   4284:                 }
1.640     albertel 4285: 	    }
1.1243    raeburn  4286:             if (lc($tagname) eq 'iframe') {
                   4287:                 my $src = $attr->{'src'} ;
                   4288:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4289:                     &add_filetype($allfiles,$src,'src');
                   4290:                 } elsif ($src =~ m{^/}) {
                   4291:                     if ($env{'request.course.id'}) {
                   4292:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4293:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4294:                         my $url = &hreflocation('',$fullpath);
                   4295:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4296:                             my $relpath = $1;
                   4297:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4298:                                 &add_filetype($allfiles,$1,'src');
                   4299:                             }
                   4300:                         }
                   4301:                     }
                   4302:                 }
                   4303:             }
1.1164    raeburn  4304:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4305:                 pop(@state);
1.1164    raeburn  4306:             }
1.640     albertel 4307: 	} elsif ($t->[0] eq 'E') {
                   4308: 	    my ($tagname) = ($t->[1]);
                   4309: 	    if ($javafiles{'codebase'} ne '') {
                   4310: 		$javafiles{'codebase'} .= '/';
                   4311: 	    }  
                   4312: 	    if (lc($tagname) eq 'applet' ||
                   4313: 		lc($tagname) eq 'object' ||
                   4314: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4315: 		) {
                   4316: 		foreach my $item (keys(%javafiles)) {
                   4317: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4318: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4319: 			&add_filetype($allfiles,$file,$item);
                   4320: 		    }
                   4321: 		}
                   4322: 	    } 
                   4323: 	    pop @state;
                   4324: 	}
                   4325:     }
1.1164    raeburn  4326:     foreach my $id (sort(keys(%flashvars))) {
                   4327:         if ($shockwave{$id} ne '') {
                   4328:             my @pairs = split(/\&/,$flashvars{$id});
                   4329:             foreach my $pair (@pairs) {
                   4330:                 my ($key,$value) = split(/\=/,$pair);
                   4331:                 if ($key eq 'thumb') {
                   4332:                     &add_filetype($allfiles,$value,$key);
                   4333:                 } elsif ($key eq 'content') {
                   4334:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4335:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4336:                     if ($ext ne '') {
                   4337:                         &add_filetype($allfiles,$path.$value,$ext);
                   4338:                     }
                   4339:                 }
                   4340:             }
                   4341:         }
                   4342:     }
1.637     raeburn  4343:     return 'ok';
                   4344: }
                   4345: 
1.639     albertel 4346: sub add_filetype {
                   4347:     my ($allfiles,$file,$type)=@_;
                   4348:     if (exists($allfiles->{$file})) {
                   4349: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4350: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4351: 	}
                   4352:     } else {
                   4353: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4354:     }
                   4355: }
                   4356: 
1.1164    raeburn  4357: sub embedded_dependency {
                   4358:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4359:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4360:         if (($identifier ne '') &&
                   4361:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4362:             ($pathfrom ne '')) {
                   4363:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4364:             foreach my $dep (@{$related->{$identifier}}) {
                   4365:                 &add_filetype($allfiles,$path.$dep,'object');
                   4366:             }
                   4367:         }
                   4368:     }
                   4369:     return;
                   4370: }
                   4371: 
1.1401    raeburn  4372: sub bubblesheet_converter {
                   4373:     my ($cdom,$fullpath,$config,$format) = @_;
                   4374:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4375:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4376:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4377:         my (%csvcols,%csvoptions);
                   4378:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4379:             %csvcols = %{$config->{'fields'}};
                   4380:         }
                   4381:         if (ref($config->{'options'}) eq 'HASH') {
                   4382:             %csvoptions = %{$config->{'options'}};
                   4383:         }
1.1401    raeburn  4384:         my %csvbynum = reverse(%csvcols);
                   4385:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4386:         if (keys(%scantronconf)) {
                   4387:             my %bynum = (
                   4388:                           $scantronconf{CODEstart} => 'CODEstart',
                   4389:                           $scantronconf{IDstart}   => 'IDstart',
                   4390:                           $scantronconf{PaperID}   => 'PaperID',
                   4391:                           $scantronconf{FirstName} => 'FirstName',
                   4392:                           $scantronconf{LastName}  => 'LastName',
                   4393:                           $scantronconf{Qstart}    => 'Qstart',
                   4394:                         );
                   4395:             my @ordered;
                   4396:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4397:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4398:             }
                   4399:             my %mapstart = (
                   4400:                               CODEstart => 'CODE',
                   4401:                               IDstart   => 'ID',
                   4402:                               PaperID   => 'PaperID',
                   4403:                               FirstName => 'FirstName',
                   4404:                               LastName  => 'LastName',
                   4405:                               Qstart    => 'FirstQuestion',
                   4406:                            );
                   4407:             my %maplength = (
                   4408:                               CODEstart => 'CODElength',
                   4409:                               IDstart   => 'IDlength',
                   4410:                               PaperID   => 'PaperIDlength',
                   4411:                               FirstName => 'FirstNamelength',
                   4412:                               LastName  => 'LastNamelength',
                   4413:             );
                   4414:             if (open(my $fh,'<',$fullpath)) {
                   4415:                 my $output;
1.1403    raeburn  4416:                 my %lettdig = &letter_to_digits();
                   4417:                 my %diglett = reverse(%lettdig);
                   4418:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4419:                 my $num = 0;
1.1401    raeburn  4420:                 while (my $line=<$fh>) {
1.1404    raeburn  4421:                     $num ++;
                   4422:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4423:                     $line =~ s{[\r\n]+$}{};
                   4424:                     my %found;
                   4425:                     my @values = split(/,/,$line);
                   4426:                     my ($qstart,$record);
                   4427:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4428:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4429:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4430:                             if ($values[$i] eq '') {
                   4431:                                 $values[$i] = $scantronconf{'Qoff'};
                   4432:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4433:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4434:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4435:                                 }
                   4436:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4437:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4438:                                     $values[$i] = $diglett{$values[$i]};
                   4439:                                 }
                   4440:                             } else {
                   4441:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4442:                                     my $digit;
                   4443:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4444:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4445:                                         if ($values[$i] eq 'J') {
                   4446:                                             $digit += $numletts;
                   4447:                                         }
                   4448:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4449:                                         $digit = $values[$i]-1;
                   4450:                                         if ($values[$i] eq '0') {
                   4451:                                             $digit += $numletts;
                   4452:                                         }
                   4453:                                     }
                   4454:                                     my $qval='';
                   4455:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4456:                                         if ($j == $digit) {
                   4457:                                             $qval .= $scantronconf{'Qon'};
                   4458:                                         } else {
                   4459:                                             $qval .= $scantronconf{'Qoff'};
                   4460:                                         }
                   4461:                                     }
                   4462:                                     $values[$i] = $qval;
                   4463:                                 }
                   4464:                             }
                   4465:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4466:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4467:                             }
                   4468:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4469:                             if ($numblank > 0) {
                   4470:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4471:                             }
1.1401    raeburn  4472:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4473:                                 $qstart = $i;
1.1403    raeburn  4474:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4475:                             } else {
1.1403    raeburn  4476:                                 $found{'FirstQuestion'} .= $values[$i];
                   4477:                             }
                   4478:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4479:                             if ($csvoptions{'rem'}) {
                   4480:                                 $values[$i] =~ s/^\s+//;
                   4481:                             }
                   4482:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4483:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4484:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4485:                                 }
                   4486:                             }
                   4487:                             $found{$csvbynum{$i}} = $values[$i];
                   4488:                         }
                   4489:                     }
                   4490:                     foreach my $item (@ordered) {
                   4491:                         my $currlength = 1+length($record);
                   4492:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4493:                         if ($numspaces > 0) {
                   4494:                             $record .= (' ' x $numspaces);
                   4495:                         }
                   4496:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4497:                             unless ($item eq 'Qstart') {
                   4498:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4499:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4500:                                 }
                   4501:                             }
                   4502:                             $record .= $found{$mapstart{$item}};
                   4503:                         }
                   4504:                     }
                   4505:                     $output .= "$record\n";
                   4506:                 }
                   4507:                 close($fh);
                   4508:                 if ($output) {
                   4509:                     if (open(my $fh,'>',$fullpath)) {
                   4510:                         print $fh $output;
                   4511:                         close($fh);
                   4512:                     }
                   4513:                 }
                   4514:             }
                   4515:         }
                   4516:         return;
                   4517:     }
                   4518: }
                   4519: 
1.1403    raeburn  4520: sub letter_to_digits {
                   4521:     my %lettdig = (
                   4522:                     A => 1,
                   4523:                     B => 2,
                   4524:                     C => 3,
                   4525:                     D => 4,
                   4526:                     E => 5,
                   4527:                     F => 6,
                   4528:                     G => 7,
                   4529:                     H => 8,
                   4530:                     I => 9,
                   4531:                     J => 0,
                   4532:                   );
                   4533:     return %lettdig;
                   4534: }
                   4535: 
1.1401    raeburn  4536: sub get_scantron_config {
                   4537:     my ($which,$cdom) = @_;
                   4538:     my @lines = &get_scantronformat_file($cdom);
                   4539:     my %config;
                   4540:     #FIXME probably should move to XML it has already gotten a bit much now
                   4541:     foreach my $line (@lines) {
                   4542:         my ($name,$descrip)=split(/:/,$line);
                   4543:         if ($name ne $which ) { next; }
                   4544:         chomp($line);
                   4545:         my @config=split(/:/,$line);
                   4546:         $config{'name'}=$config[0];
                   4547:         $config{'description'}=$config[1];
                   4548:         $config{'CODElocation'}=$config[2];
                   4549:         $config{'CODEstart'}=$config[3];
                   4550:         $config{'CODElength'}=$config[4];
                   4551:         $config{'IDstart'}=$config[5];
                   4552:         $config{'IDlength'}=$config[6];
                   4553:         $config{'Qstart'}=$config[7];
                   4554:         $config{'Qlength'}=$config[8];
                   4555:         $config{'Qoff'}=$config[9];
                   4556:         $config{'Qon'}=$config[10];
                   4557:         $config{'PaperID'}=$config[11];
                   4558:         $config{'PaperIDlength'}=$config[12];
                   4559:         $config{'FirstName'}=$config[13];
                   4560:         $config{'FirstNamelength'}=$config[14];
                   4561:         $config{'LastName'}=$config[15];
                   4562:         $config{'LastNamelength'}=$config[16];
                   4563:         $config{'BubblesPerRow'}=$config[17];
                   4564:         last;
                   4565:     }
                   4566:     return %config;
                   4567: }
                   4568: 
                   4569: sub get_scantronformat_file {
                   4570:     my ($cdom) = @_;
                   4571:     if ($cdom eq '') {
                   4572:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4573:     }
                   4574:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4575:     my $gottab = 0;
                   4576:     my @lines;
                   4577:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4578:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4579:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4580:             if ($formatfile ne '-1') {
                   4581:                 @lines = split("\n",$formatfile,-1);
                   4582:                 $gottab = 1;
                   4583:             }
                   4584:         }
                   4585:     }
                   4586:     if (!$gottab) {
                   4587:         my $confname = $cdom.'-domainconfig';
                   4588:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4589:         my $formatfile = &getfile($default);
                   4590:         if ($formatfile ne '-1') {
                   4591:             @lines = split("\n",$formatfile,-1);
                   4592:             $gottab = 1;
                   4593:         }
                   4594:     }
                   4595:     if (!$gottab) {
                   4596:         my @domains = &current_machine_domains();
                   4597:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4598:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4599:                 @lines = <$fh>;
                   4600:                 close($fh);
1.1403    raeburn  4601:             }
1.1401    raeburn  4602:         } else {
                   4603:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4604:                 @lines = <$fh>;
                   4605:                 close($fh);
                   4606:             }
                   4607:         }
                   4608:     }
                   4609:     return @lines;
                   4610: }
                   4611: 
1.493     albertel 4612: sub removeuploadedurl {
1.984     neumanie 4613:     my ($url)=@_;	
                   4614:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4615:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4616: }
                   4617: 
                   4618: sub removeuserfile {
                   4619:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4620:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4621:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4622:     if ($result eq 'ok') {	
1.798     raeburn  4623:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4624:             my $metafile = $fname.'.meta';
                   4625:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4626: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4627:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4628:             my $sqlresult = 
1.823     albertel 4629:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4630:                                         'portfolio_metadata',$group,
                   4631:                                         'delete');
1.798     raeburn  4632:         }
                   4633:     }
                   4634:     return $result;
1.257     www      4635: }
1.15      www      4636: 
1.530     albertel 4637: sub mkdiruserfile {
                   4638:     my ($docuname,$docudom,$dir)=@_;
                   4639:     my $home=&homeserver($docuname,$docudom);
                   4640:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4641: }
                   4642: 
1.531     albertel 4643: sub renameuserfile {
                   4644:     my ($docuname,$docudom,$old,$new)=@_;
                   4645:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4646:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4647:                         &escape("$old").':'.&escape("$new"),$home);
                   4648:     if ($result eq 'ok') {
                   4649:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4650:             my $oldmeta = $old.'.meta';
                   4651:             my $newmeta = $new.'.meta';
                   4652:             my $metaresult = 
                   4653:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4654: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4655:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4656:             my $sqlresult = 
1.823     albertel 4657:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4658:                                         'portfolio_metadata',$group,
                   4659:                                         'delete');
1.798     raeburn  4660:         }
                   4661:     }
                   4662:     return $result;
1.531     albertel 4663: }
                   4664: 
1.14      www      4665: # ------------------------------------------------------------------------- Log
                   4666: 
                   4667: sub log {
                   4668:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4669:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4670: }
                   4671: 
                   4672: # ------------------------------------------------------------------ Course Log
1.352     www      4673: #
                   4674: # This routine flushes several buffers of non-mission-critical nature
                   4675: #
1.157     www      4676: 
                   4677: sub flushcourselogs {
1.352     www      4678:     &logthis('Flushing log buffers');
                   4679: #
                   4680: # course logs
                   4681: # This is a log of all transactions in a course, which can be used
                   4682: # for data mining purposes
                   4683: #
                   4684: # It also collects the courseid database, which lists last transaction
                   4685: # times and course titles for all courseids
                   4686: #
                   4687:     my %courseidbuffer=();
1.921     raeburn  4688:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4689:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4690: 		          &escape($courselogs{$crsid}),
                   4691: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4692: 	    delete $courselogs{$crsid};
                   4693:         } else {
                   4694:             &logthis('Failed to flush log buffer for '.$crsid);
                   4695:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4696:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4697:                         " exceeded maximum size, deleting.</font>");
                   4698:                delete $courselogs{$crsid};
                   4699:             }
1.352     www      4700:         }
1.920     raeburn  4701:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4702:             'description' => $coursedescrbuf{$crsid},
                   4703:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4704:             'type'        => $coursetypebuf{$crsid},
                   4705:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4706:         };
1.191     harris41 4707:     }
1.352     www      4708: #
                   4709: # Write course id database (reverse lookup) to homeserver of courses 
                   4710: # Is used in pickcourse
                   4711: #
1.840     albertel 4712:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4713:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4714:                                     $courseidbuffer{$crs_home},
                   4715:                                     $crs_home,'timeonly');
1.352     www      4716:     }
                   4717: #
                   4718: # File accesses
                   4719: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4720: #
1.449     matthew  4721:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4722:         if ($entry =~ /___count$/) {
                   4723:             my ($dom,$name);
1.807     albertel 4724:             ($dom,$name,undef)=
1.811     albertel 4725: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4726:             if (! defined($dom) || $dom eq '' || 
                   4727:                 ! defined($name) || $name eq '') {
1.620     albertel 4728:                 my $cid = $env{'request.course.id'};
                   4729:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4730:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4731:             }
1.450     matthew  4732:             my $value = $accesshash{$entry};
                   4733:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4734:             my %temphash=($url => $value);
1.449     matthew  4735:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4736:             if ($result eq 'ok') {
                   4737:                 delete $accesshash{$entry};
                   4738:             }
                   4739:         } else {
1.811     albertel 4740:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4741:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4742:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4743:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4744:                 delete $accesshash{$entry};
                   4745:             }
1.185     www      4746:         }
1.191     harris41 4747:     }
1.352     www      4748: #
                   4749: # Roles
                   4750: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4751: #
1.800     albertel 4752:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4753:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4754: 	    split(/\:/,$entry);
                   4755:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4756:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4757:                 $rudom,$runame) eq 'ok') {
                   4758: 	    delete $userrolehash{$entry};
                   4759:         }
                   4760:     }
1.662     raeburn  4761: #
1.1334    raeburn  4762: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4763: #
                   4764:     my %domrolebuffer = ();
1.1000    raeburn  4765:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4766:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4767:         if ($domrolebuffer{$rudom}) {
                   4768:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4769:                       '='.&escape($domainrolehash{$entry});
                   4770:         } else {
                   4771:             $domrolebuffer{$rudom}.=&escape($entry).
                   4772:                       '='.&escape($domainrolehash{$entry});
                   4773:         }
                   4774:         delete $domainrolehash{$entry};
                   4775:     }
                   4776:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4777: 	my %servers;
                   4778: 	if (defined(&domain($dom,'primary'))) {
                   4779: 	    my $primary=&domain($dom,'primary');
                   4780: 	    my $hostname=&hostname($primary);
                   4781: 	    $servers{$primary} = $hostname;
                   4782: 	} else { 
                   4783: 	    %servers = &get_servers($dom,'library');
                   4784: 	}
1.841     albertel 4785: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4786: 	    if (&reply('domroleput:'.$dom.':'.
                   4787: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4788: 		last;
                   4789: 	    } else {  
1.841     albertel 4790: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4791: 	    }
1.662     raeburn  4792:         }
                   4793:     }
1.186     www      4794:     $dumpcount++;
1.157     www      4795: }
                   4796: 
                   4797: sub courselog {
                   4798:     my $what=shift;
1.158     www      4799:     $what=time.':'.$what;
1.620     albertel 4800:     unless ($env{'request.course.id'}) { return ''; }
                   4801:     $coursedombuf{$env{'request.course.id'}}=
                   4802:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4803:     $coursenumbuf{$env{'request.course.id'}}=
                   4804:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4805:     $coursehombuf{$env{'request.course.id'}}=
                   4806:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4807:     $coursedescrbuf{$env{'request.course.id'}}=
                   4808:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4809:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4810:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4811:     $courseownerbuf{$env{'request.course.id'}}=
                   4812:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4813:     $coursetypebuf{$env{'request.course.id'}}=
                   4814:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4815:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4816: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4817:     } else {
1.620     albertel 4818: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4819:     }
1.620     albertel 4820:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4821: 	&flushcourselogs();
                   4822:     }
1.158     www      4823: }
                   4824: 
                   4825: sub courseacclog {
                   4826:     my $fnsymb=shift;
1.620     albertel 4827:     unless ($env{'request.course.id'}) { return ''; }
                   4828:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4829:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4830:         $what.=':POST';
1.583     matthew  4831:         # FIXME: Probably ought to escape things....
1.800     albertel 4832: 	foreach my $key (keys(%env)) {
                   4833:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4834:                 my $formitem = $1;
                   4835:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4836:                     $what.=':'.$formitem.'='.$env{$key};
                   4837:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4838:                     $what.=':'.$formitem.'='.$env{$key};
                   4839:                 }
1.158     www      4840:             }
1.191     harris41 4841:         }
1.583     matthew  4842:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4843:         # FIXME: We should not be depending on a form parameter that someone
                   4844:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4845:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4846:             $what.= ':POST';
                   4847:             # FIXME: Probably ought to escape things....
                   4848:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4849:                                  'crsdiscuss') {
1.620     albertel 4850:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4851:             }
                   4852:         }
1.158     www      4853:     }
                   4854:     &courselog($what);
1.149     www      4855: }
                   4856: 
1.185     www      4857: sub countacc {
                   4858:     my $url=&declutter(shift);
1.458     matthew  4859:     return if (! defined($url) || $url eq '');
1.620     albertel 4860:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4861: #
                   4862: # Mark that this url was used in this course
                   4863: #
1.620     albertel 4864:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4865: #
                   4866: # Increase the access count for this resource in this child process
                   4867: #
1.281     www      4868:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4869:     $accesshash{$key}++;
1.185     www      4870: }
1.349     www      4871: 
1.361     www      4872: sub linklog {
                   4873:     my ($from,$to)=@_;
                   4874:     $from=&declutter($from);
                   4875:     $to=&declutter($to);
                   4876:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4877:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4878: }
1.1160    www      4879: 
                   4880: sub statslog {
                   4881:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4882:     if ($users<2) { return; }
                   4883:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4884:             'course'       => $env{'request.course.id'},
                   4885:             'sections'     => '"all"',
                   4886:             'num_students' => $users,
                   4887:             'part'         => $part,
                   4888:             'symb'         => $symb,
                   4889:             'mean_tries'   => $av_attempts,
                   4890:             'deg_of_diff'  => $degdiff});
                   4891:     foreach my $key (keys(%dynstore)) {
                   4892:         $accesshash{$key}=$dynstore{$key};
                   4893:     }
                   4894: }
1.361     www      4895:   
1.349     www      4896: sub userrolelog {
                   4897:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4898:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4899:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4900:        $userrolehash
                   4901:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4902:                     =$tend.':'.$tstart;
1.662     raeburn  4903:     }
1.1169    droeschl 4904:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4905:        $userrolehash
                   4906:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4907:                     =$tend.':'.$tstart;
                   4908:     }
1.1334    raeburn  4909:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4910:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4911:        $domainrolehash
                   4912:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4913:                     = $tend.':'.$tstart;
                   4914:     }
1.351     www      4915: }
                   4916: 
1.957     raeburn  4917: sub courserolelog {
                   4918:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4919:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4920:         my $cdom = $1;
                   4921:         my $cnum = $2;
                   4922:         my $sec = $3;
                   4923:         my $namespace = 'rolelog';
                   4924:         my %storehash = (
                   4925:                            role    => $trole,
                   4926:                            start   => $tstart,
                   4927:                            end     => $tend,
                   4928:                            selfenroll => $selfenroll,
                   4929:                            context    => $context,
                   4930:                         );
                   4931:         if ($trole eq 'gr') {
                   4932:             $namespace = 'groupslog';
                   4933:             $storehash{'group'} = $sec;
                   4934:         } else {
                   4935:             $storehash{'section'} = $sec;
                   4936:         }
1.1188    raeburn  4937:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4938:                    $domain,$cnum,$cdom);
1.1184    raeburn  4939:         if (($trole ne 'st') || ($sec ne '')) {
                   4940:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4941:         }
                   4942:     }
                   4943:     return;
                   4944: }
                   4945: 
1.1184    raeburn  4946: sub domainrolelog {
                   4947:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4948:     if ($area =~ m{^/($match_domain)/$}) {
                   4949:         my $cdom = $1;
                   4950:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4951:         my $namespace = 'rolelog';
                   4952:         my %storehash = (
                   4953:                            role    => $trole,
                   4954:                            start   => $tstart,
                   4955:                            end     => $tend,
                   4956:                            context => $context,
                   4957:                         );
1.1188    raeburn  4958:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4959:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4960:     }
                   4961:     return;
                   4962: 
                   4963: }
                   4964: 
                   4965: sub coauthorrolelog {
                   4966:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4967:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4968:         my $audom = $1;
                   4969:         my $auname = $2;
                   4970:         my $namespace = 'rolelog';
                   4971:         my %storehash = (
                   4972:                            role    => $trole,
                   4973:                            start   => $tstart,
                   4974:                            end     => $tend,
                   4975:                            context => $context,
                   4976:                         );
1.1188    raeburn  4977:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4978:                    $domain,$auname,$audom);
1.1184    raeburn  4979:     }
                   4980:     return;
                   4981: }
                   4982: 
1.351     www      4983: sub get_course_adv_roles {
1.948     raeburn  4984:     my ($cid,$codes) = @_;
1.620     albertel 4985:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4986:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4987:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4988:     my %nothide=();
1.800     albertel 4989:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4990:         if ($user !~ /:/) {
                   4991: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4992:         } else {
                   4993:             $nothide{$user}=1;
                   4994:         }
1.470     www      4995:     }
1.1219    raeburn  4996:     my @possdoms = ($coursehash{'domain'});
                   4997:     if ($coursehash{'checkforpriv'}) {
                   4998:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4999:     }
1.351     www      5000:     my %returnhash=();
                   5001:     my %dumphash=
                   5002:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5003:     my $now=time;
1.997     raeburn  5004:     my %privileged;
1.1000    raeburn  5005:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5006: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5007:         if (($tstart) && ($tstart<0)) { next; }
                   5008:         if (($tend) && ($tend<$now)) { next; }
                   5009:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5010:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5011: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5012:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5013:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5014: 	if ($role eq 'cr') { next; }
1.948     raeburn  5015:         if ($codes) {
                   5016:             if ($section) { $role .= ':'.$section; }
                   5017:             if ($returnhash{$role}) {
                   5018:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5019:             } else {
                   5020:                 $returnhash{$role}=$username.':'.$domain;
                   5021:             }
1.351     www      5022:         } else {
1.988     raeburn  5023:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5024:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5025:             if ($returnhash{$key}) {
                   5026: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5027:             } else {
                   5028:                 $returnhash{$key}=$username.':'.$domain;
                   5029:             }
1.351     www      5030:         }
1.948     raeburn  5031:     }
1.400     www      5032:     return %returnhash;
                   5033: }
                   5034: 
                   5035: sub get_my_roles {
1.937     raeburn  5036:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5037:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5038:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5039:     my (%dumphash,%nothide);
1.1086    raeburn  5040:     if ($context eq 'userroles') {
1.1166    raeburn  5041:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5042:     } else {
1.1219    raeburn  5043:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5044:         if ($hidepriv) {
                   5045:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5046:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5047:                 if ($user !~ /:/) {
                   5048:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5049:                 } else {
                   5050:                     $nothide{$user} = 1;
                   5051:                 }
                   5052:             }
                   5053:         }
1.858     raeburn  5054:     }
1.400     www      5055:     my %returnhash=();
                   5056:     my $now=time;
1.999     raeburn  5057:     my %privileged;
1.800     albertel 5058:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5059:         my ($role,$tend,$tstart);
                   5060:         if ($context eq 'userroles') {
1.1149    raeburn  5061:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5062: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5063:         } else {
                   5064:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5065:         }
1.400     www      5066:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5067:         my $status = 'active';
1.939     raeburn  5068:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5069:             $status = 'previous';
                   5070:         } 
                   5071:         if (($tstart) && ($now<$tstart)) {
                   5072:             $status = 'future';
                   5073:         }
                   5074:         if (ref($types) eq 'ARRAY') {
                   5075:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5076:                 next;
                   5077:             } 
                   5078:         } else {
                   5079:             if ($status ne 'active') {
                   5080:                 next;
                   5081:             }
                   5082:         }
1.867     raeburn  5083:         my ($rolecode,$username,$domain,$section,$area);
                   5084:         if ($context eq 'userroles') {
1.1186    raeburn  5085:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5086:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5087:         } else {
                   5088:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5089:         }
1.832     raeburn  5090:         if (ref($roledoms) eq 'ARRAY') {
                   5091:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5092:                 next;
                   5093:             }
                   5094:         }
                   5095:         if (ref($roles) eq 'ARRAY') {
                   5096:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5097:                 if ($role =~ /^cr\//) {
                   5098:                     if (!grep(/^cr$/,@{$roles})) {
                   5099:                         next;
                   5100:                     }
1.1104    raeburn  5101:                 } elsif ($role =~ /^gr\//) {
                   5102:                     if (!grep(/^gr$/,@{$roles})) {
                   5103:                         next;
                   5104:                     }
1.922     raeburn  5105:                 } else {
                   5106:                     next;
                   5107:                 }
1.832     raeburn  5108:             }
1.867     raeburn  5109:         }
1.937     raeburn  5110:         if ($hidepriv) {
1.1219    raeburn  5111:             my @privroles = ('dc','su');
1.999     raeburn  5112:             if ($context eq 'userroles') {
1.1219    raeburn  5113:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5114:             } else {
1.1219    raeburn  5115:                 my $possdoms = [$domain];
                   5116:                 if (ref($roledoms) eq 'ARRAY') {
                   5117:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5118:                 }
1.1219    raeburn  5119:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5120:                     if (!$nothide{$username.':'.$domain}) {
                   5121:                         next;
                   5122:                     }
                   5123:                 }
1.937     raeburn  5124:             }
                   5125:         }
1.933     raeburn  5126:         if ($withsec) {
                   5127:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5128:                 $tstart.':'.$tend;
                   5129:         } else {
                   5130:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5131:         }
1.832     raeburn  5132:     }
1.373     www      5133:     return %returnhash;
1.399     www      5134: }
                   5135: 
1.1333    raeburn  5136: sub get_all_adhocroles {
                   5137:     my ($dom) = @_;
                   5138:     my @roles_by_num = ();
                   5139:     my %domdefaults = &get_domain_defaults($dom);
                   5140:     my (%description,%access_in_dom,%access_info);
                   5141:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5142:         my $count = 0;
                   5143:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5144:         my %ordered;
                   5145:         foreach my $role (sort(keys(%domcurrent))) {
                   5146:             my ($order,$desc,$access_in_dom);
                   5147:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5148:                 $order = $domcurrent{$role}{'order'};
                   5149:                 $desc = $domcurrent{$role}{'desc'};
                   5150:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5151:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5152:             }
                   5153:             if ($order eq '') {
                   5154:                 $order = $count;
                   5155:             }
                   5156:             $ordered{$order} = $role;
                   5157:             if ($desc ne '') {
                   5158:                 $description{$role} = $desc;
                   5159:             } else {
                   5160:                 $description{$role}= $role;
                   5161:             }
                   5162:             $count++;
                   5163:         }
                   5164:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5165:             push(@roles_by_num,$ordered{$item});
                   5166:         }
                   5167:     }
                   5168:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5169: }
                   5170: 
1.1332    raeburn  5171: sub get_my_adhocroles {
1.1333    raeburn  5172:     my ($cid,$checkreg) = @_;
                   5173:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5174:     if ($env{'request.course.id'} eq $cid) {
                   5175:         $cdom = $env{'course.'.$cid.'.domain'};
                   5176:         $cnum = $env{'course.'.$cid.'.num'};
                   5177:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5178:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5179:         $cdom = $1;
                   5180:         $cnum = $2;
                   5181:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5182:                                      $cdom,$cnum);
                   5183:     }
                   5184:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5185:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5186:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5187:         if ($rosterhash{$user} ne '') {
                   5188:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5189:             return ([],{}) if ($type eq 'auto');
                   5190:         }
                   5191:     }
                   5192:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5193:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5194:             my $then=$env{'user.login.time'};
                   5195:             my $update=$env{'user.update.time'};
1.1335    raeburn  5196:             if (!$update) {
                   5197:                 $update = $then;
                   5198:             }
                   5199:             my @liveroles;
1.1334    raeburn  5200:             foreach my $role ('dh','da') {
                   5201:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5202:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5203:                     my $limit = $update;
                   5204:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5205:                         $limit = $then;
                   5206:                     }
1.1335    raeburn  5207:                     my $activerole = 1;
                   5208:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5209:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5210:                     if ($activerole) {
                   5211:                         push(@liveroles,$role);
                   5212:                     }
1.1334    raeburn  5213:                 }
1.1332    raeburn  5214:             }
1.1335    raeburn  5215:             if (@liveroles) {
1.1332    raeburn  5216:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5217:                     my ($accessref,$accessinfo,%access_in_dom);
                   5218:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5219:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5220:                         if (@{$roles_by_num}) {
1.1332    raeburn  5221:                             my %settings;
                   5222:                             if ($env{'request.course.id'} eq $cid) {
                   5223:                                 foreach my $envkey (keys(%env)) {
                   5224:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5225:                                         $settings{$1} = $env{$envkey};
                   5226:                                     }
                   5227:                                 }
                   5228:                             } else {
                   5229:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5230:                             }
                   5231:                             my %setincrs;
                   5232:                             if ($settings{'internal.adhocaccess'}) {
                   5233:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5234:                             }
                   5235:                             my @statuses;
                   5236:                             if ($env{'environment.inststatus'}) {
                   5237:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5238:                             }
                   5239:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5240:                             if (ref($accessref) eq 'HASH') {
                   5241:                                 %access_in_dom = %{$accessref};
                   5242:                             }
                   5243:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5244:                                 my ($curraccess,@okstatus,@personnel);
                   5245:                                 if ($setincrs{$role}) {
                   5246:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5247:                                     if ($curraccess eq 'status') {
                   5248:                                         @okstatus = split(/\&/,$rest);
                   5249:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5250:                                         @personnel = split(/\&/,$rest);
                   5251:                                     }
                   5252:                                 } else {
                   5253:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5254:                                     if (ref($accessinfo) eq 'HASH') {
                   5255:                                         if ($curraccess eq 'status') {
                   5256:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5257:                                                 @okstatus = @{$accessinfo->{$role}};
                   5258:                                             }
                   5259:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5260:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5261:                                                 @personnel = @{$accessinfo->{$role}};
                   5262:                                             }
1.1332    raeburn  5263:                                         }
                   5264:                                     }
                   5265:                                 }
                   5266:                                 if ($curraccess eq 'none') {
                   5267:                                     next;
                   5268:                                 } elsif ($curraccess eq 'all') {
                   5269:                                     push(@possroles,$role);
1.1336    raeburn  5270:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5271:                                     if (grep(/^dh$/,@liveroles)) {
                   5272:                                         push(@possroles,$role);
                   5273:                                     } else {
                   5274:                                         next;
                   5275:                                     }
1.1336    raeburn  5276:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5277:                                     if (grep(/^da$/,@liveroles)) {
                   5278:                                         push(@possroles,$role);
                   5279:                                     } else {
                   5280:                                         next;
                   5281:                                     }
1.1332    raeburn  5282:                                 } elsif ($curraccess eq 'status') {
                   5283:                                     if (@okstatus) {
                   5284:                                         if (!@statuses) {
                   5285:                                             if (grep(/^default$/,@okstatus)) {
                   5286:                                                 push(@possroles,$role);
                   5287:                                             }
                   5288:                                         } else {
                   5289:                                             foreach my $status (@okstatus) {
                   5290:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5291:                                                     push(@possroles,$role);
                   5292:                                                     last;
                   5293:                                                 }
                   5294:                                             }
                   5295:                                         }
                   5296:                                     }
                   5297:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5298:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5299:                                         if ($curraccess eq 'exc') {
                   5300:                                             push(@possroles,$role);
                   5301:                                         }
                   5302:                                     } elsif ($curraccess eq 'inc') {
                   5303:                                         push(@possroles,$role);
                   5304:                                     }
                   5305:                                 }
                   5306:                             }
                   5307:                         }
                   5308:                     }
                   5309:                 }
                   5310:             }
                   5311:         }
                   5312:     }
1.1333    raeburn  5313:     unless (ref($description) eq 'HASH') {
                   5314:         if (ref($roles_by_num) eq 'ARRAY') {
                   5315:             my %desc;
                   5316:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5317:             $description = \%desc;
                   5318:         } else {
                   5319:             $description = {};
                   5320:         }
                   5321:     }
                   5322:     return (\@possroles,$description);
1.1332    raeburn  5323: }
                   5324: 
1.399     www      5325: # ----------------------------------------------------- Frontpage Announcements
                   5326: #
                   5327: #
                   5328: 
                   5329: sub postannounce {
                   5330:     my ($server,$text)=@_;
1.844     albertel 5331:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5332:     unless ($text=~/\w/) { $text=''; }
                   5333:     return &reply('setannounce:'.&escape($text),$server);
                   5334: }
                   5335: 
                   5336: sub getannounce {
1.448     albertel 5337: 
1.1359    raeburn  5338:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5339: 	my $announcement='';
1.800     albertel 5340: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5341: 	close($fh);
1.399     www      5342: 	if ($announcement=~/\w/) { 
                   5343: 	    return 
                   5344:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5345:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5346: 	} else {
                   5347: 	    return '';
                   5348: 	}
                   5349:     } else {
                   5350: 	return '';
                   5351:     }
1.351     www      5352: }
1.353     www      5353: 
                   5354: # ---------------------------------------------------------- Course ID routines
                   5355: # Deal with domain's nohist_courseid.db files
                   5356: #
                   5357: 
                   5358: sub courseidput {
1.921     raeburn  5359:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5360:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5361:     my $outcome;
                   5362:     if ($caller eq 'timeonly') {
                   5363:         my $cids = '';
                   5364:         foreach my $item (keys(%$storehash)) {
                   5365:             $cids.=&escape($item).'&';
                   5366:         }
                   5367:         $cids=~s/\&$//;
                   5368:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5369:                           $coursehome);       
                   5370:     } else {
                   5371:         my $items = '';
                   5372:         foreach my $item (keys(%$storehash)) {
                   5373:             $items.= &escape($item).'='.
                   5374:                      &freeze_escape($$storehash{$item}).'&';
                   5375:         }
                   5376:         $items=~s/\&$//;
                   5377:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5378:                           $coursehome);
1.918     raeburn  5379:     }
                   5380:     if ($outcome eq 'unknown_cmd') {
                   5381:         my $what;
                   5382:         foreach my $cid (keys(%$storehash)) {
                   5383:             $what .= &escape($cid).'=';
1.921     raeburn  5384:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5385:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5386:             }
                   5387:             $what =~ s/\:$/&/;
                   5388:         }
                   5389:         $what =~ s/\&$//;  
                   5390:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5391:     } else {
                   5392:         return $outcome;
                   5393:     }
1.353     www      5394: }
                   5395: 
                   5396: sub courseiddump {
1.921     raeburn  5397:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5398:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5399:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5400:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5401:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5402:     my $as_hash = 1;
                   5403:     my %returnhash;
                   5404:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5405:     my %libserv = &all_library();
                   5406:     foreach my $tryserver (keys(%libserv)) {
                   5407:         if ( (  $hostidflag == 1 
                   5408: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5409: 	     || (!defined($hostidflag)) ) {
                   5410: 
1.918     raeburn  5411: 	    if (($domfilter eq '') ||
                   5412: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5413:                 my $rep;
                   5414:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5415:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5416:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5417:                                 &escape($descfilter), &escape($instcodefilter), 
                   5418:                                 &escape($ownerfilter), &escape($coursefilter),
                   5419:                                 &escape($typefilter), &escape($regexp_ok), 
                   5420:                                 $as_hash, &escape($selfenrollonly), 
                   5421:                                 &escape($catfilter), $showhidden, $caller, 
                   5422:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5423:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5424:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5425:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5426:                 } else {
                   5427:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5428:                              $sincefilter.':'.&escape($descfilter).':'.
                   5429:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5430:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5431:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5432:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5433:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5434:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5435:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5436:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5437:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5438:                 }
                   5439:                      
1.918     raeburn  5440:                 my @pairs=split(/\&/,$rep);
                   5441:                 foreach my $item (@pairs) {
                   5442:                     my ($key,$value)=split(/\=/,$item,2);
                   5443:                     $key = &unescape($key);
                   5444:                     next if ($key =~ /^error: 2 /);
                   5445:                     my $result = &thaw_unescape($value);
                   5446:                     if (ref($result) eq 'HASH') {
                   5447:                         $returnhash{$key}=$result;
                   5448:                     } else {
1.921     raeburn  5449:                         my @responses = split(/:/,$value);
                   5450:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5451:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5452:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5453:                         }
1.1008    raeburn  5454:                     }
1.353     www      5455:                 }
                   5456:             }
                   5457:         }
                   5458:     }
                   5459:     return %returnhash;
                   5460: }
                   5461: 
1.1055    raeburn  5462: sub courselastaccess {
                   5463:     my ($cdom,$cnum,$hostidref) = @_;
                   5464:     my %returnhash;
                   5465:     if ($cdom && $cnum) {
                   5466:         my $chome = &homeserver($cnum,$cdom);
                   5467:         if ($chome ne 'no_host') {
                   5468:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5469:             &extract_lastaccess(\%returnhash,$rep);
                   5470:         }
                   5471:     } else {
                   5472:         if (!$cdom) { $cdom=''; }
                   5473:         my %libserv = &all_library();
                   5474:         foreach my $tryserver (keys(%libserv)) {
                   5475:             if (ref($hostidref) eq 'ARRAY') {
                   5476:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5477:             } 
                   5478:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5479:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5480:                 &extract_lastaccess(\%returnhash,$rep);
                   5481:             }
                   5482:         }
                   5483:     }
                   5484:     return %returnhash;
                   5485: }
                   5486: 
                   5487: sub extract_lastaccess {
                   5488:     my ($returnhash,$rep) = @_;
                   5489:     if (ref($returnhash) eq 'HASH') {
                   5490:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5491:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5492:                  $rep eq '') {
                   5493:             my @pairs=split(/\&/,$rep);
                   5494:             foreach my $item (@pairs) {
                   5495:                 my ($key,$value)=split(/\=/,$item,2);
                   5496:                 $key = &unescape($key);
                   5497:                 next if ($key =~ /^error: 2 /);
                   5498:                 $returnhash->{$key} = &thaw_unescape($value);
                   5499:             }
                   5500:         }
                   5501:     }
                   5502:     return;
                   5503: }
                   5504: 
1.658     raeburn  5505: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5506: 
                   5507: sub dcmailput {
1.685     raeburn  5508:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5509:     my $status = &Apache::lonnet::critical(
1.740     www      5510:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5511:        &escape($message),$server);
1.662     raeburn  5512:     return $status;
                   5513: }
                   5514: 
1.658     raeburn  5515: sub dcmaildump {
                   5516:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5517:     my %returnhash=();
1.846     albertel 5518: 
                   5519:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5520:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5521:                                                          &escape($enddate).':';
                   5522: 	my @esc_senders=map { &escape($_)} @$senders;
                   5523: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5524: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5525:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5526:             if (($key) && ($value)) {
                   5527:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5528:             }
                   5529:         }
                   5530:     }
                   5531:     return %returnhash;
                   5532: }
1.662     raeburn  5533: # ---------------------------------------------------------- Domain roles
                   5534: 
                   5535: sub get_domain_roles {
                   5536:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5537:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5538:         $startdate = '.';
                   5539:     }
1.1018    raeburn  5540:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5541:         $enddate = '.';
                   5542:     }
1.922     raeburn  5543:     my $rolelist;
                   5544:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5545:         $rolelist = join('&',@{$roles});
1.922     raeburn  5546:     }
1.662     raeburn  5547:     my %personnel = ();
1.841     albertel 5548: 
                   5549:     my %servers = &get_servers($dom,'library');
                   5550:     foreach my $tryserver (keys(%servers)) {
                   5551: 	%{$personnel{$tryserver}}=();
                   5552: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5553: 					    &escape($startdate).':'.
                   5554: 					    &escape($enddate).':'.
                   5555: 					    &escape($rolelist), $tryserver))) {
                   5556: 	    my ($key,$value) = split(/\=/,$line,2);
                   5557: 	    if (($key) && ($value)) {
                   5558: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5559: 	    }
                   5560: 	}
1.662     raeburn  5561:     }
                   5562:     return %personnel;
                   5563: }
1.658     raeburn  5564: 
1.1332    raeburn  5565: sub get_active_domroles {
                   5566:     my ($dom,$roles) = @_;
                   5567:     return () unless (ref($roles) eq 'ARRAY');
                   5568:     my $now = time;
                   5569:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5570:     my %domroles;
                   5571:     foreach my $server (keys(%dompersonnel)) {
                   5572:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5573:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5574:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5575:         }
                   5576:     }
                   5577:     return %domroles;
                   5578: }
                   5579: 
1.1057    www      5580: # ----------------------------------------------------------- Interval timing 
1.149     www      5581: 
1.1153    www      5582: {
                   5583: # Caches needed for speedup of navmaps
                   5584: # We don't want to cache this for very long at all (5 seconds at most)
                   5585: # 
                   5586: # The user for whom we cache
                   5587: my $cachedkey='';
                   5588: # The cached times for this user
                   5589: my %cachedtimes=();
                   5590: # When this was last done
1.1282    raeburn  5591: my $cachedtime='';
1.1153    www      5592: 
                   5593: sub load_all_first_access {
1.1308    raeburn  5594:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5595:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5596:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5597:         (!$ignorecache)) {
1.1154    raeburn  5598:         return;
                   5599:     }
                   5600:     $cachedtime=time;
                   5601:     $cachedkey=$uname.':'.$udom;
                   5602:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5603: }
                   5604: 
1.504     albertel 5605: sub get_first_access {
1.1308    raeburn  5606:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5607:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5608:     if ($argsymb) { $symb=$argsymb; }
                   5609:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5610:     if ($argmap) { $map = $argmap; }
1.926     albertel 5611:     if ($type eq 'course') {
                   5612: 	$res='course';
                   5613:     } elsif ($type eq 'map') {
1.588     albertel 5614: 	$res=&symbread($map);
                   5615:     } else {
                   5616: 	$res=$symb;
                   5617:     }
1.1308    raeburn  5618:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5619:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5620: }
                   5621: 
                   5622: sub set_first_access {
1.1162    raeburn  5623:     my ($type,$interval)=@_;
1.790     albertel 5624:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5625:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5626:     if ($type eq 'course') {
                   5627: 	$res='course';
                   5628:     } elsif ($type eq 'map') {
1.588     albertel 5629: 	$res=&symbread($map);
                   5630:     } else {
                   5631: 	$res=$symb;
                   5632:     }
1.1153    www      5633:     $cachedkey='';
1.1162    raeburn  5634:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5635:     if ($firstaccess) {
                   5636:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5637:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5638:                  "in $courseid");
1.1386    raeburn  5639:         return 'already_set';
                   5640:     } else {
1.1162    raeburn  5641:         my $start = time;
                   5642: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5643:                           $udom,$uname);
                   5644:         if ($putres eq 'ok') {
                   5645:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5646:                  $udom,$uname); 
                   5647:             &appenv(
                   5648:                      {
                   5649:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5650:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5651:                      }
                   5652:                   );
1.1365    raeburn  5653:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5654:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5655:             }
1.1386    raeburn  5656:         } elsif ($putres ne 'refused') {
                   5657:             &logthis("Result: $putres when attempting to set first access time ".
                   5658:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5659:         }
                   5660:         return $putres;
1.505     albertel 5661:     }
                   5662:     return 'already_set';
1.504     albertel 5663: }
1.1153    www      5664: }
1.1282    raeburn  5665: 
1.110     www      5666: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5667: 
                   5668: sub expirespread {
                   5669:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5670:     my $cid=$env{'request.course.id'}; 
1.110     www      5671:     if ($cid) {
                   5672:        my $now=time;
                   5673:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5674:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5675:                             $env{'course.'.$cid.'.num'}.
1.110     www      5676: 	        	    ':nohist_expirationdates:'.
                   5677:                             &escape($key).'='.$now,
1.620     albertel 5678:                             $env{'course.'.$cid.'.home'})
1.110     www      5679:     }
                   5680:     return 'ok';
1.14      www      5681: }
                   5682: 
1.109     www      5683: # ----------------------------------------------------- Devalidate Spreadsheets
                   5684: 
                   5685: sub devalidate {
1.325     www      5686:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5687:     my $cid=$env{'request.course.id'}; 
1.109     www      5688:     if ($cid) {
1.391     matthew  5689:         # delete the stored spreadsheets for
                   5690:         # - the student level sheet of this user in course's homespace
                   5691:         # - the assessment level sheet for this resource 
                   5692:         #   for this user in user's homespace
1.553     albertel 5693: 	# - current conditional state info
1.325     www      5694: 	my $key=$uname.':'.$udom.':';
1.109     www      5695:         my $status=
1.299     matthew  5696: 	    &del('nohist_calculatedsheets',
1.391     matthew  5697: 		 [$key.'studentcalc:'],
1.620     albertel 5698: 		 $env{'course.'.$cid.'.domain'},
                   5699: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5700: 		.' '.
                   5701: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5702: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5703:         unless ($status eq 'ok ok') {
                   5704:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5705:                     $uname.' at '.$udom.' for '.
1.109     www      5706: 		    $symb.': '.$status);
1.133     albertel 5707:         }
1.553     albertel 5708: 	&delenv('user.state.'.$cid);
1.109     www      5709:     }
                   5710: }
                   5711: 
1.265     albertel 5712: sub get_scalar {
                   5713:     my ($string,$end) = @_;
                   5714:     my $value;
                   5715:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5716: 	$value = $1;
                   5717:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5718: 	$value = $1;
                   5719:     }
                   5720:     return &unescape($value);
                   5721: }
                   5722: 
                   5723: sub array2str {
                   5724:   my (@array) = @_;
                   5725:   my $result=&arrayref2str(\@array);
                   5726:   $result=~s/^__ARRAY_REF__//;
                   5727:   $result=~s/__END_ARRAY_REF__$//;
                   5728:   return $result;
                   5729: }
                   5730: 
1.204     albertel 5731: sub arrayref2str {
                   5732:   my ($arrayref) = @_;
1.265     albertel 5733:   my $result='__ARRAY_REF__';
1.204     albertel 5734:   foreach my $elem (@$arrayref) {
1.265     albertel 5735:     if(ref($elem) eq 'ARRAY') {
                   5736:       $result.=&arrayref2str($elem).'&';
                   5737:     } elsif(ref($elem) eq 'HASH') {
                   5738:       $result.=&hashref2str($elem).'&';
                   5739:     } elsif(ref($elem)) {
                   5740:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5741:     } else {
                   5742:       $result.=&escape($elem).'&';
                   5743:     }
                   5744:   }
                   5745:   $result=~s/\&$//;
1.265     albertel 5746:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5747:   return $result;
                   5748: }
                   5749: 
1.168     albertel 5750: sub hash2str {
1.204     albertel 5751:   my (%hash) = @_;
                   5752:   my $result=&hashref2str(\%hash);
1.265     albertel 5753:   $result=~s/^__HASH_REF__//;
                   5754:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5755:   return $result;
                   5756: }
                   5757: 
                   5758: sub hashref2str {
                   5759:   my ($hashref)=@_;
1.265     albertel 5760:   my $result='__HASH_REF__';
1.800     albertel 5761:   foreach my $key (sort(keys(%$hashref))) {
                   5762:     if (ref($key) eq 'ARRAY') {
                   5763:       $result.=&arrayref2str($key).'=';
                   5764:     } elsif (ref($key) eq 'HASH') {
                   5765:       $result.=&hashref2str($key).'=';
                   5766:     } elsif (ref($key)) {
1.265     albertel 5767:       $result.='=';
1.800     albertel 5768:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5769:     } else {
1.1132    raeburn  5770: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5771:     }
                   5772: 
1.800     albertel 5773:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5774:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5775:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5776:       $result.=&hashref2str($hashref->{$key}).'&';
                   5777:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5778:        $result.='&';
1.800     albertel 5779:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5780:     } else {
1.800     albertel 5781:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5782:     }
                   5783:   }
1.168     albertel 5784:   $result=~s/\&$//;
1.265     albertel 5785:   $result .= '__END_HASH_REF__';
1.168     albertel 5786:   return $result;
                   5787: }
                   5788: 
                   5789: sub str2hash {
1.265     albertel 5790:     my ($string)=@_;
                   5791:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5792:     return %$hash;
                   5793: }
                   5794: 
                   5795: sub str2hashref {
1.168     albertel 5796:   my ($string) = @_;
1.265     albertel 5797: 
                   5798:   my %hash;
                   5799: 
                   5800:   if($string !~ /^__HASH_REF__/) {
                   5801:       if (! ($string eq '' || !defined($string))) {
                   5802: 	  $hash{'error'}='Not hash reference';
                   5803:       }
                   5804:       return (\%hash, $string);
                   5805:   }
                   5806: 
                   5807:   $string =~ s/^__HASH_REF__//;
                   5808: 
                   5809:   while($string !~ /^__END_HASH_REF__/) {
                   5810:       #key
                   5811:       my $key='';
                   5812:       if($string =~ /^__HASH_REF__/) {
                   5813:           ($key, $string)=&str2hashref($string);
                   5814:           if(defined($key->{'error'})) {
                   5815:               $hash{'error'}='Bad data';
                   5816:               return (\%hash, $string);
                   5817:           }
                   5818:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5819:           ($key, $string)=&str2arrayref($string);
                   5820:           if($key->[0] eq 'Array reference error') {
                   5821:               $hash{'error'}='Bad data';
                   5822:               return (\%hash, $string);
                   5823:           }
                   5824:       } else {
                   5825:           $string =~ s/^(.*?)=//;
1.267     albertel 5826: 	  $key=&unescape($1);
1.265     albertel 5827:       }
                   5828:       $string =~ s/^=//;
                   5829: 
                   5830:       #value
                   5831:       my $value='';
                   5832:       if($string =~ /^__HASH_REF__/) {
                   5833:           ($value, $string)=&str2hashref($string);
                   5834:           if(defined($value->{'error'})) {
                   5835:               $hash{'error'}='Bad data';
                   5836:               return (\%hash, $string);
                   5837:           }
                   5838:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5839:           ($value, $string)=&str2arrayref($string);
                   5840:           if($value->[0] eq 'Array reference error') {
                   5841:               $hash{'error'}='Bad data';
                   5842:               return (\%hash, $string);
                   5843:           }
                   5844:       } else {
                   5845: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5846:       }
                   5847:       $string =~ s/^&//;
                   5848: 
                   5849:       $hash{$key}=$value;
1.204     albertel 5850:   }
1.265     albertel 5851: 
                   5852:   $string =~ s/^__END_HASH_REF__//;
                   5853: 
                   5854:   return (\%hash, $string);
1.204     albertel 5855: }
                   5856: 
                   5857: sub str2array {
1.265     albertel 5858:     my ($string)=@_;
                   5859:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5860:     return @$array;
                   5861: }
                   5862: 
                   5863: sub str2arrayref {
1.204     albertel 5864:   my ($string) = @_;
1.265     albertel 5865:   my @array;
                   5866: 
                   5867:   if($string !~ /^__ARRAY_REF__/) {
                   5868:       if (! ($string eq '' || !defined($string))) {
                   5869: 	  $array[0]='Array reference error';
                   5870:       }
                   5871:       return (\@array, $string);
                   5872:   }
                   5873: 
                   5874:   $string =~ s/^__ARRAY_REF__//;
                   5875: 
                   5876:   while($string !~ /^__END_ARRAY_REF__/) {
                   5877:       my $value='';
                   5878:       if($string =~ /^__HASH_REF__/) {
                   5879:           ($value, $string)=&str2hashref($string);
                   5880:           if(defined($value->{'error'})) {
                   5881:               $array[0] ='Array reference error';
                   5882:               return (\@array, $string);
                   5883:           }
                   5884:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5885:           ($value, $string)=&str2arrayref($string);
                   5886:           if($value->[0] eq 'Array reference error') {
                   5887:               $array[0] ='Array reference error';
                   5888:               return (\@array, $string);
                   5889:           }
                   5890:       } else {
                   5891: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5892:       }
                   5893:       $string =~ s/^&//;
                   5894: 
                   5895:       push(@array, $value);
1.191     harris41 5896:   }
1.265     albertel 5897: 
                   5898:   $string =~ s/^__END_ARRAY_REF__//;
                   5899: 
                   5900:   return (\@array, $string);
1.168     albertel 5901: }
                   5902: 
1.167     albertel 5903: # -------------------------------------------------------------------Temp Store
                   5904: 
1.168     albertel 5905: sub tmpreset {
                   5906:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5907:   if (!$symb) {
                   5908:     $symb=&symbread();
1.620     albertel 5909:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5910:   }
                   5911:   $symb=escape($symb);
                   5912: 
1.620     albertel 5913:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5914:   $namespace=~s/\//\_/g;
                   5915:   $namespace=~s/\W//g;
                   5916: 
1.620     albertel 5917:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5918:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5919:   if ($domain eq 'public' && $stuname eq 'public') {
                   5920:       $stuname=$ENV{'REMOTE_ADDR'};
                   5921:   }
1.1117    foxr     5922:   my $path=LONCAPA::tempdir();
1.168     albertel 5923:   my %hash;
                   5924:   if (tie(%hash,'GDBM_File',
                   5925: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5926: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5927:     foreach my $key (keys(%hash)) {
1.180     albertel 5928:       if ($key=~ /:$symb/) {
1.168     albertel 5929: 	delete($hash{$key});
                   5930:       }
                   5931:     }
                   5932:   }
                   5933: }
                   5934: 
1.167     albertel 5935: sub tmpstore {
1.168     albertel 5936:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5937: 
                   5938:   if (!$symb) {
                   5939:     $symb=&symbread();
1.620     albertel 5940:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5941:   }
                   5942:   $symb=escape($symb);
                   5943: 
                   5944:   if (!$namespace) {
                   5945:     # I don't think we would ever want to store this for a course.
                   5946:     # it seems this will only be used if we don't have a course.
1.620     albertel 5947:     #$namespace=$env{'request.course.id'};
1.168     albertel 5948:     #if (!$namespace) {
1.620     albertel 5949:       $namespace=$env{'request.state'};
1.168     albertel 5950:     #}
                   5951:   }
                   5952:   $namespace=~s/\//\_/g;
                   5953:   $namespace=~s/\W//g;
1.620     albertel 5954:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5955:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5956:   if ($domain eq 'public' && $stuname eq 'public') {
                   5957:       $stuname=$ENV{'REMOTE_ADDR'};
                   5958:   }
1.168     albertel 5959:   my $now=time;
                   5960:   my %hash;
1.1117    foxr     5961:   my $path=LONCAPA::tempdir();
1.168     albertel 5962:   if (tie(%hash,'GDBM_File',
                   5963: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5964: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5965:     $hash{"version:$symb"}++;
                   5966:     my $version=$hash{"version:$symb"};
                   5967:     my $allkeys=''; 
                   5968:     foreach my $key (keys(%$storehash)) {
                   5969:       $allkeys.=$key.':';
1.591     albertel 5970:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5971:     }
                   5972:     $hash{"$version:$symb:timestamp"}=$now;
                   5973:     $allkeys.='timestamp';
                   5974:     $hash{"$version:keys:$symb"}=$allkeys;
                   5975:     if (untie(%hash)) {
                   5976:       return 'ok';
                   5977:     } else {
                   5978:       return "error:$!";
                   5979:     }
                   5980:   } else {
                   5981:     return "error:$!";
                   5982:   }
                   5983: }
1.167     albertel 5984: 
1.168     albertel 5985: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5986: 
1.168     albertel 5987: sub tmprestore {
                   5988:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5989: 
1.168     albertel 5990:   if (!$symb) {
                   5991:     $symb=&symbread();
1.620     albertel 5992:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5993:   }
                   5994:   $symb=escape($symb);
                   5995: 
1.620     albertel 5996:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5997: 
1.620     albertel 5998:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5999:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6000:   if ($domain eq 'public' && $stuname eq 'public') {
                   6001:       $stuname=$ENV{'REMOTE_ADDR'};
                   6002:   }
1.168     albertel 6003:   my %returnhash;
                   6004:   $namespace=~s/\//\_/g;
                   6005:   $namespace=~s/\W//g;
                   6006:   my %hash;
1.1117    foxr     6007:   my $path=LONCAPA::tempdir();
1.168     albertel 6008:   if (tie(%hash,'GDBM_File',
                   6009: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6010: 	  &GDBM_READER(),0640)) {
1.168     albertel 6011:     my $version=$hash{"version:$symb"};
                   6012:     $returnhash{'version'}=$version;
                   6013:     my $scope;
                   6014:     for ($scope=1;$scope<=$version;$scope++) {
                   6015:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6016:       my @keys=split(/:/,$vkeys);
                   6017:       my $key;
                   6018:       $returnhash{"$scope:keys"}=$vkeys;
                   6019:       foreach $key (@keys) {
1.591     albertel 6020: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6021: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6022:       }
                   6023:     }
1.168     albertel 6024:     if (!(untie(%hash))) {
                   6025:       return "error:$!";
                   6026:     }
                   6027:   } else {
                   6028:     return "error:$!";
                   6029:   }
                   6030:   return %returnhash;
1.167     albertel 6031: }
                   6032: 
1.9       www      6033: # ----------------------------------------------------------------------- Store
                   6034: 
                   6035: sub store {
1.1269    raeburn  6036:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6037:     my $home='';
                   6038: 
1.168     albertel 6039:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6040: 
1.213     www      6041:     $symb=&symbclean($symb);
1.122     albertel 6042:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6043: 
1.620     albertel 6044:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6045:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6046: 
                   6047:     &devalidate($symb,$stuname,$domain);
1.109     www      6048: 
                   6049:     $symb=escape($symb);
1.187     www      6050:     if (!$namespace) { 
1.620     albertel 6051:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6052:           return ''; 
                   6053:        } 
                   6054:     }
1.620     albertel 6055:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6056: 
                   6057:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6058:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6059: 
1.12      www      6060:     my $namevalue='';
1.800     albertel 6061:     foreach my $key (keys(%$storehash)) {
                   6062:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6063:     }
1.12      www      6064:     $namevalue=~s/\&$//;
1.187     www      6065:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6066:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6067: }
                   6068: 
1.47      www      6069: # -------------------------------------------------------------- Critical Store
                   6070: 
                   6071: sub cstore {
1.1269    raeburn  6072:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6073:     my $home='';
                   6074: 
1.168     albertel 6075:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6076: 
1.213     www      6077:     $symb=&symbclean($symb);
1.122     albertel 6078:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6079: 
1.620     albertel 6080:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6081:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6082: 
                   6083:     &devalidate($symb,$stuname,$domain);
1.109     www      6084: 
                   6085:     $symb=escape($symb);
1.187     www      6086:     if (!$namespace) { 
1.620     albertel 6087:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6088:           return ''; 
                   6089:        } 
                   6090:     }
1.620     albertel 6091:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6092: 
                   6093:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6094:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6095: 
1.47      www      6096:     my $namevalue='';
1.800     albertel 6097:     foreach my $key (keys(%$storehash)) {
                   6098:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6099:     }
1.47      www      6100:     $namevalue=~s/\&$//;
1.187     www      6101:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6102:     return critical
1.1269    raeburn  6103:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6104: }
                   6105: 
1.9       www      6106: # --------------------------------------------------------------------- Restore
                   6107: 
                   6108: sub restore {
1.124     www      6109:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6110:     my $home='';
                   6111: 
1.168     albertel 6112:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6113: 
1.122     albertel 6114:     if (!$symb) {
1.1224    raeburn  6115:         return if ($namespace eq 'courserequests');
                   6116:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6117:     } else {
1.1224    raeburn  6118:         unless ($namespace eq 'courserequests') {
                   6119:             $symb=&escape(&symbclean($symb));
                   6120:         }
1.122     albertel 6121:     }
1.188     www      6122:     if (!$namespace) { 
1.620     albertel 6123:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6124:           return ''; 
                   6125:        } 
                   6126:     }
1.620     albertel 6127:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6128:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6129:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6130:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6131: 
1.12      www      6132:     my %returnhash=();
1.800     albertel 6133:     foreach my $line (split(/\&/,$answer)) {
                   6134: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6135:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6136:     }
1.75      www      6137:     my $version;
                   6138:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6139:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6140:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6141:        }
1.75      www      6142:     }
1.13      www      6143:     return %returnhash;
1.34      www      6144: }
                   6145: 
                   6146: # ---------------------------------------------------------- Course Description
1.1118    foxr     6147: #
                   6148: #  
1.34      www      6149: 
                   6150: sub coursedescription {
1.731     albertel 6151:     my ($courseid,$args)=@_;
1.34      www      6152:     $courseid=~s/^\///;
1.49      www      6153:     $courseid=~s/\_/\//g;
1.34      www      6154:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6155:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6156:     my $normalid=$cdomain.'_'.$cnum;
                   6157:     # need to always cache even if we get errors otherwise we keep 
                   6158:     # trying and trying and trying to get the course description.
                   6159:     my %envhash=();
                   6160:     my %returnhash=();
1.731     albertel 6161:     
                   6162:     my $expiretime=600;
                   6163:     if ($env{'request.course.id'} eq $normalid) {
                   6164: 	$expiretime=120;
                   6165:     }
                   6166: 
                   6167:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6168:     if (!$args->{'freshen_cache'}
                   6169: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6170: 	foreach my $key (keys(%env)) {
                   6171: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6172: 	    my ($setting) = $1;
                   6173: 	    $returnhash{$setting} = $env{$key};
                   6174: 	}
                   6175: 	return %returnhash;
                   6176:     }
                   6177: 
1.1118    foxr     6178:     # get the data again
                   6179: 
1.731     albertel 6180:     if (!$args->{'one_time'}) {
                   6181: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6182:     }
1.811     albertel 6183: 
1.34      www      6184:     if ($chome ne 'no_host') {
1.302     albertel 6185:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6186:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6187: 	   my $username = $env{'user.name'}; # Defult username
                   6188: 	   if(defined $args->{'user'}) {
                   6189: 	       $username = $args->{'user'};
                   6190: 	   }
1.129     albertel 6191:            $returnhash{'home'}= $chome;
                   6192: 	   $returnhash{'domain'} = $cdomain;
                   6193: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6194:            if (!defined($returnhash{'type'})) {
                   6195:                $returnhash{'type'} = 'Course';
                   6196:            }
1.130     albertel 6197:            while (my ($name,$value) = each %returnhash) {
1.53      www      6198:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6199:            }
1.270     www      6200:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6201:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6202: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6203:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6204:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6205:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6206:        }
                   6207:     }
1.731     albertel 6208:     if (!$args->{'one_time'}) {
1.949     raeburn  6209: 	&appenv(\%envhash);
1.731     albertel 6210:     }
1.302     albertel 6211:     return %returnhash;
1.461     www      6212: }
                   6213: 
1.1080    raeburn  6214: sub update_released_required {
                   6215:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6216:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6217:         $cid = $env{'request.course.id'};
                   6218:         $cdom = $env{'course.'.$cid.'.domain'};
                   6219:         $cnum = $env{'course.'.$cid.'.num'};
                   6220:         $chome = $env{'course.'.$cid.'.home'};
                   6221:     }
                   6222:     if ($needsrelease) {
                   6223:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6224:         my $needsupdate;
                   6225:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6226:             $needsupdate = 1;
                   6227:         } else {
                   6228:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6229:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6230:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6231:                 $needsupdate = 1;
                   6232:             }
                   6233:         }
                   6234:         if ($needsupdate) {
                   6235:             my %needshash = (
                   6236:                              'internal.releaserequired' => $needsrelease,
                   6237:                             );
                   6238:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6239:             if ($putresult eq 'ok') {
                   6240:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6241:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6242:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6243:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6244:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6245:                 }
                   6246:             }
                   6247:         }
                   6248:     }
                   6249:     return;
                   6250: }
                   6251: 
1.461     www      6252: # -------------------------------------------------See if a user is privileged
                   6253: 
                   6254: sub privileged {
1.1219    raeburn  6255:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6256:     my $now = time;
1.1219    raeburn  6257:     my $roles;
                   6258:     if (ref($possroles) eq 'ARRAY') {
                   6259:         $roles = $possroles; 
                   6260:     } else {
                   6261:         $roles = ['dc','su'];
                   6262:     }
                   6263:     if (ref($possdomains) eq 'ARRAY') {
                   6264:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6265:         foreach my $dom (@{$possdomains}) {
                   6266:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6267:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6268:                 foreach my $role (@{$roles}) {
                   6269:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6270:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6271:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6272:                             return 1 unless (($end && $end < $now) ||
                   6273:                                              ($start && $start > $now));
                   6274:                         }
                   6275:                     }
                   6276:                 }
                   6277:             }
                   6278:         }
                   6279:     } else {
                   6280:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6281:         my $now = time;
1.1170    droeschl 6282: 
1.1275    musolffc 6283:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6284:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6285:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6286:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6287:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6288:             }
1.1219    raeburn  6289:         }
                   6290:     }
                   6291:     return 0;
                   6292: }
1.1170    droeschl 6293: 
1.1219    raeburn  6294: sub privileged_by_domain {
                   6295:     my ($domains,$roles) = @_;
                   6296:     my %privileged = ();
                   6297:     my $cachetime = 60*60*24;
                   6298:     my $now = time;
                   6299:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6300:         return %privileged;
                   6301:     }
                   6302:     foreach my $dom (@{$domains}) {
                   6303:         next if (ref($privileged{$dom}) eq 'HASH');
                   6304:         my $needroles;
                   6305:         foreach my $role (@{$roles}) {
                   6306:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6307:             if (defined($cached)) {
                   6308:                 if (ref($result) eq 'HASH') {
                   6309:                     $privileged{$dom}{$role} = $result;
                   6310:                 }
                   6311:             } else {
                   6312:                 $needroles = 1;
                   6313:             }
                   6314:         }
                   6315:         if ($needroles) {
                   6316:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6317:             $privileged{$dom} = {};
                   6318:             foreach my $server (keys(%dompersonnel)) {
                   6319:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6320:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6321:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6322:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6323:                         next if ($end && $end < $now);
                   6324:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6325:                             $dompersonnel{$server}{$item};
                   6326:                     }
                   6327:                 }
                   6328:             }
                   6329:             if (ref($privileged{$dom}) eq 'HASH') {
                   6330:                 foreach my $role (@{$roles}) {
                   6331:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6332:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6333:                     } else {
                   6334:                         my %hash = ();
                   6335:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6336:                     }
                   6337:                 }
                   6338:             }
                   6339:         }
                   6340:     }
                   6341:     return %privileged;
1.9       www      6342: }
1.1       albertel 6343: 
1.103     harris41 6344: # -------------------------------------------------------- Get user privileges
1.11      www      6345: 
                   6346: sub rolesinit {
1.1169    droeschl 6347:     my ($domain, $username) = @_;
                   6348:     my %userroles = ('user.login.time' => time);
                   6349:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6350: 
                   6351:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6352:     # also, blocking can be triggered by an activating timer
                   6353:     # it's saved in the user's %env.
                   6354:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6355:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6356:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6357:         %timerintchk, %timerintenv);
                   6358: 
1.1162    raeburn  6359:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6360:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6361:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6362:     }
1.1169    droeschl 6363: 
1.1162    raeburn  6364:     foreach my $key (keys(%timerinterval)) {
                   6365:         my ($cid,$rest) = split(/\0/,$key);
                   6366:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6367:     }
1.1169    droeschl 6368: 
1.11      www      6369:     my %allroles=();
1.1162    raeburn  6370:     my %allgroups=();
1.11      www      6371: 
1.1274    raeburn  6372:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6373:         my $role = $rolesdump{$area};
                   6374:         $area =~ s/\_\w\w$//;
                   6375: 
                   6376:         my ($trole, $tend, $tstart, $group_privs);
                   6377: 
                   6378:         if ($role =~ /^cr/) {
                   6379:         # Custom role, defined by a user 
                   6380:         # e.g., user.role.cr/msu/smith/mynewrole
                   6381:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6382:                 $trole = $1;
                   6383:                 ($tend, $tstart) = split('_', $2);
                   6384:             } else {
                   6385:                 $trole = $role;
                   6386:             }
                   6387:         } elsif ($role =~ m|^gr/|) {
                   6388:         # Role of member in a group, defined within a course/community
                   6389:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6390:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6391:             next if $tstart eq '-1';
                   6392:             ($trole, $group_privs) = split(/\//, $trole);
                   6393:             $group_privs = &unescape($group_privs);
                   6394:         } else {
                   6395:         # Just a normal role, defined in roles.tab
                   6396:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6397:         }
                   6398: 
                   6399:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6400:                  $username);
                   6401:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6402: 
                   6403:         # role expired or not available yet?
                   6404:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6405:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6406: 
                   6407:         next if $area eq '' or $trole eq '';
                   6408: 
                   6409:         my $spec = "$trole.$area";
                   6410:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6411: 
                   6412:         if ($trole =~ /^cr\//) {
                   6413:         # Custom role, defined by a user
                   6414:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6415:         } elsif ($trole eq 'gr') {
                   6416:         # Role of a member in a group, defined within a course/community
                   6417:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6418:             next;
                   6419:         } else {
                   6420:         # Normal role, defined in roles.tab
                   6421:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6422:         }
                   6423: 
                   6424:         my $cid = $tdomain.'_'.$trest;
                   6425:         unless ($firstaccchk{$cid}) {
                   6426:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6427:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6428:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6429:                         $coursetimerstarts{$cid}{$item}; 
                   6430:                 }
                   6431:             }
                   6432:             $firstaccchk{$cid} = 1;
                   6433:         }
                   6434:         unless ($timerintchk{$cid}) {
                   6435:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6436:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6437:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6438:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6439:                 }
1.12      www      6440:             }
1.1169    droeschl 6441:             $timerintchk{$cid} = 1;
1.191     harris41 6442:         }
1.11      www      6443:     }
1.1169    droeschl 6444: 
1.1341    raeburn  6445:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6446:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6447:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6448:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6449: 
1.1162    raeburn  6450:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6451: }
                   6452: 
1.567     raeburn  6453: sub set_arearole {
1.1215    raeburn  6454:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6455:     unless ($nolog) {
1.567     raeburn  6456: # log the associated role with the area
1.1215    raeburn  6457:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6458:     }
1.743     albertel 6459:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6460: }
                   6461: 
                   6462: sub custom_roleprivs {
                   6463:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6464:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6465:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6466:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6467:         my ($rdummy,$roledef)=
                   6468:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6469:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6470:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6471:             if (defined($syspriv)) {
1.1043    raeburn  6472:                 if ($trest =~ /^$match_community$/) {
                   6473:                     $syspriv =~ s/bre\&S//; 
                   6474:                 }
1.567     raeburn  6475:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6476:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6477:             }
                   6478:             if ($tdomain ne '') {
                   6479:                 if (defined($dompriv)) {
                   6480:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6481:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6482:                 }
                   6483:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6484:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6485:                         my $rolename = $1;
                   6486:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6487:                     }
1.567     raeburn  6488:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6489:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6490:                 }
                   6491:             }
                   6492:         }
                   6493:     }
                   6494: }
                   6495: 
1.1332    raeburn  6496: sub course_adhocrole_privs {
                   6497:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6498:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6499:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6500:         my (%currprivs,%storeprivs);
                   6501:         foreach my $item (split(/:/,$coursepriv)) {
                   6502:             my ($priv,$restrict) = split(/\&/,$item);
                   6503:             $currprivs{$priv} = $restrict;
                   6504:         }
                   6505:         my (%possadd,%possremove,%full);
                   6506:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6507:             my ($priv,$restrict)=split(/\&/,$item);
                   6508:             $full{$priv} = $restrict;
                   6509:         }
                   6510:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6511:              next if ($item eq '');
                   6512:              my ($rule,$rest) = split(/=/,$item);
                   6513:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6514:              foreach my $priv (split(/:/,$rest)) {
                   6515:                  if ($priv ne '') {
                   6516:                      if ($rule eq 'off') {
                   6517:                          $possremove{$priv} = 1;
                   6518:                      } else {
                   6519:                          $possadd{$priv} = 1;
                   6520:                      }
                   6521:                  }
                   6522:              }
                   6523:          }
                   6524:          foreach my $priv (sort(keys(%full))) {
                   6525:              if (exists($currprivs{$priv})) {
                   6526:                  unless (exists($possremove{$priv})) {
                   6527:                      $storeprivs{$priv} = $currprivs{$priv};
                   6528:                  }
                   6529:              } elsif (exists($possadd{$priv})) {
                   6530:                  $storeprivs{$priv} = $full{$priv};
                   6531:              }
                   6532:          }
                   6533:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6534:      }
                   6535:      return $coursepriv;
                   6536: }
                   6537: 
1.678     raeburn  6538: sub group_roleprivs {
                   6539:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6540:     my $access = 1;
                   6541:     my $now = time;
                   6542:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6543:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6544:     if ($access) {
1.811     albertel 6545:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6546:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6547:     }
                   6548: }
1.567     raeburn  6549: 
                   6550: sub standard_roleprivs {
                   6551:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6552:     if (defined($pr{$trole.':s'})) {
                   6553:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6554:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6555:     }
                   6556:     if ($tdomain ne '') {
                   6557:         if (defined($pr{$trole.':d'})) {
                   6558:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6559:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6560:         }
                   6561:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6562:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6563:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6564:         }
                   6565:     }
                   6566: }
                   6567: 
                   6568: sub set_userprivs {
1.1064    raeburn  6569:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6570:     my $author=0;
                   6571:     my $adv=0;
1.1341    raeburn  6572:     my $rar=0;
1.678     raeburn  6573:     my %grouproles = ();
                   6574:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6575:         my @groupkeys; 
1.1000    raeburn  6576:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6577:             push(@groupkeys,$role);
                   6578:         }
                   6579:         if (ref($groups_roles) eq 'HASH') {
                   6580:             foreach my $key (keys(%{$groups_roles})) {
                   6581:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6582:                     push(@groupkeys,$key);
                   6583:                 }
                   6584:             }
                   6585:         }
                   6586:         if (@groupkeys > 0) {
                   6587:             foreach my $role (@groupkeys) {
                   6588:                 my ($trole,$area,$sec,$extendedarea);
                   6589:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6590:                     $trole = $1;
                   6591:                     $area = $2;
                   6592:                     $sec = $3;
                   6593:                     $extendedarea = $area.$sec;
                   6594:                     if (exists($$allgroups{$area})) {
                   6595:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6596:                             my $spec = $trole.'.'.$extendedarea;
                   6597:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6598:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6599:                         }
1.678     raeburn  6600:                     }
                   6601:                 }
                   6602:             }
                   6603:         }
                   6604:     }
1.800     albertel 6605:     foreach my $group (keys(%grouproles)) {
                   6606:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6607:     }
1.800     albertel 6608:     foreach my $role (keys(%{$allroles})) {
                   6609:         my %thesepriv;
1.941     raeburn  6610:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6611:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6612:             if ($item ne '') {
                   6613:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6614:                 if ($restrictions eq '') {
                   6615:                     $thesepriv{$privilege}='F';
                   6616:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6617:                     $thesepriv{$privilege}.=$restrictions;
                   6618:                 }
                   6619:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6620:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6621:             }
                   6622:         }
                   6623:         my $thesestr='';
1.1104    raeburn  6624:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6625: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6626: 	}
                   6627:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6628:     }
1.1341    raeburn  6629:     return ($author,$adv,$rar);
1.567     raeburn  6630: }
                   6631: 
1.994     raeburn  6632: sub role_status {
1.1104    raeburn  6633:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6634:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6635:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6636:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6637:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6638:             $$where = '/'.$two;
1.994     raeburn  6639:             $$trolecode=$$role.'.'.$$where;
                   6640:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6641:             $$tstatus='is';
1.1104    raeburn  6642:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6643:                 $$tstatus='future';
1.1034    raeburn  6644:                 if ($$tstart<$now) {
                   6645:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6646:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6647:                             my (%allroles,%allgroups,$group_privs,
                   6648:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6649:                             my %userroles = (
                   6650:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6651:                             );
1.1064    raeburn  6652:                             @rolecodes = ('cm'); 
1.1002    raeburn  6653:                             my $spec=$$role.'.'.$$where;
                   6654:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6655:                             if ($$role =~ /^cr\//) {
                   6656:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6657:                                 push(@rolecodes,'cr');
1.1002    raeburn  6658:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6659:                                 push(@rolecodes,$$role);
1.1002    raeburn  6660:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6661:                                                     $env{'user.name'});
1.1064    raeburn  6662:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6663:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6664:                                 $group_privs = &unescape($group_privs);
                   6665:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6666:                                 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  6667:                                 &get_groups_roles($tdomain,$trest,
                   6668:                                                   \%course_roles,\@rolecodes,
                   6669:                                                   \%groups_roles);
1.1002    raeburn  6670:                             } else {
1.1064    raeburn  6671:                                 push(@rolecodes,$$role);
1.1002    raeburn  6672:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6673:                             }
1.1341    raeburn  6674:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6675:                                                                    \%groups_roles);
1.1064    raeburn  6676:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6677:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6678:                         }
                   6679:                     }
1.1034    raeburn  6680:                     $$tstatus = 'is';
1.1002    raeburn  6681:                 }
1.994     raeburn  6682:             }
                   6683:             if ($$tend) {
1.1104    raeburn  6684:                 if ($$tend<$update) {
1.994     raeburn  6685:                     $$tstatus='expired';
                   6686:                 } elsif ($$tend<$now) {
                   6687:                     $$tstatus='will_not';
                   6688:                 }
                   6689:             }
                   6690:         }
                   6691:     }
                   6692: }
                   6693: 
1.1104    raeburn  6694: sub get_groups_roles {
                   6695:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6696:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6697:                   (ref($rolecodes) eq 'ARRAY') && 
                   6698:                   (ref($groups_roles) eq 'HASH')); 
                   6699:     if (keys(%{$cdom_courseroles}) > 0) {
                   6700:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6701:         if ($cdom ne '' && $cnum ne '') {
                   6702:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6703:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6704:                     my $crsrole = $1;
                   6705:                     my $crssec = $2;
                   6706:                     if ($crsrole =~ /^cr/) {
                   6707:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6708:                             push(@{$rolecodes},'cr');
                   6709:                         }
                   6710:                     } else {
                   6711:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6712:                             push(@{$rolecodes},$crsrole);
                   6713:                         }
                   6714:                     }
                   6715:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6716:                     if ($crssec ne '') {
                   6717:                         $rolekey .= "/$crssec";
                   6718:                     }
                   6719:                     $rolekey .= './';
                   6720:                     $groups_roles->{$rolekey} = $rolecodes;
                   6721:                 }
                   6722:             }
                   6723:         }
                   6724:     }
                   6725:     return;
                   6726: }
                   6727: 
                   6728: sub delete_env_groupprivs {
                   6729:     my ($where,$courseroles,$possroles) = @_;
                   6730:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6731:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6732:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6733:         %{$courseroles->{$udom}} =
                   6734:             &get_my_roles('','','userroles',['active'],
                   6735:                           $possroles,[$udom],1);
                   6736:     }
                   6737:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6738:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6739:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6740:             my $area = '/'.$cdom.'/'.$cnum;
                   6741:             my $privkey = "user.priv.$crsrole.$area";
                   6742:             if ($crssec ne '') {
                   6743:                 $privkey .= '/'.$crssec;
                   6744:             }
                   6745:             $privkey .= ".$area/$group";
                   6746:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6747:         }
                   6748:     }
                   6749:     return;
                   6750: }
                   6751: 
1.994     raeburn  6752: sub check_adhoc_privs {
1.1329    raeburn  6753:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6754:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6755:     if ($sec) {
                   6756:         $cckey .= '/'.$sec;
                   6757:     } 
1.1185    raeburn  6758:     my $setprivs;
1.994     raeburn  6759:     if ($env{$cckey}) {
                   6760:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6761:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6762:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6763:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6764:             $setprivs = 1;
1.994     raeburn  6765:         }
                   6766:     } else {
1.1330    raeburn  6767:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6768:         $setprivs = 1;
1.994     raeburn  6769:     }
1.1185    raeburn  6770:     return $setprivs;
1.994     raeburn  6771: }
                   6772: 
                   6773: sub set_adhoc_privileges {
1.1326    raeburn  6774: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6775:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6776:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6777:     if ($sec ne '') {
                   6778:         $area .= '/'.$sec;
                   6779:     }
1.994     raeburn  6780:     my $spec = $role.'.'.$area;
                   6781:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6782:                                   $env{'user.name'},1);
1.1326    raeburn  6783:     my %rolehash = ();
1.1332    raeburn  6784:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6785:         my $rolename = $1;
1.1326    raeburn  6786:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6787:         my %domdef = &get_domain_defaults($dcdom);
                   6788:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6789:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6790:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6791:             }
                   6792:         }
1.1326    raeburn  6793:     } else {
                   6794:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6795:     }
1.1341    raeburn  6796:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6797:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6798:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  6799:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6800:             ($caller eq 'tiny')) {
1.1088    raeburn  6801:         &appenv( {'request.role'        => $spec,
                   6802:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6803:                   'request.course.sec'  => $sec,
1.1088    raeburn  6804:                  }
                   6805:                );
                   6806:         my $tadv=0;
                   6807:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6808:         &appenv({'request.role.adv'    => $tadv});
                   6809:     }
1.994     raeburn  6810: }
                   6811: 
1.12      www      6812: # --------------------------------------------------------------- get interface
                   6813: 
                   6814: sub get {
1.131     albertel 6815:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6816:    my $items='';
1.800     albertel 6817:    foreach my $item (@$storearr) {
                   6818:        $items.=&escape($item).'&';
1.191     harris41 6819:    }
1.12      www      6820:    $items=~s/\&$//;
1.620     albertel 6821:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6822:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6823:    my $uhome=&homeserver($uname,$udomain);
                   6824: 
1.133     albertel 6825:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6826:    my @pairs=split(/\&/,$rep);
1.273     albertel 6827:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6828:      return @pairs;
                   6829:    }
1.15      www      6830:    my %returnhash=();
1.42      www      6831:    my $i=0;
1.800     albertel 6832:    foreach my $item (@$storearr) {
                   6833:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6834:       $i++;
1.191     harris41 6835:    }
1.15      www      6836:    return %returnhash;
1.27      www      6837: }
                   6838: 
                   6839: # --------------------------------------------------------------- del interface
                   6840: 
                   6841: sub del {
1.133     albertel 6842:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6843:    my $items='';
1.800     albertel 6844:    foreach my $item (@$storearr) {
                   6845:        $items.=&escape($item).'&';
1.191     harris41 6846:    }
1.984     neumanie 6847: 
1.27      www      6848:    $items=~s/\&$//;
1.620     albertel 6849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6850:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6851:    my $uhome=&homeserver($uname,$udomain);
                   6852:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6853: }
                   6854: 
                   6855: # -------------------------------------------------------------- dump interface
                   6856: 
1.1180    droeschl 6857: sub unserialize {
                   6858:     my ($rep, $escapedkeys) = @_;
                   6859: 
                   6860:     return {} if $rep =~ /^error/;
                   6861: 
                   6862:     my %returnhash=();
1.1252    raeburn  6863: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6864: 	    my ($key, $value) = split(/=/, $item, 2);
                   6865: 	    $key = unescape($key) unless $escapedkeys;
                   6866: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6867: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6868: 	}
                   6869:     #return %returnhash;
                   6870:     return \%returnhash;
                   6871: }        
                   6872: 
                   6873: # see Lond::dump_with_regexp
                   6874: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6875: sub dump {
1.1180    droeschl 6876:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6877:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6878:     if (!$uname) { $uname=$env{'user.name'}; }
                   6879:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6880: 
1.1266    raeburn  6881:     if ($regexp) {
                   6882:         $regexp=&escape($regexp);
                   6883:     } else {
                   6884:         $regexp='.';
                   6885:     }
1.1180    droeschl 6886:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6887:         # user is hosted on this machine
1.1266    raeburn  6888:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6889:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6890:         return %{unserialize($reply, $escapedkeys)};
                   6891:     }
1.1166    raeburn  6892:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6893:     my @pairs=split(/\&/,$rep);
                   6894:     my %returnhash=();
1.1098    foxr     6895:     if (!($rep =~ /^error/ )) {
                   6896: 	foreach my $item (@pairs) {
                   6897: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6898:         $key = unescape($key) unless $escapedkeys;
                   6899:         #$key = &unescape($key);
1.1098    foxr     6900: 	    next if ($key =~ /^error: 2 /);
                   6901: 	    $returnhash{$key}=&thaw_unescape($value);
                   6902: 	}
1.755     albertel 6903:     }
                   6904:     return %returnhash;
1.407     www      6905: }
                   6906: 
1.1098    foxr     6907: 
1.717     albertel 6908: # --------------------------------------------------------- dumpstore interface
                   6909: 
                   6910: sub dumpstore {
                   6911:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6912:    # same as dump but keys must be escaped. They may contain colon separated
                   6913:    # lists of values that may themself contain colons (e.g. symbs).
                   6914:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6915: }
                   6916: 
1.407     www      6917: # -------------------------------------------------------------- keys interface
                   6918: 
                   6919: sub getkeys {
                   6920:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6921:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6922:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6923:    my $uhome=&homeserver($uname,$udomain);
                   6924:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6925:    my @keyarray=();
1.800     albertel 6926:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6927:       next if ($key =~ /^error: 2 /);
1.800     albertel 6928:       push(@keyarray,&unescape($key));
1.407     www      6929:    }
                   6930:    return @keyarray;
1.318     matthew  6931: }
                   6932: 
1.319     matthew  6933: # --------------------------------------------------------------- currentdump
                   6934: sub currentdump {
1.328     matthew  6935:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6936:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6937:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6938:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6939:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6940:    my $rep;
                   6941: 
                   6942:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6943:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6944:                    $courseid)));
                   6945:    } else {
                   6946:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6947:    }
                   6948: 
1.318     matthew  6949:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6950:    #
1.318     matthew  6951:    my %returnhash=();
1.319     matthew  6952:    #
1.1343    raeburn  6953:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6954:        # an old lond will not know currentdump
                   6955:        # Do a dump and make it look like a currentdump
1.822     albertel 6956:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6957:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6958:        my %hash = @tmp;
                   6959:        @tmp=();
1.424     matthew  6960:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6961:    } else {
                   6962:        my @pairs=split(/\&/,$rep);
1.800     albertel 6963:        foreach my $pair (@pairs) {
                   6964:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6965:            my ($symb,$param) = split(/:/,$key);
                   6966:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6967:                                                         &thaw_unescape($value);
1.319     matthew  6968:        }
1.191     harris41 6969:    }
1.12      www      6970:    return %returnhash;
1.424     matthew  6971: }
                   6972: 
                   6973: sub convert_dump_to_currentdump{
                   6974:     my %hash = %{shift()};
                   6975:     my %returnhash;
                   6976:     # Code ripped from lond, essentially.  The only difference
                   6977:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6978:     # we might run in to problems with parameter names =~ /^v\./
                   6979:     while (my ($key,$value) = each(%hash)) {
                   6980:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6981: 	$symb  = &unescape($symb);
                   6982: 	$param = &unescape($param);
1.424     matthew  6983:         next if ($v eq 'version' || $symb eq 'keys');
                   6984:         next if (exists($returnhash{$symb}) &&
                   6985:                  exists($returnhash{$symb}->{$param}) &&
                   6986:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6987:         $returnhash{$symb}->{$param}=$value;
                   6988:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6989:     }
                   6990:     #
                   6991:     # Remove all of the keys in the hashes which keep track of
                   6992:     # the version of the parameter.
                   6993:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6994:         # use a foreach because we are going to delete from the hash.
                   6995:         foreach my $key (keys(%$param_hash)) {
                   6996:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6997:         }
                   6998:     }
                   6999:     return \%returnhash;
1.12      www      7000: }
                   7001: 
1.627     albertel 7002: # ------------------------------------------------------ critical inc interface
                   7003: 
                   7004: sub cinc {
                   7005:     return &inc(@_,'critical');
                   7006: }
                   7007: 
1.449     matthew  7008: # --------------------------------------------------------------- inc interface
                   7009: 
                   7010: sub inc {
1.627     albertel 7011:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7012:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7013:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7014:     my $uhome=&homeserver($uname,$udomain);
                   7015:     my $items='';
                   7016:     if (! ref($store)) {
                   7017:         # got a single value, so use that instead
                   7018:         $items = &escape($store).'=&';
                   7019:     } elsif (ref($store) eq 'SCALAR') {
                   7020:         $items = &escape($$store).'=&';        
                   7021:     } elsif (ref($store) eq 'ARRAY') {
                   7022:         $items = join('=&',map {&escape($_);} @{$store});
                   7023:     } elsif (ref($store) eq 'HASH') {
                   7024:         while (my($key,$value) = each(%{$store})) {
                   7025:             $items.= &escape($key).'='.&escape($value).'&';
                   7026:         }
                   7027:     }
                   7028:     $items=~s/\&$//;
1.627     albertel 7029:     if ($critical) {
                   7030: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7031:     } else {
                   7032: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7033:     }
1.449     matthew  7034: }
                   7035: 
1.12      www      7036: # --------------------------------------------------------------- put interface
                   7037: 
                   7038: sub put {
1.134     albertel 7039:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7040:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7041:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7042:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7043:    my $items='';
1.800     albertel 7044:    foreach my $item (keys(%$storehash)) {
                   7045:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7046:    }
1.12      www      7047:    $items=~s/\&$//;
1.134     albertel 7048:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7049: }
                   7050: 
1.631     albertel 7051: # ------------------------------------------------------------ newput interface
                   7052: 
                   7053: sub newput {
                   7054:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7055:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7056:    if (!$uname) { $uname=$env{'user.name'}; }
                   7057:    my $uhome=&homeserver($uname,$udomain);
                   7058:    my $items='';
                   7059:    foreach my $key (keys(%$storehash)) {
                   7060:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7061:    }
                   7062:    $items=~s/\&$//;
                   7063:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7064: }
                   7065: 
                   7066: # ---------------------------------------------------------  putstore interface
                   7067: 
1.524     raeburn  7068: sub putstore {
1.1269    raeburn  7069:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7070:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7071:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7072:    my $uhome=&homeserver($uname,$udomain);
                   7073:    my $items='';
1.715     albertel 7074:    foreach my $key (keys(%$storehash)) {
                   7075:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7076:    }
1.715     albertel 7077:    $items=~s/\&$//;
1.716     albertel 7078:    my $esc_symb=&escape($symb);
                   7079:    my $esc_v=&escape($version);
1.715     albertel 7080:    my $reply =
1.716     albertel 7081:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7082: 	      $uhome);
1.1269    raeburn  7083:    if (($tolog) && ($reply eq 'ok')) {
                   7084:        my $namevalue='';
                   7085:        foreach my $key (keys(%{$storehash})) {
                   7086:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7087:        }
                   7088:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7089:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7090:                      '&version='.$esc_v.
                   7091:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7092:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7093:    }
1.715     albertel 7094:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7095:        # gfall back to way things use to be done
1.715     albertel 7096:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7097: 			    $uname);
1.524     raeburn  7098:    }
1.715     albertel 7099:    return $reply;
                   7100: }
                   7101: 
                   7102: sub old_putstore {
1.716     albertel 7103:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7104:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7105:     if (!$uname) { $uname=$env{'user.name'}; }
                   7106:     my $uhome=&homeserver($uname,$udomain);
                   7107:     my %newstorehash;
1.800     albertel 7108:     foreach my $item (keys(%$storehash)) {
                   7109: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7110: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7111:     }
                   7112:     my $items='';
                   7113:     my %allitems = ();
1.800     albertel 7114:     foreach my $item (keys(%newstorehash)) {
                   7115: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7116: 	    my $key = $1.':keys:'.$2;
                   7117: 	    $allitems{$key} .= $3.':';
                   7118: 	}
1.800     albertel 7119: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7120:     }
1.800     albertel 7121:     foreach my $item (keys(%allitems)) {
                   7122: 	$allitems{$item} =~ s/\:$//;
                   7123: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7124:     }
                   7125:     $items=~s/\&$//;
                   7126:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7127: }
                   7128: 
1.47      www      7129: # ------------------------------------------------------ critical put interface
                   7130: 
                   7131: sub cput {
1.134     albertel 7132:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7133:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7134:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7135:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7136:    my $items='';
1.800     albertel 7137:    foreach my $item (keys(%$storehash)) {
                   7138:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7139:    }
1.47      www      7140:    $items=~s/\&$//;
1.134     albertel 7141:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7142: }
                   7143: 
                   7144: # -------------------------------------------------------------- eget interface
                   7145: 
                   7146: sub eget {
1.133     albertel 7147:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7148:    my $items='';
1.800     albertel 7149:    foreach my $item (@$storearr) {
                   7150:        $items.=&escape($item).'&';
1.191     harris41 7151:    }
1.12      www      7152:    $items=~s/\&$//;
1.620     albertel 7153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7154:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7155:    my $uhome=&homeserver($uname,$udomain);
                   7156:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7157:    my @pairs=split(/\&/,$rep);
                   7158:    my %returnhash=();
1.42      www      7159:    my $i=0;
1.800     albertel 7160:    foreach my $item (@$storearr) {
                   7161:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7162:       $i++;
1.191     harris41 7163:    }
1.12      www      7164:    return %returnhash;
                   7165: }
                   7166: 
1.667     albertel 7167: # ------------------------------------------------------------ tmpput interface
                   7168: sub tmpput {
1.802     raeburn  7169:     my ($storehash,$server,$context)=@_;
1.667     albertel 7170:     my $items='';
1.800     albertel 7171:     foreach my $item (keys(%$storehash)) {
                   7172: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7173:     }
                   7174:     $items=~s/\&$//;
1.802     raeburn  7175:     if (defined($context)) {
                   7176:         $items .= ':'.&escape($context);
                   7177:     }
1.667     albertel 7178:     return &reply("tmpput:$items",$server);
                   7179: }
                   7180: 
                   7181: # ------------------------------------------------------------ tmpget interface
                   7182: sub tmpget {
1.688     albertel 7183:     my ($token,$server)=@_;
                   7184:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7185:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7186:     my %returnhash;
1.1328    raeburn  7187:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7188:         return %returnhash;
                   7189:     }
1.667     albertel 7190:     foreach my $item (split(/\&/,$rep)) {
                   7191: 	my ($key,$value)=split(/=/,$item);
                   7192: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7193:     }
                   7194:     return %returnhash;
                   7195: }
                   7196: 
1.1113    raeburn  7197: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7198: sub tmpdel {
                   7199:     my ($token,$server)=@_;
                   7200:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7201:     return &reply("tmpdel:$token",$server);
                   7202: }
                   7203: 
1.1198    raeburn  7204: # ------------------------------------------------------------ get_timebased_id 
                   7205: 
                   7206: sub get_timebased_id {
                   7207:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7208:         $maxtries) = @_;
                   7209:     my ($newid,$error,$dellock);
                   7210:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7211:         return ('','ok','invalid call to get suffix');
                   7212:     }
                   7213: 
                   7214: # set defaults for any optional args for which values were not supplied
                   7215:     if ($who eq '') {
                   7216:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7217:     }
                   7218:     if (!$locktries) {
                   7219:         $locktries = 3;
                   7220:     }
                   7221:     if (!$maxtries) {
                   7222:         $maxtries = 10;
                   7223:     }
                   7224:     
                   7225:     if (($cdom eq '') || ($cnum eq '')) {
                   7226:         if ($env{'request.course.id'}) {
                   7227:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7228:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7229:         }
                   7230:         if (($cdom eq '') || ($cnum eq '')) {
                   7231:             return ('','ok','call to get suffix not in course context');
                   7232:         }
                   7233:     }
                   7234: 
                   7235: # construct locking item
                   7236:     my $lockhash = {
                   7237:                       $prefix."\0".'locked_'.$keyid => $who,
                   7238:                    };
                   7239:     my $tries = 0;
                   7240: 
                   7241: # attempt to get lock on nohist_$namespace file
                   7242:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7243:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7244:         $tries ++;
                   7245:         sleep 1;
                   7246:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7247:     }
                   7248: 
                   7249: # attempt to get unique identifier, based on current timestamp
                   7250:     if ($gotlock eq 'ok') {
                   7251:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7252:         my $id = time;
                   7253:         $newid = $id;
1.1268    raeburn  7254:         if ($idtype eq 'addcode') {
                   7255:             $newid .= &sixnum_code();
                   7256:         }
1.1198    raeburn  7257:         my $idtries = 0;
                   7258:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7259:             if ($idtype eq 'concat') {
                   7260:                 $newid = $id.$idtries;
1.1268    raeburn  7261:             } elsif ($idtype eq 'addcode') {
                   7262:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7263:             } else {
                   7264:                 $newid ++;
                   7265:             }
                   7266:             $idtries ++;
                   7267:         }
                   7268:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7269:             my %new_item =  (
                   7270:                               $prefix."\0".$newid => $who,
                   7271:                             );
                   7272:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7273:                                                  $cdom,$cnum);
                   7274:             if ($putresult ne 'ok') {
                   7275:                 undef($newid);
                   7276:                 $error = 'error saving new item: '.$putresult;
                   7277:             }
                   7278:         } else {
1.1268    raeburn  7279:              undef($newid);
1.1198    raeburn  7280:              $error = ('error: no unique suffix available for the new item ');
                   7281:         }
                   7282: #  remove lock
                   7283:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7284:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7285:     } else {
                   7286:         $error = "error: could not obtain lockfile\n";
                   7287:         $dellock = 'ok';
1.1276    raeburn  7288:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7289:             $dellock = 'nolock';
                   7290:         }
1.1198    raeburn  7291:     }
                   7292:     return ($newid,$dellock,$error);
                   7293: }
                   7294: 
1.1268    raeburn  7295: sub sixnum_code {
                   7296:     my $code;
                   7297:     for (0..6) {
                   7298:         $code .= int( rand(9) );
                   7299:     }
                   7300:     return $code;
                   7301: }
                   7302: 
1.765     albertel 7303: # -------------------------------------------------- portfolio access checking
                   7304: 
                   7305: sub portfolio_access {
1.1270    raeburn  7306:     my ($requrl,$clientip) = @_;
1.765     albertel 7307:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7308:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7309:     if ($result) {
                   7310:         my %setters;
                   7311:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7312:             my ($startblock,$endblock) =
                   7313:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7314:             if ($startblock && $endblock) {
                   7315:                 return 'B';
                   7316:             }
                   7317:         } else {
                   7318:             my ($startblock,$endblock) =
                   7319:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7320:             if ($startblock && $endblock) {
                   7321:                 return 'B';
                   7322:             }
                   7323:         }
                   7324:     }
1.765     albertel 7325:     if ($result eq 'ok') {
1.766     albertel 7326:        return 'F';
1.765     albertel 7327:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7328:        return 'A';
1.765     albertel 7329:     }
1.766     albertel 7330:     return '';
1.765     albertel 7331: }
                   7332: 
                   7333: sub get_portfolio_access {
1.1270    raeburn  7334:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7335: 
                   7336:     if (!ref($access_hash)) {
                   7337: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7338: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7339: 						   $file_name);
                   7340: 	$access_hash = $access_controls{$file_name};
                   7341:     }
                   7342: 
1.1270    raeburn  7343:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7344:     my $now = time;
                   7345:     if (ref($access_hash) eq 'HASH') {
                   7346:         foreach my $key (keys(%{$access_hash})) {
                   7347:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7348:             if ($start > $now) {
                   7349:                 next;
                   7350:             }
                   7351:             if ($end && $end<$now) {
                   7352:                 next;
                   7353:             }
                   7354:             if ($scope eq 'public') {
                   7355:                 $public = $key;
                   7356:                 last;
                   7357:             } elsif ($scope eq 'guest') {
                   7358:                 $guest = $key;
                   7359:             } elsif ($scope eq 'domains') {
                   7360:                 push(@domains,$key);
                   7361:             } elsif ($scope eq 'users') {
                   7362:                 push(@users,$key);
                   7363:             } elsif ($scope eq 'course') {
                   7364:                 push(@courses,$key);
                   7365:             } elsif ($scope eq 'group') {
                   7366:                 push(@groups,$key);
1.1270    raeburn  7367:             } elsif ($scope eq 'ip') {
                   7368:                 push(@ips,$key);
1.765     albertel 7369:             }
                   7370:         }
                   7371:         if ($public) {
                   7372:             return 'ok';
1.1270    raeburn  7373:         } elsif (@ips > 0) {
                   7374:             my $allowed;
                   7375:             foreach my $ipkey (@ips) {
                   7376:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7377:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7378:                         $allowed = 1;
                   7379:                         last; 
                   7380:                     }
                   7381:                 }
                   7382:             }
                   7383:             if ($allowed) {
                   7384:                 return 'ok';
                   7385:             }
1.765     albertel 7386:         }
                   7387:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7388:             if ($guest) {
                   7389:                 return $guest;
                   7390:             }
                   7391:         } else {
                   7392:             if (@domains > 0) {
                   7393:                 foreach my $domkey (@domains) {
                   7394:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7395:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7396:                             return 'ok';
                   7397:                         }
                   7398:                     }
                   7399:                 }
                   7400:             }
                   7401:             if (@users > 0) {
                   7402:                 foreach my $userkey (@users) {
1.865     raeburn  7403:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7404:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7405:                             if (ref($item) eq 'HASH') {
                   7406:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7407:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7408:                                     return 'ok';
                   7409:                                 }
                   7410:                             }
                   7411:                         }
                   7412:                     } 
1.765     albertel 7413:                 }
                   7414:             }
                   7415:             my %roleshash;
                   7416:             my @courses_and_groups = @courses;
                   7417:             push(@courses_and_groups,@groups); 
                   7418:             if (@courses_and_groups > 0) {
                   7419:                 my (%allgroups,%allroles); 
                   7420:                 my ($start,$end,$role,$sec,$group);
                   7421:                 foreach my $envkey (%env) {
1.1060    raeburn  7422:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7423:                         my $cid = $2.'_'.$3; 
                   7424:                         if ($1 eq 'gr') {
                   7425:                             $group = $4;
                   7426:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7427:                         } else {
                   7428:                             if ($4 eq '') {
                   7429:                                 $sec = 'none';
                   7430:                             } else {
                   7431:                                 $sec = $4;
                   7432:                             }
                   7433:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7434:                         }
1.811     albertel 7435:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7436:                         my $cid = $2.'_'.$3;
                   7437:                         if ($4 eq '') {
                   7438:                             $sec = 'none';
                   7439:                         } else {
                   7440:                             $sec = $4;
                   7441:                         }
                   7442:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7443:                     }
                   7444:                 }
                   7445:                 if (keys(%allroles) == 0) {
                   7446:                     return;
                   7447:                 }
                   7448:                 foreach my $key (@courses_and_groups) {
                   7449:                     my %content = %{$$access_hash{$key}};
                   7450:                     my $cnum = $content{'number'};
                   7451:                     my $cdom = $content{'domain'};
                   7452:                     my $cid = $cdom.'_'.$cnum;
                   7453:                     if (!exists($allroles{$cid})) {
                   7454:                         next;
                   7455:                     }    
                   7456:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7457:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7458:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7459:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7460:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7461:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7462:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7463:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7464:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7465:                                         if (grep/^all$/,@sections) {
                   7466:                                             return 'ok';
                   7467:                                         } else {
                   7468:                                             if (grep/^$sec$/,@sections) {
                   7469:                                                 return 'ok';
                   7470:                                             }
                   7471:                                         }
                   7472:                                     }
                   7473:                                 }
                   7474:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7475:                                     if (grep/^none$/,@groups) {
                   7476:                                         return 'ok';
                   7477:                                     }
                   7478:                                 } else {
                   7479:                                     if (grep/^all$/,@groups) {
                   7480:                                         return 'ok';
                   7481:                                     } 
                   7482:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7483:                                         if (grep/^$group$/,@groups) {
                   7484:                                             return 'ok';
                   7485:                                         }
                   7486:                                     }
                   7487:                                 } 
                   7488:                             }
                   7489:                         }
                   7490:                     }
                   7491:                 }
                   7492:             }
                   7493:             if ($guest) {
                   7494:                 return $guest;
                   7495:             }
                   7496:         }
                   7497:     }
                   7498:     return;
                   7499: }
                   7500: 
                   7501: sub course_group_datechecker {
                   7502:     my ($dates,$now,$status) = @_;
                   7503:     my ($start,$end) = split(/\./,$dates);
                   7504:     if (!$start && !$end) {
                   7505:         return 'ok';
                   7506:     }
                   7507:     if (grep/^active$/,@{$status}) {
                   7508:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7509:             return 'ok';
                   7510:         }
                   7511:     }
                   7512:     if (grep/^previous$/,@{$status}) {
                   7513:         if ($end > $now ) {
                   7514:             return 'ok';
                   7515:         }
                   7516:     }
                   7517:     if (grep/^future$/,@{$status}) {
                   7518:         if ($start > $now) {
                   7519:             return 'ok';
                   7520:         }
                   7521:     }
                   7522:     return; 
                   7523: }
                   7524: 
                   7525: sub parse_portfolio_url {
                   7526:     my ($url) = @_;
                   7527: 
                   7528:     my ($type,$udom,$unum,$group,$file_name);
                   7529:     
1.823     albertel 7530:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7531: 	$type = 1;
                   7532:         $udom = $1;
                   7533:         $unum = $2;
                   7534:         $file_name = $3;
1.823     albertel 7535:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7536: 	$type = 2;
                   7537:         $udom = $1;
                   7538:         $unum = $2;
                   7539:         $group = $3;
                   7540:         $file_name = $3.'/'.$4;
                   7541:     }
                   7542:     if (wantarray) {
                   7543: 	return ($type,$udom,$unum,$file_name,$group);
                   7544:     }
                   7545:     return $type;
                   7546: }
                   7547: 
                   7548: sub is_portfolio_url {
                   7549:     my ($url) = @_;
                   7550:     return scalar(&parse_portfolio_url($url));
                   7551: }
                   7552: 
1.798     raeburn  7553: sub is_portfolio_file {
                   7554:     my ($file) = @_;
1.820     raeburn  7555:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7556:         return 1;
                   7557:     }
                   7558:     return;
                   7559: }
                   7560: 
1.976     raeburn  7561: sub usertools_access {
1.1084    raeburn  7562:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7563:     my ($access,%tools);
                   7564:     if ($context eq '') {
                   7565:         $context = 'tools';
                   7566:     }
                   7567:     if ($context eq 'requestcourses') {
                   7568:         %tools = (
                   7569:                       official   => 1,
                   7570:                       unofficial => 1,
1.1006    raeburn  7571:                       community  => 1,
1.1246    raeburn  7572:                       textbook   => 1,
1.1305    raeburn  7573:                       placement  => 1,
1.1368    raeburn  7574:                       lti        => 1,
1.985     raeburn  7575:                  );
1.1183    raeburn  7576:     } elsif ($context eq 'requestauthor') {
                   7577:         %tools = (
                   7578:                       requestauthor => 1,
                   7579:                  );
1.985     raeburn  7580:     } else {
                   7581:         %tools = (
                   7582:                       aboutme   => 1,
                   7583:                       blog      => 1,
1.1177    raeburn  7584:                       webdav    => 1,
1.985     raeburn  7585:                       portfolio => 1,
                   7586:                  );
                   7587:     }
1.976     raeburn  7588:     return if (!defined($tools{$tool}));
                   7589: 
1.1242    raeburn  7590:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7591:         $udom = $env{'user.domain'};
                   7592:         $uname = $env{'user.name'};
                   7593:     }
                   7594: 
1.978     raeburn  7595:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7596:         if ($action ne 'reload') {
1.985     raeburn  7597:             if ($context eq 'requestcourses') {
                   7598:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7599:             } elsif ($context eq 'requestauthor') {
                   7600:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7601:             } else {
                   7602:                 return $env{'environment.availabletools.'.$tool};
                   7603:             }
                   7604:         }
1.976     raeburn  7605:     }
                   7606: 
1.1183    raeburn  7607:     my ($toolstatus,$inststatus,$envkey);
                   7608:     if ($context eq 'requestauthor') {
                   7609:         $envkey = $context; 
                   7610:     } else {
                   7611:         $envkey = $context.'.'.$tool;
                   7612:     }
1.976     raeburn  7613: 
1.985     raeburn  7614:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7615:          ($action ne 'reload')) {
1.1183    raeburn  7616:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7617:         $inststatus = $env{'environment.inststatus'};
                   7618:     } else {
1.1084    raeburn  7619:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7620:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7621:             $inststatus = $userenvref->{'inststatus'};
                   7622:         } else {
1.1183    raeburn  7623:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7624:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7625:             $inststatus = $userenv{'inststatus'};
                   7626:         }
1.976     raeburn  7627:     }
                   7628: 
                   7629:     if ($toolstatus ne '') {
                   7630:         if ($toolstatus) {
                   7631:             $access = 1;
                   7632:         } else {
                   7633:             $access = 0;
                   7634:         }
                   7635:         return $access;
                   7636:     }
                   7637: 
1.1084    raeburn  7638:     my ($is_adv,%domdef);
                   7639:     if (ref($is_advref) eq 'HASH') {
                   7640:         $is_adv = $is_advref->{'is_adv'};
                   7641:     } else {
                   7642:         $is_adv = &is_advanced_user($udom,$uname);
                   7643:     }
                   7644:     if (ref($domdefref) eq 'HASH') {
                   7645:         %domdef = %{$domdefref};
                   7646:     } else {
                   7647:         %domdef = &get_domain_defaults($udom);
                   7648:     }
1.976     raeburn  7649:     if (ref($domdef{$tool}) eq 'HASH') {
                   7650:         if ($is_adv) {
                   7651:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7652:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7653:                     $access = 1;
                   7654:                 } else {
                   7655:                     $access = 0;
                   7656:                 }
                   7657:                 return $access;
                   7658:             }
                   7659:         }
                   7660:         if ($inststatus ne '') {
                   7661:             my ($hasaccess,$hasnoaccess);
                   7662:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7663:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7664:                     if ($domdef{$tool}{$affiliation}) {
                   7665:                         $hasaccess = 1;
                   7666:                     } else {
                   7667:                         $hasnoaccess = 1;
                   7668:                     }
                   7669:                 }
                   7670:             }
                   7671:             if ($hasaccess || $hasnoaccess) {
                   7672:                 if ($hasaccess) {
                   7673:                     $access = 1;
                   7674:                 } elsif ($hasnoaccess) {
                   7675:                     $access = 0; 
                   7676:                 }
                   7677:                 return $access;
                   7678:             }
                   7679:         } else {
                   7680:             if ($domdef{$tool}{'default'} ne '') {
                   7681:                 if ($domdef{$tool}{'default'}) {
                   7682:                     $access = 1;
                   7683:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7684:                     $access = 0;
                   7685:                 }
                   7686:                 return $access;
                   7687:             }
                   7688:         }
                   7689:     } else {
1.1177    raeburn  7690:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7691:             $access = 1;
                   7692:         } else {
                   7693:             $access = 0;
                   7694:         }
1.976     raeburn  7695:         return $access;
                   7696:     }
                   7697: }
                   7698: 
1.1050    raeburn  7699: sub is_course_owner {
                   7700:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7701:     if (($udom eq '') || ($uname eq '')) {
                   7702:         $udom = $env{'user.domain'};
                   7703:         $uname = $env{'user.name'};
                   7704:     }
                   7705:     unless (($udom eq '') || ($uname eq '')) {
                   7706:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7707:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7708:                 return 1;
                   7709:             } else {
                   7710:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7711:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7712:                     return 1;
                   7713:                 }
                   7714:             }
                   7715:         }
                   7716:     }
                   7717:     return;
                   7718: }
                   7719: 
1.976     raeburn  7720: sub is_advanced_user {
                   7721:     my ($udom,$uname) = @_;
1.1085    raeburn  7722:     if ($udom ne '' && $uname ne '') {
                   7723:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7724:             if (wantarray) {
                   7725:                 return ($env{'user.adv'},$env{'user.author'});
                   7726:             } else {
                   7727:                 return $env{'user.adv'};
                   7728:             }
1.1085    raeburn  7729:         }
                   7730:     }
1.976     raeburn  7731:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7732:     my %allroles;
1.1128    raeburn  7733:     my ($is_adv,$is_author);
1.976     raeburn  7734:     foreach my $role (keys(%roleshash)) {
                   7735:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7736:         my $area = '/'.$tdomain.'/'.$trest;
                   7737:         if ($sec ne '') {
                   7738:             $area .= '/'.$sec;
                   7739:         }
                   7740:         if (($area ne '') && ($trole ne '')) {
                   7741:             my $spec=$trole.'.'.$area;
                   7742:             if ($trole =~ /^cr\//) {
                   7743:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7744:             } elsif ($trole ne 'gr') {
                   7745:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7746:             }
1.1128    raeburn  7747:             if ($trole eq 'au') {
                   7748:                 $is_author = 1;
                   7749:             }
1.976     raeburn  7750:         }
                   7751:     }
                   7752:     foreach my $role (keys(%allroles)) {
                   7753:         last if ($is_adv);
                   7754:         foreach my $item (split(/:/,$allroles{$role})) {
                   7755:             if ($item ne '') {
                   7756:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7757:                 if ($privilege eq 'adv') {
                   7758:                     $is_adv = 1;
                   7759:                     last;
                   7760:                 }
                   7761:             }
                   7762:         }
                   7763:     }
1.1128    raeburn  7764:     if (wantarray) {
                   7765:         return ($is_adv,$is_author);
                   7766:     }
1.976     raeburn  7767:     return $is_adv;
                   7768: }
1.798     raeburn  7769: 
1.1035    raeburn  7770: sub check_can_request {
1.1368    raeburn  7771:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7772:     my $canreq = 0;
1.1368    raeburn  7773:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7774:         $uname = $env{'user.name'};
                   7775:         $udom = $env{'user.domain'};
                   7776:     }
1.1035    raeburn  7777:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7778:     my @options = ('approval','validate','autolimit');
                   7779:     my $optregex = join('|',@options);
                   7780:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7781:         foreach my $type (@{$types}) {
1.1368    raeburn  7782:             if (&usertools_access($uname,$udom,$type,undef,
                   7783:                                   'requestcourses')) {
1.1035    raeburn  7784:                 $canreq ++;
1.1036    raeburn  7785:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7786:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7787:                 }
1.1368    raeburn  7788:                 if ($dom eq $udom) {
1.1035    raeburn  7789:                     $can_request->{$type} = 1;
                   7790:                 }
                   7791:             }
1.1368    raeburn  7792:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7793:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7794:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7795:                 if (@curr > 0) {
1.1036    raeburn  7796:                     foreach my $item (@curr) {
                   7797:                         if (ref($request_domains) eq 'HASH') {
                   7798:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7799:                             if ($otherdom ne '') {
                   7800:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7801:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7802:                                         push(@{$request_domains->{$type}},$otherdom);
                   7803:                                     }
                   7804:                                 } else {
                   7805:                                     push(@{$request_domains->{$type}},$otherdom);
                   7806:                                 }
                   7807:                             }
                   7808:                         }
                   7809:                     }
1.1368    raeburn  7810:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7811:                         $canreq ++;
1.1035    raeburn  7812:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7813:                             $can_request->{$type} = 1;
                   7814:                         }
                   7815:                     }
                   7816:                 }
                   7817:             }
                   7818:         }
                   7819:     }
                   7820:     return $canreq;
                   7821: }
                   7822: 
1.341     www      7823: # ---------------------------------------------- Custom access rule evaluation
                   7824: 
                   7825: sub customaccess {
                   7826:     my ($priv,$uri)=@_;
1.807     albertel 7827:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7828:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7829:     $udom = &LONCAPA::clean_domain($udom);
                   7830:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7831:     my $access=0;
1.800     albertel 7832:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7833: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7834: 	if ($type eq 'user') {
                   7835: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7836: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7837: 		if ($tdom) {
                   7838: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7839: 		}
1.896     albertel 7840: 		if ($tuname) {
                   7841: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7842: 		}
                   7843: 		$access=($effect eq 'allow');
                   7844: 		last;
                   7845: 	    }
                   7846: 	} else {
                   7847: 	    if ($role) {
                   7848: 		if ($role ne $urole) { next; }
                   7849: 	    }
                   7850: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7851: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7852: 		if ($tdom) {
                   7853: 		    if ($tdom ne $udom) { next; }
                   7854: 		}
                   7855: 		if ($tcrs) {
                   7856: 		    if ($tcrs ne $ucrs) { next; }
                   7857: 		}
                   7858: 		if ($tsec) {
                   7859: 		    if ($tsec ne $usec) { next; }
                   7860: 		}
                   7861: 		$access=($effect eq 'allow');
                   7862: 		last;
                   7863: 	    }
                   7864: 	    if ($realm eq '' && $role eq '') {
                   7865: 		$access=($effect eq 'allow');
                   7866: 	    }
1.402     bowersj2 7867: 	}
1.341     www      7868:     }
                   7869:     return $access;
                   7870: }
                   7871: 
1.103     harris41 7872: # ------------------------------------------------- Check for a user privilege
1.12      www      7873: 
                   7874: sub allowed {
1.1281    raeburn  7875:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7876:     my $ver_orguri=$uri;
1.439     www      7877:     $uri=&deversion($uri);
1.152     www      7878:     my $orguri=$uri;
1.52      www      7879:     $uri=&declutter($uri);
1.809     raeburn  7880: 
1.810     raeburn  7881:     if ($priv eq 'evb') {
                   7882: # Evade communication block restrictions for specified role in a course
                   7883:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7884:             return $1;
                   7885:         } else {
                   7886:             return;
                   7887:         }
                   7888:     }
                   7889: 
1.620     albertel 7890:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7891: # Free bre access to adm and meta resources
1.1343    raeburn  7892:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7893: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7894: 	&& ($priv eq 'bre')) {
1.14      www      7895: 	return 'F';
1.159     www      7896:     }
                   7897: 
1.545     banghart 7898: # Free bre access to user's own portfolio contents
1.714     raeburn  7899:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7900:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7901: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7902:         my %setters;
                   7903:         my ($startblock,$endblock) = 
                   7904:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7905:         if ($startblock && $endblock) {
                   7906:             return 'B';
                   7907:         } else {
                   7908:             return 'F';
                   7909:         }
1.545     banghart 7910:     }
                   7911: 
1.762     raeburn  7912: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7913:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7914:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7915:         if (exists($env{'request.course.id'})) {
                   7916:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7917:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7918:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7919:                 my $courseprivid=$env{'request.course.id'};
                   7920:                 $courseprivid=~s/\_/\//;
                   7921:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7922:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7923:                     return $1; 
1.762     raeburn  7924:                 } else {
                   7925:                     if ($env{'request.course.sec'}) {
                   7926:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7927:                     }
                   7928:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7929:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7930:                         return $2;
                   7931:                     }
1.714     raeburn  7932:                 }
                   7933:             }
                   7934:         }
                   7935:     }
                   7936: 
1.159     www      7937: # Free bre to public access
                   7938: 
                   7939:     if ($priv eq 'bre') {
1.1362    raeburn  7940:         my $copyright;
                   7941:         unless ($uri =~ /ext\.tool/) {
                   7942:             $copyright=&metadata($uri,'copyright');
                   7943:         }
1.620     albertel 7944: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7945:            return 'F'; 
                   7946:         }
1.238     www      7947:         if ($copyright eq 'priv') {
                   7948:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7949: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7950: 		return '';
                   7951:             }
                   7952:         }
                   7953:         if ($copyright eq 'domain') {
                   7954:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7955: 	    unless (($env{'user.domain'} eq $1) ||
                   7956:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7957: 		return '';
                   7958:             }
1.262     matthew  7959:         }
1.620     albertel 7960:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7961:             # Library role, so allow browsing of resources in this domain.
                   7962:             return 'F';
1.238     www      7963:         }
1.341     www      7964:         if ($copyright eq 'custom') {
                   7965: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7966:         }
1.14      www      7967:     }
1.264     matthew  7968:     # Domain coordinator is trying to create a course
1.620     albertel 7969:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7970:         # uri is the requested domain in this case.
                   7971:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7972:         # a role of dc for the domain in question.
1.620     albertel 7973:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7974:     }
1.29      www      7975: 
1.52      www      7976:     my $thisallowed='';
                   7977:     my $statecond=0;
                   7978:     my $courseprivid='';
                   7979: 
1.1039    raeburn  7980:     my $ownaccess;
1.1043    raeburn  7981:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7982:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7983:         if ($uri eq '') {
                   7984:             $ownaccess = 1;
                   7985:         } else {
                   7986:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7987:                 my $udom = $env{'user.domain'};
                   7988:                 my $uname = $env{'user.name'};
                   7989:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7990:                     $ownaccess = 1;
1.1040    raeburn  7991:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7992:                     unless ($uri =~ m{\.\./}) {
                   7993:                         $ownaccess = 1;
                   7994:                     }
                   7995:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7996:                     my $now = time;
                   7997:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7998:                         my $adom = $1;
                   7999:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8000:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  8001:                                 my ($start,$end) = split('.',$env{$key});
                   8002:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8003:                                     $ownaccess = 1;
                   8004:                                     last;
                   8005:                                 }
                   8006:                             }
                   8007:                         }
                   8008:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8009:                         my $adom = $1;
                   8010:                         my $aname = $2;
1.1042    raeburn  8011:                         foreach my $role ('ca','aa') { 
                   8012:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8013:                                 my ($start,$end) =
                   8014:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   8015:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8016:                                     $ownaccess = 1;
                   8017:                                     last;
                   8018:                                 }
1.1039    raeburn  8019:                             }
                   8020:                         }
                   8021:                     }
                   8022:                 }
                   8023:             }
                   8024:         }
                   8025:     }
                   8026: 
1.52      www      8027: # Course
                   8028: 
1.620     albertel 8029:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8030:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8031:             $thisallowed.=$1;
                   8032:         }
1.52      www      8033:     }
1.29      www      8034: 
1.52      www      8035: # Domain
                   8036: 
1.620     albertel 8037:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8038:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8039:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8040:             $thisallowed.=$1;
                   8041:         }
1.12      www      8042:     }
1.52      www      8043: 
1.1141    raeburn  8044: # User who is not author or co-author might still be able to edit
                   8045: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8046:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8047:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8048:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8049:             $thisallowed.=$1;
                   8050:         }
                   8051:     }
                   8052: 
1.52      www      8053: # Course: uri itself is a course
1.66      www      8054:     my $courseuri=$uri;
                   8055:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8056:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8057: 
1.620     albertel 8058:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8059:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8060:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8061:             $thisallowed.=$1;
                   8062:         }
1.12      www      8063:     }
1.29      www      8064: 
1.665     albertel 8065: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8066: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8067:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8068: 	$thisallowed='';
1.671     raeburn  8069:         my ($match)=&is_on_map($uri);
                   8070:         if ($match) {
                   8071:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8072:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8073:                 my $value = $1;
1.1402    raeburn  8074:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8075:                 if ($deeplinkblock) {
                   8076:                     $thisallowed='D';
                   8077:                 } elsif ($noblockcheck) {
1.1281    raeburn  8078:                     $thisallowed.=$value;
1.1162    raeburn  8079:                 } else {
1.1281    raeburn  8080:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8081:                     if (@blockers > 0) {
                   8082:                         $thisallowed = 'B';
                   8083:                     } else {
                   8084:                         $thisallowed.=$value;
                   8085:                     }
1.1162    raeburn  8086:                 }
1.671     raeburn  8087:             }
                   8088:         } else {
1.705     albertel 8089:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8090:             if ($refuri) {
                   8091:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8092:                     $thisallowed='F';
1.671     raeburn  8093:                 } else {
                   8094:                     $refuri=&declutter($refuri);
                   8095:                     my ($match) = &is_on_map($refuri);
                   8096:                     if ($match) {
1.1402    raeburn  8097:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8098:                         if ($deeplinkblock) {
                   8099:                             $thisallowed='D';
                   8100:                         } elsif ($noblockcheck) {
1.1281    raeburn  8101:                             $thisallowed='F';
1.1162    raeburn  8102:                         } else {
1.1281    raeburn  8103:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8104:                             if (@blockers > 0) {
                   8105:                                 $thisallowed = 'B';
                   8106:                             } else {
                   8107:                                 $thisallowed='F';
                   8108:                             }
1.1162    raeburn  8109:                         }
1.671     raeburn  8110:                     }
1.669     raeburn  8111:                 }
1.671     raeburn  8112:             }
                   8113:         }
1.314     www      8114:     }
1.492     albertel 8115: 
1.766     albertel 8116:     if ($priv eq 'bre'
                   8117: 	&& $thisallowed ne 'F' 
                   8118: 	&& $thisallowed ne '2'
                   8119: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8120: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8121:     }
1.1250    raeburn  8122: 
1.52      www      8123: # Full access at system, domain or course-wide level? Exit.
1.29      www      8124:     if ($thisallowed=~/F/) {
                   8125: 	return 'F';
                   8126:     }
                   8127: 
1.52      www      8128: # If this is generating or modifying users, exit with special codes
1.29      www      8129: 
1.643     www      8130:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8131: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8132: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8133: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8134: 	    unless ($auname) { return $thisallowed; }
                   8135: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8136: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8137: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8138: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8139: 	}
1.52      www      8140: 	return $thisallowed;
                   8141:     }
                   8142: #
1.103     harris41 8143: # Gathered so far: system, domain and course wide privileges
1.52      www      8144: #
                   8145: # Course: See if uri or referer is an individual resource that is part of 
                   8146: # the course
                   8147: 
1.620     albertel 8148:     if ($env{'request.course.id'}) {
1.232     www      8149: 
1.620     albertel 8150:        $courseprivid=$env{'request.course.id'};
                   8151:        if ($env{'request.course.sec'}) {
                   8152:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8153:        }
                   8154:        $courseprivid=~s/\_/\//;
                   8155:        my $checkreferer=1;
1.232     www      8156:        my ($match,$cond)=&is_on_map($uri);
                   8157:        if ($match) {
                   8158:            $statecond=$cond;
1.620     albertel 8159:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8160:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8161:                my $value = $1;
                   8162:                if ($priv eq 'bre') {
1.1281    raeburn  8163:                    if ($noblockcheck) {
                   8164:                        $thisallowed.=$value;
1.1162    raeburn  8165:                    } else {
1.1281    raeburn  8166:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8167:                        if (@blockers > 0) {
                   8168:                            $thisallowed = 'B';
                   8169:                        } else {
                   8170:                            $thisallowed.=$value;
                   8171:                        }
1.1162    raeburn  8172:                    }
                   8173:                } else {
                   8174:                    $thisallowed.=$value;
                   8175:                }
1.52      www      8176:                $checkreferer=0;
                   8177:            }
1.29      www      8178:        }
1.83      www      8179:        
1.148     www      8180:        if ($checkreferer) {
1.620     albertel 8181: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8182:             unless ($refuri) {
1.800     albertel 8183:                 foreach my $key (keys(%env)) {
                   8184: 		    if ($key=~/^httpref\..*\*/) {
                   8185: 			my $pattern=$key;
1.156     www      8186:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8187:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8188:                         $pattern=~s/\//\\\//g;
1.152     www      8189:                         if ($orguri=~/$pattern/) {
1.800     albertel 8190: 			    $refuri=$env{$key};
1.148     www      8191:                         }
                   8192:                     }
1.191     harris41 8193:                 }
1.148     www      8194:             }
1.232     www      8195: 
1.148     www      8196:          if ($refuri) { 
1.152     www      8197: 	  $refuri=&declutter($refuri);
1.232     www      8198:           my ($match,$cond)=&is_on_map($refuri);
                   8199:             if ($match) {
                   8200:               my $refstatecond=$cond;
1.620     albertel 8201:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8202:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8203:                   my $value = $1;
                   8204:                   if ($priv eq 'bre') {
1.1402    raeburn  8205:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8206:                       if ($deeplinkblock) {
                   8207:                           $thisallowed = 'D';
                   8208:                       } elsif ($noblockcheck) {
1.1281    raeburn  8209:                           $thisallowed.=$value;
1.1162    raeburn  8210:                       } else {
1.1281    raeburn  8211:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8212:                           if (@blockers > 0) {
                   8213:                               $thisallowed = 'B';
                   8214:                           } else {
                   8215:                               $thisallowed.=$value;
                   8216:                           }
1.1162    raeburn  8217:                       }
                   8218:                   } else {
                   8219:                       $thisallowed.=$value;
                   8220:                   }
1.53      www      8221:                   $uri=$refuri;
                   8222:                   $statecond=$refstatecond;
1.52      www      8223:               }
                   8224:           }
1.148     www      8225:         }
1.29      www      8226:        }
1.52      www      8227:    }
1.29      www      8228: 
1.52      www      8229: #
1.103     harris41 8230: # Gathered now: all privileges that could apply, and condition number
1.52      www      8231: # 
                   8232: #
                   8233: # Full or no access?
                   8234: #
1.29      www      8235: 
1.52      www      8236:     if ($thisallowed=~/F/) {
                   8237: 	return 'F';
                   8238:     }
1.29      www      8239: 
1.52      www      8240:     unless ($thisallowed) {
                   8241:         return '';
                   8242:     }
1.29      www      8243: 
1.52      www      8244: # Restrictions exist, deal with them
                   8245: #
                   8246: #   C:according to course preferences
                   8247: #   R:according to resource settings
                   8248: #   L:unless locked
                   8249: #   X:according to user session state
                   8250: #
                   8251: 
                   8252: # Possibly locked functionality, check all courses
1.54      www      8253: # Locks might take effect only after 10 minutes cache expiration for other
                   8254: # courses, and 2 minutes for current course
1.52      www      8255: 
                   8256:     my $envkey;
                   8257:     if ($thisallowed=~/L/) {
1.1000    raeburn  8258:         foreach $envkey (keys(%env)) {
1.54      www      8259:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8260:                my $courseid=$2;
                   8261:                my $roleid=$1.'.'.$2;
1.92      www      8262:                $courseid=~s/^\///;
1.54      www      8263:                my $expiretime=600;
1.620     albertel 8264:                if ($env{'request.role'} eq $roleid) {
1.54      www      8265: 		  $expiretime=120;
                   8266:                }
                   8267: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8268:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8269:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8270: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8271:                }
1.620     albertel 8272:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8273:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8274: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8275:                        &log($env{'user.domain'},$env{'user.name'},
                   8276:                             $env{'user.home'},
1.57      www      8277:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8278:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8279:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8280: 		       return '';
                   8281:                    }
                   8282:                }
1.620     albertel 8283:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8284:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8285: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8286:                        &log($env{'user.domain'},$env{'user.name'},
                   8287:                             $env{'user.home'},
1.57      www      8288:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8289:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8290:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8291: 		       return '';
                   8292:                    }
                   8293:                }
                   8294: 	   }
1.29      www      8295:        }
1.52      www      8296:     }
                   8297:    
                   8298: #
                   8299: # Rest of the restrictions depend on selected course
                   8300: #
                   8301: 
1.620     albertel 8302:     unless ($env{'request.course.id'}) {
1.766     albertel 8303: 	if ($thisallowed eq 'A') {
                   8304: 	    return 'A';
1.814     raeburn  8305:         } elsif ($thisallowed eq 'B') {
                   8306:             return 'B';
1.766     albertel 8307: 	} else {
                   8308: 	    return '1';
                   8309: 	}
1.52      www      8310:     }
1.29      www      8311: 
1.52      www      8312: #
                   8313: # Now user is definitely in a course
                   8314: #
1.53      www      8315: 
                   8316: 
                   8317: # Course preferences
                   8318: 
                   8319:    if ($thisallowed=~/C/) {
1.620     albertel 8320:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8321:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8322:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8323: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8324: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8325: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8326: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8327: 			$env{'request.course.id'});
                   8328: 	   }
1.237     www      8329:            return '';
                   8330:        }
                   8331: 
1.620     albertel 8332:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8333: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8334: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8335: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8336: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8337: 			$env{'request.course.id'});
                   8338: 	   }
1.54      www      8339:            return '';
                   8340:        }
1.53      www      8341:    }
                   8342: 
                   8343: # Resource preferences
                   8344: 
                   8345:    if ($thisallowed=~/R/) {
1.620     albertel 8346:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8347:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8348: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8349: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8350: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8351: 	   }
                   8352: 	   return '';
1.54      www      8353:        }
1.53      www      8354:    }
1.30      www      8355: 
1.246     www      8356: # Restricted by state or randomout?
1.30      www      8357: 
1.52      www      8358:    if ($thisallowed=~/X/) {
1.620     albertel 8359:       if ($env{'acc.randomout'}) {
1.579     albertel 8360: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8361:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8362:             return ''; 
                   8363:          }
1.247     www      8364:       }
                   8365:       if (&condval($statecond)) {
1.52      www      8366: 	 return '2';
                   8367:       } else {
                   8368:          return '';
                   8369:       }
                   8370:    }
1.30      www      8371: 
1.766     albertel 8372:     if ($thisallowed eq 'A') {
                   8373: 	return 'A';
1.814     raeburn  8374:     } elsif ($thisallowed eq 'B') {
                   8375:         return 'B';
1.1402    raeburn  8376:     } elsif ($thisallowed eq 'D') {
                   8377:         return 'D';
1.766     albertel 8378:     }
1.52      www      8379:    return 'F';
1.232     www      8380: }
1.1162    raeburn  8381: 
1.1192    raeburn  8382: # ------------------------------------------- Check construction space access
                   8383: 
                   8384: sub constructaccess {
                   8385:     my ($url,$setpriv)=@_;
                   8386: 
                   8387: # We do not allow editing of previous versions of files
                   8388:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8389: 
                   8390: # Get username and domain from URL
                   8391:     my ($ownername,$ownerdomain,$ownerhome);
                   8392: 
                   8393:     ($ownerdomain,$ownername) =
1.1325    raeburn  8394:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8395: 
                   8396: # The URL does not really point to any authorspace, forget it
                   8397:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8398: 
                   8399: # Now we need to see if the user has access to the authorspace of
                   8400: # $ownername at $ownerdomain
                   8401: 
                   8402:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8403: # Real author for this?
                   8404:        $ownerhome = $env{'user.home'};
                   8405:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8406:           return ($ownername,$ownerdomain,$ownerhome);
                   8407:        }
                   8408:     } else {
                   8409: # Co-author for this?
                   8410:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8411:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8412:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8413:             return ($ownername,$ownerdomain,$ownerhome);
                   8414:         }
1.1312    raeburn  8415:         if ($env{'request.course.id'}) {
                   8416:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8417:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8418:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8419:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8420:                     return ($ownername,$ownerdomain,$ownerhome);
                   8421:                 }
                   8422:             }
                   8423:         }
1.1192    raeburn  8424:     }
                   8425: 
                   8426: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8427: # we might as well leave
                   8428:    unless ($setpriv) { return ''; }
                   8429: 
                   8430: # Backdoor access?
                   8431:     my $allowed=&allowed('eco',$ownerdomain);
                   8432: # Nope
                   8433:     unless ($allowed) { return ''; }
                   8434: # Looks like we may have access, but could be locked by the owner of the construction space
                   8435:     if ($allowed eq 'U') {
                   8436:         my %blocked=&get('environment',['domcoord.author'],
                   8437:                          $ownerdomain,$ownername);
                   8438: # Is blocked by owner
                   8439:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8440:     }
                   8441:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8442: # Grant temporary access
                   8443:         my $then=$env{'user.login.time'};
1.1209    raeburn  8444:         my $update=$env{'user.update.time'};
1.1192    raeburn  8445:         if (!$update) { $update = $then; }
                   8446:         my $refresh=$env{'user.refresh.time'};
                   8447:         if (!$refresh) { $refresh = $update; }
                   8448:         my $now = time;
                   8449:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8450:                            $now,'ca','constructaccess');
                   8451:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8452:         return($ownername,$ownerdomain,$ownerhome);
                   8453:     }
                   8454: # No business here
                   8455:     return '';
                   8456: }
                   8457: 
1.1282    raeburn  8458: # ----------------------------------------------------------- Content Blocking
                   8459: 
                   8460: {
                   8461: # Caches for faster Course Contents display where content blocking
                   8462: # is in operation (i.e., interval param set) for timed quiz.
                   8463: #
                   8464: # User for whom data are being temporarily cached.
                   8465: my $cacheduser='';
                   8466: # Cached blockers for this user (a hash of blocking items). 
                   8467: my %cachedblockers=();
                   8468: # When the data were last cached.
                   8469: my $cachedlast='';
                   8470: 
                   8471: sub load_all_blockers {
                   8472:     my ($uname,$udom,$blocks)=@_;
                   8473:     if (($uname ne '') && ($udom ne '')) { 
                   8474:         if (($cacheduser eq $uname.':'.$udom) &&
                   8475:             (abs($cachedlast-time)<5)) {
                   8476:             return;
                   8477:         }
                   8478:     }
                   8479:     $cachedlast=time;
                   8480:     $cacheduser=$uname.':'.$udom;
                   8481:     %cachedblockers = &get_commblock_resources($blocks);
                   8482: }
                   8483: 
1.1162    raeburn  8484: sub get_comm_blocks {
                   8485:     my ($cdom,$cnum) = @_;
                   8486:     if ($cdom eq '' || $cnum eq '') {
                   8487:         return unless ($env{'request.course.id'});
                   8488:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8489:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8490:     }
                   8491:     my %commblocks;
                   8492:     my $hashid=$cdom.'_'.$cnum;
                   8493:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8494:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8495:         %commblocks = %{$blocksref};
                   8496:     } else {
                   8497:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8498:         my $cachetime = 600;
                   8499:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8500:     }
                   8501:     return %commblocks;
                   8502: }
                   8503: 
1.1282    raeburn  8504: sub get_commblock_resources {
                   8505:     my ($blocks) = @_;
                   8506:     my %blockers = ();
                   8507:     return %blockers unless ($env{'request.course.id'});
                   8508:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8509:     my %commblocks;
                   8510:     if (ref($blocks) eq 'HASH') {
                   8511:         %commblocks = %{$blocks};
                   8512:     } else {
                   8513:         %commblocks = &get_comm_blocks();
                   8514:     }
1.1282    raeburn  8515:     return %blockers unless (keys(%commblocks) > 0); 
                   8516:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8517:     return %blockers unless (ref($navmap));
1.1162    raeburn  8518:     my $now = time;
                   8519:     foreach my $block (keys(%commblocks)) {
                   8520:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8521:             my ($start,$end) = ($1,$2);
                   8522:             if ($start <= $now && $end >= $now) {
                   8523:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8524:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8525:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8526:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8527:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8528:                             }
                   8529:                         }
                   8530:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8531:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8532:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8533:                             }
                   8534:                         }
                   8535:                     }
                   8536:                 }
                   8537:             }
                   8538:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8539:             my $item = $1;
1.1163    raeburn  8540:             my @to_test;
1.1162    raeburn  8541:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8542:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8543:                     my @interval;
                   8544:                     my $type = 'map';
                   8545:                     if ($item eq 'course') {
                   8546:                         $type = 'course';
                   8547:                         @interval=&EXT("resource.0.interval");
                   8548:                     } else {
                   8549:                         if ($item =~ /___\d+___/) {
                   8550:                             $type = 'resource';
                   8551:                             @interval=&EXT("resource.0.interval",$item);
                   8552:                             if (ref($navmap)) {                        
                   8553:                                 my $res = $navmap->getBySymb($item); 
                   8554:                                 push(@to_test,$res);
                   8555:                             }
1.1162    raeburn  8556:                         } else {
1.1282    raeburn  8557:                             my $mapsymb = &symbread($item,1);
                   8558:                             if ($mapsymb) {
                   8559:                                 if (ref($navmap)) {
                   8560:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8561:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8562:                                     foreach my $res (@to_test) {
                   8563:                                         my $symb = $res->symb();
                   8564:                                         next if ($symb eq $mapsymb);
                   8565:                                         if ($symb ne '') {
                   8566:                                             @interval=&EXT("resource.0.interval",$symb);
                   8567:                                             if ($interval[1] eq 'map') {
                   8568:                                                 last;
1.1162    raeburn  8569:                                             }
                   8570:                                         }
                   8571:                                     }
                   8572:                                 }
                   8573:                             }
                   8574:                         }
1.1282    raeburn  8575:                     }
1.1310    raeburn  8576:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8577:                         my $timelimit = $1; 
1.1282    raeburn  8578:                         my $first_access;
                   8579:                         if ($type eq 'resource') {
                   8580:                             $first_access=&get_first_access($interval[1],$item);
                   8581:                         } elsif ($type eq 'map') {
                   8582:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8583:                         } else {
                   8584:                             $first_access=&get_first_access($interval[1]);
                   8585:                         }
                   8586:                         if ($first_access) {
1.1292    raeburn  8587:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8588:                             if ($timesup > $now) {
                   8589:                                 my $activeblock;
                   8590:                                 foreach my $res (@to_test) {
1.1283    raeburn  8591:                                     if ($res->answerable()) {
1.1282    raeburn  8592:                                         $activeblock = 1;
                   8593:                                         last;
                   8594:                                     }
                   8595:                                 }
                   8596:                                 if ($activeblock) {
                   8597:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8598:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8599:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8600:                                          }
                   8601:                                     }
                   8602:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8603:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8604:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8605:                                         }
1.1162    raeburn  8606:                                     }
                   8607:                                 }
                   8608:                             }
                   8609:                         }
                   8610:                     }
                   8611:                 }
                   8612:             }
                   8613:         }
                   8614:     }
1.1282    raeburn  8615:     return %blockers;
1.1162    raeburn  8616: }
                   8617: 
1.1282    raeburn  8618: sub has_comm_blocking {
                   8619:     my ($priv,$symb,$uri,$blocks) = @_;
                   8620:     my @blockers;
                   8621:     return unless ($env{'request.course.id'});
                   8622:     return unless ($priv eq 'bre');
                   8623:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8624:     return if ($env{'request.state'} eq 'construct');
                   8625:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8626:     return unless (keys(%cachedblockers) > 0);
                   8627:     my (%possibles,@symbs);
                   8628:     if (!$symb) {
                   8629:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8630:     }
1.1282    raeburn  8631:     if ($symb) {
                   8632:         @symbs = ($symb);
                   8633:     } elsif (keys(%possibles)) { 
                   8634:         @symbs = keys(%possibles);
                   8635:     }
                   8636:     my $noblock;
                   8637:     foreach my $symb (@symbs) {
                   8638:         last if ($noblock);
                   8639:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8640:         foreach my $block (keys(%cachedblockers)) {
                   8641:             if ($block =~ /^firstaccess____(.+)$/) {
                   8642:                 my $item = $1;
                   8643:                 if (($item eq $map) || ($item eq $symb)) {
                   8644:                     $noblock = 1;
                   8645:                     last;
                   8646:                 }
                   8647:             }
                   8648:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8649:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8650:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8651:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8652:                             push(@blockers,$block);
                   8653:                         }
                   8654:                     }
                   8655:                 }
1.1162    raeburn  8656:             }
1.1282    raeburn  8657:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8658:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8659:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8660:                         push(@blockers,$block);
                   8661:                     }
                   8662:                 }
1.1162    raeburn  8663:             }
                   8664:         }
                   8665:     }
1.1282    raeburn  8666:     return if ($noblock);
                   8667:     return @blockers;
                   8668: }
1.1162    raeburn  8669: }
                   8670: 
1.1402    raeburn  8671: sub deeplink_check {
                   8672:     my ($priv,$symb,$uri) = @_;
                   8673:     return unless ($env{'request.course.id'});
                   8674:     return unless ($priv eq 'bre');
                   8675:     return if ($env{'request.state'} eq 'construct');
                   8676:     return if ($env{'request.role.adv'});
                   8677:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8678:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8679:     my (%possibles,@symbs);
                   8680:     if (!$symb) {
                   8681:         $symb = &symbread($uri,1,1,1,\%possibles);
                   8682:     }
                   8683:     if ($symb) {
                   8684:         @symbs = ($symb);
                   8685:     } elsif (keys(%possibles)) {
                   8686:         @symbs = keys(%possibles);
                   8687:     }
                   8688: 
                   8689:     my ($login,$switchrole,$allow);
                   8690:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   8691:         my $key = $1;
                   8692:         my $tinyurl;
                   8693:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   8694:         if (defined($cached)) {
                   8695:              $tinyurl = $result;
                   8696:         } else {
                   8697:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   8698:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   8699:              if ($currtiny{$key} ne '') {
                   8700:                  $tinyurl = $currtiny{$key};
                   8701:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   8702:              }
                   8703:         }
                   8704:         if ($tinyurl ne '') {
                   8705:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
                   8706:             if ($cnumreq eq $cnum) {
                   8707:                 $login = $posslogin;
                   8708:             } else {
                   8709:                 $switchrole = 1;
                   8710:             }
                   8711:         }
                   8712:     }
                   8713:     foreach my $symb (@symbs) {
                   8714:         last if ($allow);
                   8715:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8716:         if ($deeplink eq '') {
                   8717:             $allow = 1;
                   8718:         } else {
                   8719:             my ($listed,$scope,$access) = split(/,/,$deeplink);
                   8720:             if ($access eq 'any') {
                   8721:                 $allow = 1;
                   8722:             } elsif ($login) {
                   8723:                 if ($access eq 'only') {
                   8724:                     if ($scope eq 'res') {
                   8725:                         if ($symb eq $login) {
                   8726:                             $allow = 1;
                   8727:                         }
                   8728:                     } elsif ($scope eq 'map') {
                   8729: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
                   8730:                     } elsif ($scope eq 'rec') {
                   8731: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
                   8732:                     }
                   8733:                 } else {
                   8734:                     my ($acctype,$item) = split(/:/,$access);
                   8735:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
                   8736:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
                   8737:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8738:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
                   8739:                                 $allow = 1;
                   8740:                             }
                   8741:                         }
                   8742:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   8743:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   8744:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8745:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
                   8746:                                 $allow = 1;
                   8747:                             }
                   8748:                         }
                   8749:                     }
                   8750:                 }
                   8751:             }
                   8752:         }
                   8753:     }
                   8754:     return if ($allow);
                   8755:     return 1;
                   8756: }
                   8757: 
1.1282    raeburn  8758: # -------------------------------- Deversion and split uri into path an filename   
                   8759: 
1.1133    foxr     8760: #
1.1282    raeburn  8761: #   Removes the version from a URI and
1.1133    foxr     8762: #   splits it in to its filename and path to the filename.
                   8763: #   Seems like File::Basename could have done this more clearly.
                   8764: #   Parameters:
                   8765: #      $uri   - input URI
                   8766: #   Returns:
                   8767: #     Two element list consisting of 
                   8768: #     $pathname  - the URI up to and excluding the trailing /
                   8769: #     $filename  - The part of the URI following the last /
                   8770: #  NOTE:
                   8771: #    Another realization of this is simply:
                   8772: #    use File::Basename;
                   8773: #    ...
                   8774: #    $uri = shift;
                   8775: #    $filename = basename($uri);
                   8776: #    $path     = dirname($uri);
                   8777: #    return ($filename, $path);
                   8778: #
                   8779: #     The implementation below is probably faster however.
                   8780: #
1.710     albertel 8781: sub split_uri_for_cond {
                   8782:     my $uri=&deversion(&declutter(shift));
                   8783:     my @uriparts=split(/\//,$uri);
                   8784:     my $filename=pop(@uriparts);
                   8785:     my $pathname=join('/',@uriparts);
                   8786:     return ($pathname,$filename);
                   8787: }
1.232     www      8788: # --------------------------------------------------- Is a resource on the map?
                   8789: 
                   8790: sub is_on_map {
1.710     albertel 8791:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8792:     #Trying to find the conditional for the file
1.620     albertel 8793:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8794: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8795:     if ($match) {
1.289     bowersj2 8796: 	return (1,$1);
                   8797:     } else {
1.434     www      8798: 	return (0,0);
1.289     bowersj2 8799:     }
1.12      www      8800: }
                   8801: 
1.427     www      8802: # --------------------------------------------------------- Get symb from alias
                   8803: 
                   8804: sub get_symb_from_alias {
                   8805:     my $symb=shift;
                   8806:     my ($map,$resid,$url)=&decode_symb($symb);
                   8807: # Already is a symb
                   8808:     if ($url) { return $symb; }
                   8809: # Must be an alias
                   8810:     my $aliassymb='';
                   8811:     my %bighash;
1.620     albertel 8812:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8813:                             &GDBM_READER(),0640)) {
                   8814:         my $rid=$bighash{'mapalias_'.$symb};
                   8815: 	if ($rid) {
                   8816: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8817: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8818: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8819: 	}
                   8820:         untie %bighash;
                   8821:     }
                   8822:     return $aliassymb;
                   8823: }
                   8824: 
1.12      www      8825: # ----------------------------------------------------------------- Define Role
                   8826: 
                   8827: sub definerole {
                   8828:   if (allowed('mcr','/')) {
1.1326    raeburn  8829:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8830:     foreach my $role (split(':',$sysrole)) {
                   8831: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8832:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8833:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8834: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8835:                return "refused:s:$crole&$cqual"; 
                   8836:             }
                   8837:         }
1.191     harris41 8838:     }
1.800     albertel 8839:     foreach my $role (split(':',$domrole)) {
                   8840: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8841:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8842:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8843: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8844:                return "refused:d:$crole&$cqual"; 
                   8845:             }
                   8846:         }
1.191     harris41 8847:     }
1.800     albertel 8848:     foreach my $role (split(':',$courole)) {
                   8849: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8850:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8851:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8852: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8853:                return "refused:c:$crole&$cqual"; 
                   8854:             }
                   8855:         }
1.191     harris41 8856:     }
1.1326    raeburn  8857:     my $uhome;
                   8858:     if (($uname ne '') && ($udom ne '')) {
                   8859:         $uhome = &homeserver($uname,$udom);
                   8860:         return $uhome if ($uhome eq 'no_host');
                   8861:     } else {
                   8862:         $uname = $env{'user.name'};
                   8863:         $udom = $env{'user.domain'};
                   8864:         $uhome = $env{'user.home'};
                   8865:     }
1.620     albertel 8866:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8867:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8868:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8869:     return reply($command,$uhome);
1.12      www      8870:   } else {
                   8871:     return 'refused';
                   8872:   }
1.105     harris41 8873: }
                   8874: 
                   8875: # ---------------- Make a metadata query against the network of library servers
                   8876: 
                   8877: sub metadata_query {
1.1237    raeburn  8878:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8879:     my %rhash;
1.845     albertel 8880:     my %libserv = &all_library();
1.244     matthew  8881:     my @server_list = (defined($server_array) ? @$server_array
                   8882:                                               : keys(%libserv) );
                   8883:     for my $server (@server_list) {
1.1237    raeburn  8884:         my $domains = ''; 
                   8885:         if (ref($domains_hash) eq 'HASH') {
                   8886:             $domains = $domains_hash->{$server}; 
                   8887:         }
1.118     harris41 8888: 	unless ($custom or $customshow) {
1.1237    raeburn  8889: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8890: 	    $rhash{$server}=$reply;
                   8891: 	}
                   8892: 	else {
                   8893: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8894: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8895: 			     $server);
                   8896: 	    $rhash{$server}=$reply;
                   8897: 	}
1.112     harris41 8898:     }
1.118     harris41 8899:     return \%rhash;
1.240     www      8900: }
                   8901: 
                   8902: # ----------------------------------------- Send log queries and wait for reply
                   8903: 
                   8904: sub log_query {
                   8905:     my ($uname,$udom,$query,%filters)=@_;
                   8906:     my $uhome=&homeserver($uname,$udom);
                   8907:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8908:     my $uhost=&hostname($uhome);
1.800     albertel 8909:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8910:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8911:                        $uhome);
1.479     albertel 8912:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8913:     return get_query_reply($queryid);
                   8914: }
                   8915: 
1.818     raeburn  8916: # -------------------------- Update MySQL table for portfolio file
                   8917: 
                   8918: sub update_portfolio_table {
1.821     raeburn  8919:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8920:     if ($group ne '') {
                   8921:         $file_name =~s /^\Q$group\E//;
                   8922:     }
1.818     raeburn  8923:     my $homeserver = &homeserver($uname,$udom);
                   8924:     my $queryid=
1.821     raeburn  8925:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8926:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8927:     my $reply = &get_query_reply($queryid);
                   8928:     return $reply;
                   8929: }
                   8930: 
1.899     raeburn  8931: # -------------------------- Update MySQL allusers table
                   8932: 
                   8933: sub update_allusers_table {
                   8934:     my ($uname,$udom,$names) = @_;
                   8935:     my $homeserver = &homeserver($uname,$udom);
                   8936:     my $queryid=
                   8937:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8938:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8939:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8940:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8941:                'generation='.&escape($names->{'generation'}).'%%'.
                   8942:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8943:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8944:     return;
1.899     raeburn  8945: }
                   8946: 
1.508     raeburn  8947: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8948: 
                   8949: sub fetch_enrollment_query {
1.511     raeburn  8950:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8951:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8952:     my $maxtries = 1;
1.508     raeburn  8953:     if ($context eq 'automated') {
                   8954:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8955:         $sleep = 2;
                   8956:         $loopmax = 100;
1.547     raeburn  8957:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8958:     } else {
                   8959:         $homeserver = &homeserver($cnum,$dom);
                   8960:     }
1.838     albertel 8961:     my $host=&hostname($homeserver);
1.506     raeburn  8962:     my $cmd = '';
1.1000    raeburn  8963:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8964:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8965:     }
                   8966:     $cmd =~ s/%%$//;
                   8967:     $cmd = &escape($cmd);
                   8968:     my $query = 'fetchenrollment';
1.620     albertel 8969:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8970:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8971:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8972:         return 'error: '.$queryid;
                   8973:     }
1.1317    raeburn  8974:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8975:     my $tries = 1;
                   8976:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8977:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8978:         $tries ++;
                   8979:     }
1.526     raeburn  8980:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8981:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8982:     } else {
1.901     albertel 8983:         my @responses = split(/:/,$reply);
1.1322    raeburn  8984:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8985:             foreach my $line (@responses) {
                   8986:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8987:                 $$replyref{$key} = $value;
                   8988:             }
                   8989:         } else {
1.1117    foxr     8990:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8991:             foreach my $line (@responses) {
                   8992:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8993:                 $$replyref{$key} = $value;
                   8994:                 if ($value > 0) {
1.800     albertel 8995:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8996:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8997:                         my $destname = $pathname.'/'.$filename;
                   8998:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8999:                         if ($xml_classlist =~ /^error/) {
                   9000:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9001:                         } else {
1.1359    raeburn  9002:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9003:                                 print FILE &unescape($xml_classlist);
                   9004:                                 close(FILE);
1.526     raeburn  9005:                             } else {
                   9006:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9007:                             }
                   9008:                         }
                   9009:                     }
                   9010:                 }
                   9011:             }
                   9012:         }
                   9013:         return 'ok';
                   9014:     }
                   9015:     return 'error';
                   9016: }
                   9017: 
1.242     www      9018: sub get_query_reply {
1.1317    raeburn  9019:     my ($queryid,$sleep,$loopmax) = @_;;
                   9020:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9021:         $sleep = 0.2;
                   9022:     }
                   9023:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9024:         $loopmax = 100;
                   9025:     }
1.1117    foxr     9026:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9027:     my $reply='';
1.1317    raeburn  9028:     for (1..$loopmax) {
                   9029: 	sleep($sleep);
1.240     www      9030:         if (-e $replyfile.'.end') {
1.1359    raeburn  9031: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9032: 		$reply = join('',<$fh>);
                   9033: 		close($fh);
1.240     www      9034: 	   } else { return 'error: reply_file_error'; }
1.242     www      9035:            return &unescape($reply);
                   9036: 	}
1.240     www      9037:     }
1.242     www      9038:     return 'timeout:'.$queryid;
1.240     www      9039: }
                   9040: 
                   9041: sub courselog_query {
1.241     www      9042: #
                   9043: # possible filters:
                   9044: # url: url or symb
                   9045: # username
                   9046: # domain
                   9047: # action: view, submit, grade
                   9048: # start: timestamp
                   9049: # end: timestamp
                   9050: #
1.240     www      9051:     my (%filters)=@_;
1.620     albertel 9052:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9053:     if ($filters{'url'}) {
                   9054: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9055:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9056:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9057:     }
1.620     albertel 9058:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9059:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9060:     return &log_query($cname,$cdom,'courselog',%filters);
                   9061: }
                   9062: 
                   9063: sub userlog_query {
1.858     raeburn  9064: #
                   9065: # possible filters:
                   9066: # action: log check role
                   9067: # start: timestamp
                   9068: # end: timestamp
                   9069: #
1.240     www      9070:     my ($uname,$udom,%filters)=@_;
                   9071:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9072: }
                   9073: 
1.506     raeburn  9074: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9075: 
                   9076: sub auto_run {
1.508     raeburn  9077:     my ($cnum,$cdom) = @_;
1.876     raeburn  9078:     my $response = 0;
                   9079:     my $settings;
                   9080:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9081:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9082:         $settings = $domconfig{'autoenroll'};
                   9083:         if ($settings->{'run'} eq '1') {
                   9084:             $response = 1;
                   9085:         }
                   9086:     } else {
1.934     raeburn  9087:         my $homeserver;
                   9088:         if (&is_course($cdom,$cnum)) {
                   9089:             $homeserver = &homeserver($cnum,$cdom);
                   9090:         } else {
                   9091:             $homeserver = &domain($cdom,'primary');
                   9092:         }
                   9093:         if ($homeserver ne 'no_host') {
                   9094:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9095:         }
1.876     raeburn  9096:     }
1.506     raeburn  9097:     return $response;
                   9098: }
1.776     albertel 9099: 
1.506     raeburn  9100: sub auto_get_sections {
1.508     raeburn  9101:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9102:     my $homeserver;
                   9103:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9104:         $homeserver = &homeserver($cnum,$cdom);
                   9105:     }
                   9106:     if (!defined($homeserver)) { 
                   9107:         if ($cdom =~ /^$match_domain$/) {
                   9108:             $homeserver = &domain($cdom,'primary');
                   9109:         }
                   9110:     }
                   9111:     my @secs;
                   9112:     if (defined($homeserver)) {
                   9113:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9114:         unless ($response eq 'refused') {
                   9115:             @secs = split(/:/,$response);
                   9116:         }
1.506     raeburn  9117:     }
                   9118:     return @secs;
                   9119: }
1.776     albertel 9120: 
1.506     raeburn  9121: sub auto_new_course {
1.1099    raeburn  9122:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9123:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9124:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9125:     return $response;
                   9126: }
1.776     albertel 9127: 
1.506     raeburn  9128: sub auto_validate_courseID {
1.508     raeburn  9129:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9130:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9131:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9132:     return $response;
                   9133: }
1.776     albertel 9134: 
1.1007    raeburn  9135: sub auto_validate_instcode {
1.1020    raeburn  9136:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9137:     my ($homeserver,$response);
                   9138:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9139:         $homeserver = &homeserver($cnum,$cdom);
                   9140:     }
                   9141:     if (!defined($homeserver)) {
                   9142:         if ($cdom =~ /^$match_domain$/) {
                   9143:             $homeserver = &domain($cdom,'primary');
                   9144:         }
                   9145:     }
1.1065    raeburn  9146:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9147:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9148:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9149:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9150: }
                   9151: 
1.506     raeburn  9152: sub auto_create_password {
1.873     raeburn  9153:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9154:     my ($homeserver,$response);
1.506     raeburn  9155:     my $create_passwd = 0;
                   9156:     my $authchk = '';
1.873     raeburn  9157:     if ($udom =~ /^$match_domain$/) {
                   9158:         $homeserver = &domain($udom,'primary');
                   9159:     }
                   9160:     if ($homeserver eq '') {
                   9161:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9162:             $homeserver = &homeserver($cnum,$cdom);
                   9163:         }
                   9164:     }
                   9165:     if ($homeserver eq '') {
                   9166:         $authchk = 'nodomain';
1.506     raeburn  9167:     } else {
1.873     raeburn  9168:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9169:         if ($response eq 'refused') {
                   9170:             $authchk = 'refused';
                   9171:         } else {
1.901     albertel 9172:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9173:         }
1.506     raeburn  9174:     }
                   9175:     return ($authparam,$create_passwd,$authchk);
                   9176: }
                   9177: 
1.706     raeburn  9178: sub auto_photo_permission {
                   9179:     my ($cnum,$cdom,$students) = @_;
                   9180:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9181:     my ($outcome,$perm_reqd,$conditions) = 
                   9182: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9183:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9184: 	return (undef,undef);
                   9185:     }
1.706     raeburn  9186:     return ($outcome,$perm_reqd,$conditions);
                   9187: }
                   9188: 
                   9189: sub auto_checkphotos {
                   9190:     my ($uname,$udom,$pid) = @_;
                   9191:     my $homeserver = &homeserver($uname,$udom);
                   9192:     my ($result,$resulttype);
                   9193:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9194: 				   &escape($uname).':'.&escape($pid),
                   9195: 				   $homeserver));
1.709     albertel 9196:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9197: 	return (undef,undef);
                   9198:     }
1.706     raeburn  9199:     if ($outcome) {
                   9200:         ($result,$resulttype) = split(/:/,$outcome);
                   9201:     } 
                   9202:     return ($result,$resulttype);
                   9203: }
                   9204: 
                   9205: sub auto_photochoice {
                   9206:     my ($cnum,$cdom) = @_;
                   9207:     my $homeserver = &homeserver($cnum,$cdom);
                   9208:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9209: 						       &escape($cdom),
                   9210: 						       $homeserver)));
1.709     albertel 9211:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9212: 	return (undef,undef);
                   9213:     }
1.706     raeburn  9214:     return ($update,$comment);
                   9215: }
                   9216: 
                   9217: sub auto_photoupdate {
                   9218:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9219:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9220:     my $host=&hostname($homeserver);
1.706     raeburn  9221:     my $cmd = '';
                   9222:     my $maxtries = 1;
1.800     albertel 9223:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9224:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9225:     }
                   9226:     $cmd =~ s/%%$//;
                   9227:     $cmd = &escape($cmd);
                   9228:     my $query = 'institutionalphotos';
                   9229:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9230:     unless ($queryid=~/^\Q$host\E\_/) {
                   9231:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9232:         return 'error: '.$queryid;
                   9233:     }
                   9234:     my $reply = &get_query_reply($queryid);
                   9235:     my $tries = 1;
                   9236:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9237:         $reply = &get_query_reply($queryid);
                   9238:         $tries ++;
                   9239:     }
                   9240:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9241:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9242:     } else {
                   9243:         my @responses = split(/:/,$reply);
                   9244:         my $outcome = shift(@responses); 
                   9245:         foreach my $item (@responses) {
                   9246:             my ($key,$value) = split(/=/,$item);
                   9247:             $$photo{$key} = $value;
                   9248:         }
                   9249:         return $outcome;
                   9250:     }
                   9251:     return 'error';
                   9252: }
                   9253: 
1.521     raeburn  9254: sub auto_instcode_format {
1.793     albertel 9255:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9256: 	$cat_order) = @_;
1.521     raeburn  9257:     my $courses = '';
1.772     raeburn  9258:     my @homeservers;
1.521     raeburn  9259:     if ($caller eq 'global') {
1.841     albertel 9260: 	my %servers = &get_servers($codedom,'library');
                   9261: 	foreach my $tryserver (keys(%servers)) {
                   9262: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9263: 		push(@homeservers,$tryserver);
                   9264: 	    }
1.584     raeburn  9265:         }
1.1022    raeburn  9266:     } elsif ($caller eq 'requests') {
                   9267:         if ($codedom =~ /^$match_domain$/) {
                   9268:             my $chome = &domain($codedom,'primary');
                   9269:             unless ($chome eq 'no_host') {
                   9270:                 push(@homeservers,$chome);
                   9271:             }
                   9272:         }
1.521     raeburn  9273:     } else {
1.772     raeburn  9274:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9275:     }
1.793     albertel 9276:     foreach my $code (keys(%{$instcodes})) {
                   9277:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9278:     }
                   9279:     chop($courses);
1.772     raeburn  9280:     my $ok_response = 0;
                   9281:     my $response;
                   9282:     while (@homeservers > 0 && $ok_response == 0) {
                   9283:         my $server = shift(@homeservers); 
                   9284:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9285:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9286:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9287: 		split(/:/,$response);
1.772     raeburn  9288:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9289:             push(@{$codetitles},&str2array($codetitles_str));
                   9290:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9291:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9292:             $ok_response = 1;
                   9293:         }
                   9294:     }
                   9295:     if ($ok_response) {
1.521     raeburn  9296:         return 'ok';
1.772     raeburn  9297:     } else {
                   9298:         return $response;
1.521     raeburn  9299:     }
                   9300: }
                   9301: 
1.792     raeburn  9302: sub auto_instcode_defaults {
                   9303:     my ($domain,$returnhash,$code_order) = @_;
                   9304:     my @homeservers;
1.841     albertel 9305: 
                   9306:     my %servers = &get_servers($domain,'library');
                   9307:     foreach my $tryserver (keys(%servers)) {
                   9308: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9309: 	    push(@homeservers,$tryserver);
                   9310: 	}
1.792     raeburn  9311:     }
1.841     albertel 9312: 
1.792     raeburn  9313:     my $response;
1.841     albertel 9314:     foreach my $server (@homeservers) {
1.792     raeburn  9315:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9316:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9317: 	
                   9318: 	foreach my $pair (split(/\&/,$response)) {
                   9319: 	    my ($name,$value)=split(/\=/,$pair);
                   9320: 	    if ($name eq 'code_order') {
                   9321: 		@{$code_order} = split(/\&/,&unescape($value));
                   9322: 	    } else {
                   9323: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9324: 	    }
                   9325: 	}
                   9326: 	return 'ok';
1.792     raeburn  9327:     }
1.841     albertel 9328: 
                   9329:     return $response;
1.1003    raeburn  9330: }
                   9331: 
                   9332: sub auto_possible_instcodes {
1.1007    raeburn  9333:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9334:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9335:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9336:         return;
                   9337:     }
1.1003    raeburn  9338:     my (@homeservers,$uhome);
                   9339:     if (defined(&domain($domain,'primary'))) {
                   9340:         $uhome=&domain($domain,'primary');
                   9341:         push(@homeservers,&domain($domain,'primary'));
                   9342:     } else {
                   9343:         my %servers = &get_servers($domain,'library');
                   9344:         foreach my $tryserver (keys(%servers)) {
                   9345:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9346:                 push(@homeservers,$tryserver);
                   9347:             }
                   9348:         }
                   9349:     }
                   9350:     my $response;
                   9351:     foreach my $server (@homeservers) {
                   9352:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9353:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9354:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9355:             split(':',$response);
                   9356:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9357:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9358:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9359:             my ($name,$value)=split('=',$item);
                   9360:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9361:         }
                   9362:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9363:             my ($name,$value)=split('=',$item);
                   9364:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9365:         }
                   9366:         return 'ok';
                   9367:     }
                   9368:     return $response;
                   9369: }
1.792     raeburn  9370: 
1.1010    raeburn  9371: sub auto_courserequest_checks {
                   9372:     my ($dom) = @_;
1.1020    raeburn  9373:     my ($homeserver,%validations);
                   9374:     if ($dom =~ /^$match_domain$/) {
                   9375:         $homeserver = &domain($dom,'primary');
                   9376:     }
                   9377:     unless ($homeserver eq 'no_host') {
                   9378:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9379:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9380:             my @items = split(/&/,$response);
                   9381:             foreach my $item (@items) {
                   9382:                 my ($key,$value) = split('=',$item);
                   9383:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9384:             }
                   9385:         }
                   9386:     }
1.1010    raeburn  9387:     return %validations; 
                   9388: }
                   9389: 
1.1020    raeburn  9390: sub auto_courserequest_validation {
1.1255    raeburn  9391:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9392:     my ($homeserver,$response);
                   9393:     if ($dom =~ /^$match_domain$/) {
                   9394:         $homeserver = &domain($dom,'primary');
                   9395:     }
1.1255    raeburn  9396:     unless ($homeserver eq 'no_host') {
                   9397:         my $customdata;
                   9398:         if (ref($custominfo) eq 'HASH') {
                   9399:             $customdata = &freeze_escape($custominfo);
                   9400:         }
1.1020    raeburn  9401:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9402:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9403:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9404:                                     $customdata,$homeserver));
1.1020    raeburn  9405:     }
                   9406:     return $response;
                   9407: }
                   9408: 
1.777     albertel 9409: sub auto_validate_class_sec {
1.918     raeburn  9410:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9411:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9412:     my $ownerlist;
                   9413:     if (ref($owners) eq 'ARRAY') {
                   9414:         $ownerlist = join(',',@{$owners});
                   9415:     } else {
                   9416:         $ownerlist = $owners;
                   9417:     }
1.773     raeburn  9418:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9419:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9420:     return $response;
                   9421: }
                   9422: 
1.1367    raeburn  9423: sub auto_validate_instclasses {
                   9424:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9425:     my ($homeserver,%validations);
                   9426:     $homeserver = &homeserver($cnum,$cdom);
                   9427:     unless ($homeserver eq 'no_host') {
                   9428:         my $ownerlist;
                   9429:         if (ref($owners) eq 'ARRAY') {
                   9430:             $ownerlist = join(',',@{$owners});
                   9431:         } else {
                   9432:             $ownerlist = $owners;
                   9433:         }
                   9434:         if (ref($classesref) eq 'HASH') {
                   9435:             my $classes = &freeze_escape($classesref);
                   9436:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9437:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9438:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9439:                 my @items = split(/&/,$response);
                   9440:                 foreach my $item (@items) {
                   9441:                     my ($key,$value) = split('=',$item);
                   9442:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9443:                 }
                   9444:             }
                   9445:         }
                   9446:     }
                   9447:     return %validations;
                   9448: }
                   9449: 
1.1248    raeburn  9450: sub auto_crsreq_update {
                   9451:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9452:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9453:     my ($homeserver,%crsreqresponse);
                   9454:     if ($cdom =~ /^$match_domain$/) {
                   9455:         $homeserver = &domain($cdom,'primary');
                   9456:     }
                   9457:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9458:         my $info;
                   9459:         if (ref($inbound) eq 'HASH') {
                   9460:             $info = &freeze_escape($inbound);
                   9461:         }
                   9462:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9463:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9464:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9465:                             &escape($title).':'.&escape($code).':'.
                   9466:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9467:                             $homeserver);
1.1248    raeburn  9468:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9469:             my @items = split(/&/,$response);
                   9470:             foreach my $item (@items) {
                   9471:                 my ($key,$value) = split('=',$item);
                   9472:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9473:             }
                   9474:         }
                   9475:     }
                   9476:     return \%crsreqresponse;
                   9477: }
                   9478: 
1.1305    raeburn  9479: sub auto_export_grades {
1.1309    raeburn  9480:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9481:     my ($homeserver,%exportresponse);
                   9482:     if ($cdom =~ /^$match_domain$/) {
                   9483:         $homeserver = &domain($cdom,'primary');
                   9484:     }
                   9485:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9486:         my $info;
                   9487:         if (ref($inforef) eq 'HASH') {
                   9488:             $info = &freeze_escape($inforef);
                   9489:         }
                   9490:         if (ref($gradesref) eq 'HASH') {
                   9491:             my $grades = &freeze_escape($gradesref);
                   9492:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9493:                                 $info.':'.$grades,$homeserver);
                   9494:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9495:                 my @items = split(/&/,$response);
                   9496:                 foreach my $item (@items) {
                   9497:                     my ($key,$value) = split('=',$item);
                   9498:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9499:                 }
                   9500:             }
                   9501:         }
                   9502:     }
                   9503:     return \%exportresponse;
1.1305    raeburn  9504: }
                   9505: 
1.1287    raeburn  9506: sub check_instcode_cloning {
                   9507:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9508:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9509:         return;
                   9510:     }
                   9511:     my $canclone;
                   9512:     if (@{$code_order} > 0) {
                   9513:         my $instcoderegexp ='^';
                   9514:         my @clonecodes = split(/\&/,$cloner);
                   9515:         foreach my $item (@{$code_order}) {
                   9516:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9517:                 foreach my $pair (@clonecodes) {
                   9518:                     my ($key,$val) = split(/\=/,$pair,2);
                   9519:                     $val = &unescape($val);
                   9520:                     if ($key eq $item) {
                   9521:                         $instcoderegexp .= '('.$val.')';
                   9522:                         last;
                   9523:                     }
                   9524:                 }
                   9525:             } else {
                   9526:                 $instcoderegexp .= $codedefaults->{$item};
                   9527:             }
                   9528:         }
                   9529:         $instcoderegexp .= '$';
                   9530:         my (@from,@to);
                   9531:         eval {
                   9532:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9533:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9534:         };
                   9535:         if ((@from > 0) && (@to > 0)) {
                   9536:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9537:             if (!@diffs) {
                   9538:                 $canclone = 1;
                   9539:             }
                   9540:         }
                   9541:     }
                   9542:     return $canclone;
                   9543: }
                   9544: 
                   9545: sub default_instcode_cloning {
                   9546:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9547:     my (%codedefaults,@code_order,$canclone);
                   9548:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9549:         %codedefaults = %{$codedefaultsref};
                   9550:         @code_order = @{$codeorderref};
                   9551:     } elsif ($clonedom) {
                   9552:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9553:     }
                   9554:     if (($domdefclone) && (@code_order)) {
                   9555:         my @clonecodes = split(/\+/,$domdefclone);
                   9556:         my $instcoderegexp ='^';
                   9557:         foreach my $item (@code_order) {
                   9558:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9559:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9560:             } else {
                   9561:                 $instcoderegexp .= $codedefaults{$item};
                   9562:             }
                   9563:         }
                   9564:         $instcoderegexp .= '$';
                   9565:         my (@from,@to);
                   9566:         eval {
                   9567:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9568:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9569:         };
                   9570:         if ((@from > 0) && (@to > 0)) {
                   9571:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9572:             if (!@diffs) {
                   9573:                 $canclone = 1;
                   9574:             }
                   9575:         }
                   9576:     }
                   9577:     return $canclone;
                   9578: }
                   9579: 
1.679     raeburn  9580: # ------------------------------------------------------- Course Group routines
                   9581: 
                   9582: sub get_coursegroups {
1.809     raeburn  9583:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9584:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9585: }
                   9586: 
1.679     raeburn  9587: sub modify_coursegroup {
                   9588:     my ($cdom,$cnum,$groupsettings) = @_;
                   9589:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9590: }
                   9591: 
1.809     raeburn  9592: sub toggle_coursegroup_status {
                   9593:     my ($cdom,$cnum,$group,$action) = @_;
                   9594:     my ($from_namespace,$to_namespace);
                   9595:     if ($action eq 'delete') {
                   9596:         $from_namespace = 'coursegroups';
                   9597:         $to_namespace = 'deleted_groups';
                   9598:     } else {
                   9599:         $from_namespace = 'deleted_groups';
                   9600:         $to_namespace = 'coursegroups';
                   9601:     }
                   9602:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9603:     if (my $tmp = &error(%curr_group)) {
                   9604:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9605:         return ('read error',$tmp);
                   9606:     } else {
                   9607:         my %savedsettings = %curr_group; 
1.809     raeburn  9608:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9609:         my $deloutcome;
                   9610:         if ($result eq 'ok') {
1.809     raeburn  9611:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9612:         } else {
                   9613:             return ('write error',$result);
                   9614:         }
                   9615:         if ($deloutcome eq 'ok') {
                   9616:             return 'ok';
                   9617:         } else {
                   9618:             return ('delete error',$deloutcome);
                   9619:         }
                   9620:     }
                   9621: }
                   9622: 
1.679     raeburn  9623: sub modify_group_roles {
1.957     raeburn  9624:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9625:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9626:     my $role = 'gr/'.&escape($userprivs);
                   9627:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9628:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9629:     if ($result eq 'ok') {
                   9630:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9631:     }
1.679     raeburn  9632:     return $result;
                   9633: }
                   9634: 
                   9635: sub modify_coursegroup_membership {
                   9636:     my ($cdom,$cnum,$membership) = @_;
                   9637:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9638:     return $result;
                   9639: }
                   9640: 
1.682     raeburn  9641: sub get_active_groups {
                   9642:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9643:     my $now = time;
                   9644:     my %groups = ();
                   9645:     foreach my $key (keys(%env)) {
1.811     albertel 9646:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9647:             my ($start,$end) = split(/\./,$env{$key});
                   9648:             if (($end!=0) && ($end<$now)) { next; }
                   9649:             if (($start!=0) && ($start>$now)) { next; }
                   9650:             if ($1 eq $cdom && $2 eq $cnum) {
                   9651:                 $groups{$3} = $env{$key} ;
                   9652:             }
                   9653:         }
                   9654:     }
                   9655:     return %groups;
                   9656: }
                   9657: 
1.683     raeburn  9658: sub get_group_membership {
                   9659:     my ($cdom,$cnum,$group) = @_;
                   9660:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9661: }
                   9662: 
                   9663: sub get_users_groups {
                   9664:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9665:     my @usersgroups;
1.683     raeburn  9666:     my $cachetime=1800;
                   9667: 
                   9668:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9669:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9670:     if (defined($cached)) {
1.734     albertel 9671:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9672:     } else {  
                   9673:         $grouplist = '';
1.816     raeburn  9674:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9675:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9676:         my $access_end = $env{'course.'.$courseid.
                   9677:                               '.default_enrollment_end_date'};
                   9678:         my $now = time;
                   9679:         foreach my $key (keys(%roleshash)) {
                   9680:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9681:                 my $group = $1;
                   9682:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9683:                     my $start = $2;
                   9684:                     my $end = $1;
                   9685:                     if ($start == -1) { next; } # deleted from group
                   9686:                     if (($start!=0) && ($start>$now)) { next; }
                   9687:                     if (($end!=0) && ($end<$now)) {
                   9688:                         if ($access_end && $access_end < $now) {
                   9689:                             if ($access_end - $end < 86400) {
                   9690:                                 push(@usersgroups,$group);
1.733     raeburn  9691:                             }
                   9692:                         }
1.817     raeburn  9693:                         next;
1.733     raeburn  9694:                     }
1.817     raeburn  9695:                     push(@usersgroups,$group);
1.683     raeburn  9696:                 }
                   9697:             }
                   9698:         }
1.817     raeburn  9699:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9700:         $grouplist = join(':',@usersgroups);
                   9701:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9702:     }
1.733     raeburn  9703:     return @usersgroups;
1.683     raeburn  9704: }
                   9705: 
                   9706: sub devalidate_getgroups_cache {
                   9707:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9708:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9709: 
1.683     raeburn  9710:     my $hashid="$udom:$uname:$courseid";
                   9711:     &devalidate_cache_new('getgroups',$hashid);
                   9712: }
                   9713: 
1.12      www      9714: # ------------------------------------------------------------------ Plain Text
                   9715: 
                   9716: sub plaintext {
1.988     raeburn  9717:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9718:     if ($short =~ m{^cr/}) {
1.758     albertel 9719: 	return (split('/',$short))[-1];
                   9720:     }
1.742     raeburn  9721:     if (!defined($cid)) {
                   9722:         $cid = $env{'request.course.id'};
                   9723:     }
                   9724:     my %rolenames = (
1.1008    raeburn  9725:                       Course    => 'std',
                   9726:                       Community => 'alt1',
1.1305    raeburn  9727:                       Placement => 'std',
1.742     raeburn  9728:                     );
1.1037    raeburn  9729:     if ($cid ne '') {
                   9730:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9731:             unless ($forcedefault) {
                   9732:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9733:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9734:                 return &Apache::lonlocal::mt($roletext);
                   9735:             }
                   9736:         }
                   9737:     }
                   9738:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9739:         (defined($rolenames{$type})) && 
                   9740:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9741:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9742:     } elsif ($cid ne '') {
                   9743:         my $crstype = $env{'course.'.$cid.'.type'};
                   9744:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9745:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9746:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9747:         }
1.742     raeburn  9748:     }
1.1037    raeburn  9749:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9750: }
                   9751: 
                   9752: # ----------------------------------------------------------------- Assign Role
                   9753: 
                   9754: sub assignrole {
1.957     raeburn  9755:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9756:         $context)=@_;
1.21      www      9757:     my $mrole;
                   9758:     if ($role =~ /^cr\//) {
1.393     www      9759:         my $cwosec=$url;
1.811     albertel 9760:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9761: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9762:            my $refused = 1;
                   9763:            if ($context eq 'requestcourses') {
                   9764:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9765:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9766:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9767:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9768:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9769:                            if ($crsenv{'internal.courseowner'} eq
                   9770:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9771:                                $refused = '';
                   9772:                            }
                   9773:                        }
                   9774:                    }
                   9775:                }
                   9776:            }
                   9777:            if ($refused) {
                   9778:                &logthis('Refused custom assignrole: '.
                   9779:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9780:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9781:                return 'refused';
                   9782:            }
1.104     www      9783:         }
1.21      www      9784:         $mrole='cr';
1.678     raeburn  9785:     } elsif ($role =~ /^gr\//) {
                   9786:         my $cwogrp=$url;
1.811     albertel 9787:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9788:         unless (&allowed('mdg',$cwogrp)) {
                   9789:             &logthis('Refused group assignrole: '.
                   9790:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9791:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9792:             return 'refused';
                   9793:         }
                   9794:         $mrole='gr';
1.21      www      9795:     } else {
1.82      www      9796:         my $cwosec=$url;
1.811     albertel 9797:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9798:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9799:             my $refused;
                   9800:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9801:                 if (!(&allowed('c'.$role,$url))) {
                   9802:                     $refused = 1;
                   9803:                 }
                   9804:             } else {
                   9805:                 $refused = 1;
                   9806:             }
1.947     raeburn  9807:             if ($refused) {
1.1045    raeburn  9808:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9809:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9810:                     my %crsenv;
                   9811:                     if ($role eq 'cc' || $role eq 'co') {
                   9812:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9813:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9814:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9815:                                 if ($crsenv{'internal.courseowner'} eq 
                   9816:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9817:                                     $refused = '';
                   9818:                                 }
                   9819:                             }
                   9820:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9821:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9822:                                 if ($crsenv{'internal.courseowner'} eq 
                   9823:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9824:                                     $refused = '';
                   9825:                                 }
                   9826:                             }
                   9827:                         }
                   9828:                     }
1.1368    raeburn  9829:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9830:                     if ($role eq 'st') {
                   9831:                         $refused = '';
1.1377    raeburn  9832:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9833:                         $refused = '';
                   9834:                     }
1.1017    raeburn  9835:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9836:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9837:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9838:                         my $wrongcc;
                   9839:                         if ($cnum =~ /^$match_community$/) {
                   9840:                             $wrongcc = 1 if ($role eq 'cc');
                   9841:                         } else {
                   9842:                             $wrongcc = 1 if ($role eq 'co');
                   9843:                         }
                   9844:                         unless ($wrongcc) {
                   9845:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9846:                             if ($crsenv{'internal.courseowner'} eq 
                   9847:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9848:                                 $refused = '';
                   9849:                             }
1.1017    raeburn  9850:                         }
                   9851:                     }
1.1183    raeburn  9852:                 } elsif ($context eq 'requestauthor') {
                   9853:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9854:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9855:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9856:                             $refused = '';
                   9857:                         } else {
                   9858:                             my %domdefaults = &get_domain_defaults($udom);
                   9859:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9860:                                 my $checkbystatus;
                   9861:                                 if ($env{'user.adv'}) { 
                   9862:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9863:                                     if ($disposition eq 'automatic') {
                   9864:                                         $refused = '';
                   9865:                                     } elsif ($disposition eq '') {
                   9866:                                         $checkbystatus = 1;
                   9867:                                     } 
                   9868:                                 } else {
                   9869:                                     $checkbystatus = 1;
                   9870:                                 }
                   9871:                                 if ($checkbystatus) {
                   9872:                                     if ($env{'environment.inststatus'}) {
                   9873:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9874:                                         foreach my $type (@inststatuses) {
                   9875:                                             if (($type ne '') &&
                   9876:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9877:                                                 $refused = '';
                   9878:                                             }
                   9879:                                         }
                   9880:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9881:                                         $refused = '';
                   9882:                                     }
                   9883:                                 }
                   9884:                             }
                   9885:                         }
                   9886:                     }
1.1017    raeburn  9887:                 }
                   9888:                 if ($refused) {
1.947     raeburn  9889:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9890:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9891: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9892:                     return 'refused';
                   9893:                 }
1.932     raeburn  9894:             }
1.1131    raeburn  9895:         } elsif ($role eq 'au') {
                   9896:             if ($url ne '/'.$udom.'/') {
                   9897:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9898:                          ' to assign author role for '.$uname.':'.$udom.
                   9899:                          ' in domain: '.$url.' refused (wrong domain).');
                   9900:                 return 'refused';
                   9901:             }
1.104     www      9902:         }
1.21      www      9903:         $mrole=$role;
                   9904:     }
1.620     albertel 9905:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9906:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9907:     if ($end) { $command.='_'.$end; }
1.21      www      9908:     if ($start) {
                   9909: 	if ($end) { 
1.81      www      9910:            $command.='_'.$start; 
1.21      www      9911:         } else {
1.81      www      9912:            $command.='_0_'.$start;
1.21      www      9913:         }
                   9914:     }
1.739     raeburn  9915:     my $origstart = $start;
                   9916:     my $origend = $end;
1.957     raeburn  9917:     my $delflag;
1.357     www      9918: # actually delete
                   9919:     if ($deleteflag) {
1.373     www      9920: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9921: # modify command to delete the role
1.620     albertel 9922:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9923:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9924: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9925: # set start and finish to negative values for userrolelog
                   9926:            $start=-1;
                   9927:            $end=-1;
1.957     raeburn  9928:            $delflag = 1;
1.357     www      9929:         }
                   9930:     }
                   9931: # send command
1.349     www      9932:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9933: # log new user role if status is ok
1.349     www      9934:     if ($answer eq 'ok') {
1.663     raeburn  9935: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9936:         if (($role eq 'cc') || ($role eq 'in') ||
                   9937:             ($role eq 'ep') || ($role eq 'ad') ||
                   9938:             ($role eq 'ta') || ($role eq 'st') ||
                   9939:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9940:             ($role eq 'co')) {
1.1200    raeburn  9941: # for course roles, perform group memberships changes triggered by role change.
                   9942:             unless ($role =~ /^gr/) {
                   9943:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9944:                                                  $origstart,$selfenroll,$context);
                   9945:             }
1.1184    raeburn  9946:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9947:                            $selfenroll,$context);
                   9948:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9949:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9950:                  ($role eq 'da')) {
1.1184    raeburn  9951:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9952:                            $context);
                   9953:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9954:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9955:                              $context); 
                   9956:         }
1.1053    raeburn  9957:         if ($role eq 'cc') {
                   9958:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9959:         }
1.349     www      9960:     }
                   9961:     return $answer;
1.169     harris41 9962: }
                   9963: 
1.1053    raeburn  9964: sub autoupdate_coowners {
                   9965:     my ($url,$end,$start,$uname,$udom) = @_;
                   9966:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9967:     if (($cdom ne '') && ($cnum ne '')) {
                   9968:         my $now = time;
                   9969:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9970:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9971:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9972:             my $instcode = $coursehash{'internal.coursecode'};
                   9973:             if ($instcode ne '') {
1.1056    raeburn  9974:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9975:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9976:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9977:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9978:                         if ($result eq 'valid') {
                   9979:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9980:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9981:                                     push(@newcoowners,$coowner);
                   9982:                                 }
                   9983:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9984:                                     push(@newcoowners,$uname.':'.$udom);
                   9985:                                 }
                   9986:                                 @newcoowners = sort(@newcoowners);
                   9987:                             } else {
                   9988:                                 push(@newcoowners,$uname.':'.$udom);
                   9989:                             }
                   9990:                         } else {
                   9991:                             if ($coursehash{'internal.co-owners'}) {
                   9992:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9993:                                     unless ($coowner eq $uname.':'.$udom) {
                   9994:                                         push(@newcoowners,$coowner);
                   9995:                                     }
                   9996:                                 }
                   9997:                                 unless (@newcoowners > 0) {
                   9998:                                     $delcoowners = 1;
                   9999:                                     $coowners = '';
                   10000:                                 }
                   10001:                             }
                   10002:                         }
                   10003:                         if (@newcoowners || $delcoowners) {
                   10004:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10005:                                             $delcoowners,@newcoowners);
                   10006:                         }
                   10007:                     }
                   10008:                 }
                   10009:             }
                   10010:         }
                   10011:     }
                   10012: }
                   10013: 
                   10014: sub store_coowners {
                   10015:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10016:     my $cid = $cdom.'_'.$cnum;
                   10017:     my ($coowners,$delresult,$putresult);
                   10018:     if (@newcoowners) {
                   10019:         $coowners = join(',',@newcoowners);
                   10020:         my %coownershash = (
                   10021:                             'internal.co-owners' => $coowners,
                   10022:                            );
                   10023:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10024:         if ($putresult eq 'ok') {
                   10025:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10026:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10027:             }
                   10028:         }
                   10029:     }
                   10030:     if ($delcoowners) {
                   10031:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10032:         if ($delresult eq 'ok') {
                   10033:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10034:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10035:             }
                   10036:         }
                   10037:     }
                   10038:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10039:         my %crsinfo =
                   10040:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10041:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10042:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10043:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10044:         }
                   10045:     }
                   10046: }
                   10047: 
1.169     harris41 10048: # -------------------------------------------------- Modify user authentication
1.197     www      10049: # Overrides without validation
                   10050: 
1.169     harris41 10051: sub modifyuserauth {
                   10052:     my ($udom,$uname,$umode,$upass)=@_;
                   10053:     my $uhome=&homeserver($uname,$udom);
1.197     www      10054:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   10055:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10056:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10057:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10058:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10059: 		     &escape($upass),$uhome);
1.620     albertel 10060:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10061:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   10062:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   10063:     &log($udom,,$uname,$uhome,
1.620     albertel 10064:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10065:                                      $env{'user.name'}.', '.$umode.
1.197     www      10066:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 10067:     unless ($reply eq 'ok') {
1.197     www      10068:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10069: 	return 'error: '.$reply;
                   10070:     }   
1.170     harris41 10071:     return 'ok';
1.80      www      10072: }
                   10073: 
1.81      www      10074: # --------------------------------------------------------------- Modify a user
1.80      www      10075: 
1.81      www      10076: sub modifyuser {
1.206     matthew  10077:     my ($udom,    $uname, $uid,
                   10078:         $umode,   $upass, $first,
                   10079:         $middle,  $last,  $gene,
1.1058    raeburn  10080:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10081:     $udom= &LONCAPA::clean_domain($udom);
                   10082:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10083:     my $showcandelete = 'none';
                   10084:     if (ref($candelete) eq 'ARRAY') {
                   10085:         if (@{$candelete} > 0) {
                   10086:             $showcandelete = join(', ',@{$candelete});
                   10087:         }
                   10088:     }
1.81      www      10089:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10090:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10091: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10092:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10093:                                      ' desiredhome not specified'). 
1.620     albertel 10094:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10095:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10096:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10097:     my $newuser;
                   10098:     if ($uhome eq 'no_host') {
                   10099:         $newuser = 1;
1.1368    raeburn  10100:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10101:                 ($umode eq 'lti')) {
                   10102:             return 'error: more information needed to create new user';
                   10103:         }
1.1075    raeburn  10104:     }
1.80      www      10105: # ----------------------------------------------------------------- Create User
1.406     albertel 10106:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10107: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10108:         my $unhome='';
1.844     albertel 10109:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10110:             $unhome = $desiredhome;
1.620     albertel 10111: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10112: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10113:         } else { # load balancing routine for determining $unhome
1.81      www      10114:             my $loadm=10000000;
1.841     albertel 10115: 	    my %servers = &get_servers($udom,'library');
                   10116: 	    foreach my $tryserver (keys(%servers)) {
                   10117: 		my $answer=reply('load',$tryserver);
                   10118: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10119: 		    $loadm=$answer;
                   10120: 		    $unhome=$tryserver;
                   10121: 		}
1.80      www      10122: 	    }
                   10123:         }
                   10124:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10125: 	    return 'error: unable to find a home server for '.$uname.
                   10126:                    ' in domain '.$udom;
1.80      www      10127:         }
                   10128:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10129:                          &escape($upass),$unhome);
                   10130: 	unless ($reply eq 'ok') {
                   10131:             return 'error: '.$reply;
                   10132:         }   
1.230     stredwic 10133:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10134:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10135: 	    return 'error: unable verify users home machine.';
1.80      www      10136:         }
1.209     matthew  10137:     }   # End of creation of new user
1.80      www      10138: # ---------------------------------------------------------------------- Add ID
                   10139:     if ($uid) {
                   10140:        $uid=~tr/A-Z/a-z/;
                   10141:        my %uidhash=&idrget($udom,$uname);
1.196     www      10142:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10143:          && (!$forceid)) {
1.80      www      10144: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10145: 	      return 'error: user id "'.$uid.'" does not match '.
                   10146:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10147:           }
                   10148:        } else {
1.1300    raeburn  10149: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10150:        }
                   10151:     }
                   10152: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10153:     my @tmp=&get('environment',
1.899     raeburn  10154: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10155:                     'permanentemail','inststatus'],
1.134     albertel 10156: 		   $udom,$uname);
1.1075    raeburn  10157:     my (%names,%oldnames);
1.313     matthew  10158:     if ($tmp[0] =~ m/^error:.*/) { 
                   10159:         %names=(); 
                   10160:     } else {
                   10161:         %names = @tmp;
1.1075    raeburn  10162:         %oldnames = %names;
1.313     matthew  10163:     }
1.388     www      10164: #
1.1058    raeburn  10165: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10166: # of users did not contain them), do not overwrite existing values
                   10167: # unless field is in $candelete array ref.  
                   10168: #
                   10169: 
                   10170:     my @fields = ('firstname','middlename','lastname','generation',
                   10171:                   'permanentemail','id');
                   10172:     my %newvalues;
                   10173:     if (ref($candelete) eq 'ARRAY') {
                   10174:         foreach my $field (@fields) {
                   10175:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10176:                 if ($field eq 'firstname') {
                   10177:                     $names{$field} = $first;
                   10178:                 } elsif ($field eq 'middlename') {
                   10179:                     $names{$field} = $middle;
                   10180:                 } elsif ($field eq 'lastname') {
                   10181:                     $names{$field} = $last;
                   10182:                 } elsif ($field eq 'generation') { 
                   10183:                     $names{$field} = $gene;
                   10184:                 } elsif ($field eq 'permanentemail') {
                   10185:                     $names{$field} = $email;
                   10186:                 } elsif ($field eq 'id') {
                   10187:                     $names{$field}  = $uid;
                   10188:                 }
                   10189:             }
                   10190:         }
                   10191:     }
1.388     www      10192:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10193:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10194:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10195:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10196:     if ($email) {
                   10197:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10198:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10199:     }
1.899     raeburn  10200:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10201:     if (defined($inststatus)) {
                   10202:         $names{'inststatus'} = '';
                   10203:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10204:         if (ref($usertypes) eq 'HASH') {
                   10205:             my @okstatuses; 
                   10206:             foreach my $item (split(/:/,$inststatus)) {
                   10207:                 if (defined($usertypes->{$item})) {
                   10208:                     push(@okstatuses,$item);  
                   10209:                 }
                   10210:             }
                   10211:             if (@okstatuses) {
                   10212:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10213:             }
                   10214:         }
                   10215:     }
1.1075    raeburn  10216:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10217:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10218:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10219:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10220:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10221:     } else {
                   10222:         $logmsg .= ' during self creation';
                   10223:     }
1.1075    raeburn  10224:     my $changed;
                   10225:     if ($newuser) {
                   10226:         $changed = 1;
                   10227:     } else {
                   10228:         foreach my $field (@fields) {
                   10229:             if ($names{$field} ne $oldnames{$field}) {
                   10230:                 $changed = 1;
                   10231:                 last;
                   10232:             }
                   10233:         }
                   10234:     }
                   10235:     unless ($changed) {
                   10236:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10237:         &logthis($logmsg);
                   10238:         return 'ok';
                   10239:     }
                   10240:     my $reply = &put('environment', \%names, $udom,$uname);
                   10241:     if ($reply ne 'ok') { 
                   10242:         return 'error: '.$reply;
                   10243:     }
1.1087    raeburn  10244:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10245:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10246:     }
1.1075    raeburn  10247:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10248:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10249:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10250:     &logthis($logmsg);
1.134     albertel 10251:     return 'ok';
1.80      www      10252: }
                   10253: 
1.81      www      10254: # -------------------------------------------------------------- Modify student
1.80      www      10255: 
1.81      www      10256: sub modifystudent {
                   10257:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10258:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10259:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10260:     if (!$cid) {
1.620     albertel 10261: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10262: 	    return 'not_in_class';
                   10263: 	}
1.80      www      10264:     }
                   10265: # --------------------------------------------------------------- Make the user
1.81      www      10266:     my $reply=&modifyuser
1.209     matthew  10267: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10268:          $desiredhome,$email,$inststatus);
1.80      www      10269:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10270:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10271:     # student's environment
1.297     matthew  10272:     $uid = undef if (!$forceid);
1.455     albertel 10273:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10274:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10275:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10276:     return $reply;
                   10277: }
                   10278: 
                   10279: sub modify_student_enrollment {
1.1216    raeburn  10280:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10281:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10282:     my ($cdom,$cnum,$chome);
                   10283:     if (!$cid) {
1.620     albertel 10284: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10285: 	    return 'not_in_class';
                   10286: 	}
1.620     albertel 10287: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10288: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10289:     } else {
                   10290: 	($cdom,$cnum)=split(/_/,$cid);
                   10291:     }
1.620     albertel 10292:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10293:     if (!$chome) {
1.457     raeburn  10294: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10295:     }
1.455     albertel 10296:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10297:     # Make sure the user exists
1.81      www      10298:     my $uhome=&homeserver($uname,$udom);
                   10299:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10300: 	return 'error: no such user';
                   10301:     }
1.297     matthew  10302:     # Get student data if we were not given enough information
                   10303:     if (!defined($first)  || $first  eq '' || 
                   10304:         !defined($last)   || $last   eq '' || 
                   10305:         !defined($uid)    || $uid    eq '' || 
                   10306:         !defined($middle) || $middle eq '' || 
                   10307:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10308:         # They did not supply us with enough data to enroll the student, so
                   10309:         # we need to pick up more information.
1.297     matthew  10310:         my %tmp = &get('environment',
1.294     matthew  10311:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10312:                        ,$udom,$uname);
                   10313: 
1.800     albertel 10314:         #foreach my $key (keys(%tmp)) {
                   10315:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10316:         #}
1.294     matthew  10317:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10318:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10319:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10320:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10321:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10322:     }
1.556     albertel 10323:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10324:     my $user = "$uname:$udom";
                   10325:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10326:     my $reply=cput('classlist',
1.1148    raeburn  10327: 		   {$user => 
1.1314    raeburn  10328: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10329: 		   $cdom,$cnum);
1.1148    raeburn  10330:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10331:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10332:     } else { 
1.81      www      10333: 	return 'error: '.$reply;
                   10334:     }
1.297     matthew  10335:     # Add student role to user
1.83      www      10336:     my $uurl='/'.$cid;
1.81      www      10337:     $uurl=~s/\_/\//g;
                   10338:     if ($usec) {
                   10339: 	$uurl.='/'.$usec;
                   10340:     }
1.1148    raeburn  10341:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10342:                              $selfenroll,$context);
                   10343:     if ($result ne 'ok') {
                   10344:         if ($old_entry{$user} ne '') {
                   10345:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10346:         } else {
                   10347:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10348:         }
                   10349:     }
                   10350:     return $result; 
1.21      www      10351: }
                   10352: 
1.556     albertel 10353: sub format_name {
                   10354:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10355:     my $name;
                   10356:     if ($first ne 'lastname') {
                   10357: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10358:     } else {
                   10359: 	if ($lastname=~/\S/) {
                   10360: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10361: 	    $name=~s/\s+,/,/;
                   10362: 	} else {
                   10363: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10364: 	}
                   10365:     }
                   10366:     $name=~s/^\s+//;
                   10367:     $name=~s/\s+$//;
                   10368:     $name=~s/\s+/ /g;
                   10369:     return $name;
                   10370: }
                   10371: 
1.84      www      10372: # ------------------------------------------------- Write to course preferences
                   10373: 
                   10374: sub writecoursepref {
                   10375:     my ($courseid,%prefs)=@_;
                   10376:     $courseid=~s/^\///;
                   10377:     $courseid=~s/\_/\//g;
                   10378:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10379:     my $chome=homeserver($cnum,$cdomain);
                   10380:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10381: 	return 'error: no such course';
                   10382:     }
                   10383:     my $cstring='';
1.800     albertel 10384:     foreach my $pref (keys(%prefs)) {
                   10385: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10386:     }
1.84      www      10387:     $cstring=~s/\&$//;
                   10388:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10389: }
                   10390: 
                   10391: # ---------------------------------------------------------- Make/modify course
                   10392: 
                   10393: sub createcourse {
1.741     raeburn  10394:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10395:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10396:     $url=&declutter($url);
                   10397:     my $cid='';
1.1028    raeburn  10398:     if ($context eq 'requestcourses') {
                   10399:         my $can_create = 0;
                   10400:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10401:         if ($udom eq $ownerdom) {
                   10402:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10403:                                   $context)) {
                   10404:                 $can_create = 1;
                   10405:             }
                   10406:         } else {
                   10407:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10408:                                            $category);
                   10409:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10410:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10411:                 if (@curr > 0) {
                   10412:                     my @options = qw(approval validate autolimit);
                   10413:                     my $optregex = join('|',@options);
                   10414:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10415:                         $can_create = 1;
                   10416:                     }
                   10417:                 }
                   10418:             }
                   10419:         }
                   10420:         if ($can_create) {
                   10421:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10422:                 unless (&allowed('ccc',$udom)) {
                   10423:                     return 'refused'; 
                   10424:                 }
1.1017    raeburn  10425:             }
                   10426:         } else {
                   10427:             return 'refused';
                   10428:         }
1.1028    raeburn  10429:     } elsif (!&allowed('ccc',$udom)) {
                   10430:         return 'refused';
1.84      www      10431:     }
1.1011    raeburn  10432: # --------------------------------------------------------------- Get Unique ID
                   10433:     my $uname;
                   10434:     if ($cnum =~ /^$match_courseid$/) {
                   10435:         my $chome=&homeserver($cnum,$udom,'true');
                   10436:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10437:             $uname = $cnum;
                   10438:         } else {
1.1038    raeburn  10439:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10440:         }
                   10441:     } else {
1.1038    raeburn  10442:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10443:     }
                   10444:     return $uname if ($uname =~ /^error/);
                   10445: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10446:     if (!defined($course_server)) {
                   10447:         if (defined(&domain($udom,'primary'))) {
                   10448:             $course_server = &domain($udom,'primary');
                   10449:         } else {
                   10450:             $course_server = $env{'user.home'}; 
                   10451:         }
                   10452:     }
                   10453:     my %host_servers =
                   10454:         &Apache::lonnet::get_servers($udom,'library');
                   10455:     unless ($host_servers{$course_server}) {
                   10456:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10457:     }
1.84      www      10458: # ------------------------------------------------------------- Make the course
                   10459:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10460:                       $course_server);
1.84      www      10461:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10462:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10463:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10464: 	return 'error: no such course';
                   10465:     }
1.271     www      10466: # ----------------------------------------------------------------- Course made
1.516     raeburn  10467: # log existence
1.1029    raeburn  10468:     my $now = time;
1.918     raeburn  10469:     my $newcourse = {
                   10470:                     $udom.'_'.$uname => {
1.921     raeburn  10471:                                      description => $description,
                   10472:                                      inst_code   => $inst_code,
                   10473:                                      owner       => $course_owner,
                   10474:                                      type        => $crstype,
1.1029    raeburn  10475:                                      creator     => $env{'user.name'}.':'.
                   10476:                                                     $env{'user.domain'},
                   10477:                                      created     => $now,
                   10478:                                      context     => $context,
1.918     raeburn  10479:                                                 },
                   10480:                     };
1.921     raeburn  10481:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10482: # set toplevel url
1.271     www      10483:     my $topurl=$url;
                   10484:     unless ($nonstandard) {
                   10485: # ------------------------------------------ For standard courses, make top url
                   10486:         my $mapurl=&clutter($url);
1.278     www      10487:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10488:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10489: <map>
                   10490: <resource id="1" type="start"></resource>
                   10491: <resource id="2" src="$mapurl"></resource>
                   10492: <resource id="3" type="finish"></resource>
                   10493: <link index="1" from="1" to="2"></link>
                   10494: <link index="2" from="2" to="3"></link>
                   10495: </map>
                   10496: ENDINITMAP
                   10497:         $topurl=&declutter(
1.638     albertel 10498:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10499:                           );
                   10500:     }
                   10501: # ----------------------------------------------------------- Write preferences
1.84      www      10502:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10503:                      ('description'              => $description,
                   10504:                       'url'                      => $topurl,
                   10505:                       'internal.creator'         => $env{'user.name'}.':'.
                   10506:                                                     $env{'user.domain'},
                   10507:                       'internal.created'         => $now,
                   10508:                       'internal.creationcontext' => $context)
                   10509:                     );
1.84      www      10510:     return '/'.$udom.'/'.$uname;
                   10511: }
                   10512: 
1.1011    raeburn  10513: # ------------------------------------------------------------------- Create ID
                   10514: sub generate_coursenum {
1.1038    raeburn  10515:     my ($udom,$crstype) = @_;
1.1011    raeburn  10516:     my $domdesc = &domain($udom);
                   10517:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10518:     my $first;
                   10519:     if ($crstype eq 'Community') {
                   10520:         $first = '0';
                   10521:     } else {
                   10522:         $first = int(1+rand(9)); 
                   10523:     } 
                   10524:     my $uname=$first.
1.1011    raeburn  10525:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10526:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10527:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10528: # ----------------------------------------------- Make sure that does not exist
                   10529:     my $uhome=&homeserver($uname,$udom,'true');
                   10530:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10531:         if ($crstype eq 'Community') {
                   10532:             $first = '0';
                   10533:         } else {
                   10534:             $first = int(1+rand(9));
                   10535:         }
                   10536:         $uname=$first.
1.1011    raeburn  10537:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10538:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10539:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10540:         $uhome=&homeserver($uname,$udom,'true');
                   10541:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10542:             return 'error: unable to generate unique course-ID';
                   10543:         }
                   10544:     }
                   10545:     return $uname;
                   10546: }
                   10547: 
1.813     albertel 10548: sub is_course {
1.1167    droeschl 10549:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10550:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10551: 
1.1381    raeburn  10552:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10553:     my $uhome=&homeserver($cnum,$cdom);
                   10554:     my $iscourse;
                   10555:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10556:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10557:     } else {
                   10558:         my $hashid = $cdom.':'.$cnum;
                   10559:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10560:         unless (defined($cached)) {
                   10561:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10562:                                         $cnum,undef,undef,'.');
                   10563:             $iscourse = 0;
                   10564:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10565:                 $iscourse = 1;
                   10566:             }
                   10567:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10568:         }
                   10569:     }
                   10570:     return unless ($iscourse);
1.1167    droeschl 10571:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10572: }
                   10573: 
1.1015    raeburn  10574: sub store_userdata {
                   10575:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10576:     my $result;
1.1016    raeburn  10577:     if ($datakey ne '') {
1.1013    raeburn  10578:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10579:             if ($udom eq '' || $uname eq '') {
                   10580:                 $udom = $env{'user.domain'};
                   10581:                 $uname = $env{'user.name'};
                   10582:             }
                   10583:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10584:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10585:                 $result = 'error: no_host';
                   10586:             } else {
                   10587:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10588:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10589: 
                   10590:                 my $namevalue='';
                   10591:                 foreach my $key (keys(%{$storehash})) {
                   10592:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10593:                 }
                   10594:                 $namevalue=~s/\&$//;
1.1224    raeburn  10595:                 unless ($namespace eq 'courserequests') {
                   10596:                     $datakey = &escape($datakey);
                   10597:                 }
1.1105    raeburn  10598:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10599:                                   $namevalue,$uhome);
1.1013    raeburn  10600:             }
                   10601:         } else {
                   10602:             $result = 'error: data to store was not a hash reference'; 
                   10603:         }
                   10604:     } else {
                   10605:         $result= 'error: invalid requestkey'; 
                   10606:     }
                   10607:     return $result;
                   10608: }
                   10609: 
1.21      www      10610: # ---------------------------------------------------------- Assign Custom Role
                   10611: 
                   10612: sub assigncustomrole {
1.957     raeburn  10613:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10614:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10615:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10616: }
                   10617: 
                   10618: # ----------------------------------------------------------------- Revoke Role
                   10619: 
                   10620: sub revokerole {
1.957     raeburn  10621:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10622:     my $now=time;
1.965     raeburn  10623:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10624: }
                   10625: 
                   10626: # ---------------------------------------------------------- Revoke Custom Role
                   10627: 
                   10628: sub revokecustomrole {
1.957     raeburn  10629:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10630:     my $now=time;
1.357     www      10631:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10632:            $deleteflag,$selfenroll,$context);
1.17      www      10633: }
                   10634: 
1.533     banghart 10635: # ------------------------------------------------------------ Disk usage
1.535     albertel 10636: sub diskusage {
1.955     raeburn  10637:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10638:     $directorypath =~ s/\/$//;
                   10639:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10640:                        .&escape($getpropath).':'.&escape($uname).':'
                   10641:                        .&escape($udom),homeserver($uname,$udom));
                   10642:     if ($listing eq 'unknown_cmd') {
                   10643:         if ($getpropath) {
                   10644:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10645:         }
                   10646:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10647:     }
1.514     albertel 10648:     return $listing;
1.512     banghart 10649: }
                   10650: 
1.566     banghart 10651: sub is_locked {
1.1096    raeburn  10652:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10653:     my @check;
                   10654:     my $is_locked;
1.1093    raeburn  10655:     push (@check,$file_name);
1.613     albertel 10656:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10657: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10658:     my ($tmp)=keys(%locked);
                   10659:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10660:     
1.566     banghart 10661:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10662:         $is_locked = 'false';
                   10663:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10664:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10665:                $is_locked = 'true';
1.1096    raeburn  10666:                if (ref($which) eq 'ARRAY') {
                   10667:                    push(@{$which},$entry);
                   10668:                } else {
                   10669:                    last;
                   10670:                }
1.745     raeburn  10671:            }
                   10672:        }
1.566     banghart 10673:     } else {
                   10674:         $is_locked = 'false';
                   10675:     }
1.1093    raeburn  10676:     return $is_locked;
1.566     banghart 10677: }
                   10678: 
1.759     albertel 10679: sub declutter_portfile {
                   10680:     my ($file) = @_;
1.833     albertel 10681:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10682:     return $file;
                   10683: }
                   10684: 
1.559     banghart 10685: # ------------------------------------------------------------- Mark as Read Only
                   10686: 
                   10687: sub mark_as_readonly {
                   10688:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10689:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10690:     my ($tmp)=keys(%current_permissions);
                   10691:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10692:     foreach my $file (@{$files}) {
1.759     albertel 10693: 	$file = &declutter_portfile($file);
1.561     banghart 10694:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10695:     }
1.613     albertel 10696:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10697:     return;
                   10698: }
                   10699: 
1.572     banghart 10700: # ------------------------------------------------------------Save Selected Files
                   10701: 
                   10702: sub save_selected_files {
                   10703:     my ($user, $path, @files) = @_;
                   10704:     my $filename = $user."savedfiles";
1.573     banghart 10705:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10706:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10707:     foreach my $file (@files) {
1.620     albertel 10708:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10709:     }
                   10710:     foreach my $file (@other_files) {
1.574     banghart 10711:         print (OUT $file."\n");
1.572     banghart 10712:     }
1.574     banghart 10713:     close (OUT);
1.572     banghart 10714:     return 'ok';
                   10715: }
                   10716: 
1.574     banghart 10717: sub clear_selected_files {
                   10718:     my ($user) = @_;
                   10719:     my $filename = $user."savedfiles";
1.1359    raeburn  10720:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10721:     print (OUT undef);
                   10722:     close (OUT);
                   10723:     return ("ok");    
                   10724: }
                   10725: 
1.572     banghart 10726: sub files_in_path {
                   10727:     my ($user, $path) = @_;
                   10728:     my $filename = $user."savedfiles";
                   10729:     my %return_files;
1.1359    raeburn  10730:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10731:     while (my $line_in = <IN>) {
1.574     banghart 10732:         chomp ($line_in);
                   10733:         my @paths_and_file = split (m!/!, $line_in);
                   10734:         my $file_part = pop (@paths_and_file);
                   10735:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10736:         $path_part.='/';
                   10737:         my $path_and_file = $path_part.$file_part;
                   10738:         if ($path_part eq $path) {
                   10739:             $return_files{$file_part}= 'selected';
                   10740:         }
                   10741:     }
1.574     banghart 10742:     close (IN);
                   10743:     return (\%return_files);
1.572     banghart 10744: }
                   10745: 
                   10746: # called in portfolio select mode, to show files selected NOT in current directory
                   10747: sub files_not_in_path {
                   10748:     my ($user, $path) = @_;
                   10749:     my $filename = $user."savedfiles";
                   10750:     my @return_files;
                   10751:     my $path_part;
1.1359    raeburn  10752:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10753:     while (my $line = <IN>) {
1.572     banghart 10754:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10755:         my @paths_and_file = split(m|/|, $line);
                   10756:         my $file_part = pop(@paths_and_file);
                   10757:         chomp($file_part);
                   10758:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10759:         $path_part .= '/';
                   10760:         my $path_and_file = $path_part.$file_part;
                   10761:         if ($path_part ne $path) {
1.800     albertel 10762:             push(@return_files, ($path_and_file));
1.572     banghart 10763:         }
                   10764:     }
1.800     albertel 10765:     close(OUT);
1.574     banghart 10766:     return (@return_files);
1.572     banghart 10767: }
                   10768: 
1.1273    raeburn  10769: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10770:  
                   10771: sub portfiles_versioning {
                   10772:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10773:     my $portfolio_root = '/userfiles/portfolio';
                   10774:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10775:     foreach my $file (@{$portfiles}) {
                   10776:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10777:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10778:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10779:         my $getpropath = 1;
                   10780:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10781:                                              $stu_name,$getpropath);
                   10782:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10783:         my $new_answer = 
                   10784:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10785:         if ($new_answer ne 'problem getting file') {
                   10786:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10787:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10788:                               [$symb,$env{'request.course.id'},'graded']);
                   10789:         }
                   10790:     }
                   10791: }
                   10792: 
                   10793: sub get_next_version {
                   10794:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10795:     my $version;
                   10796:     if (ref($dir_list) eq 'ARRAY') {
                   10797:         foreach my $row (@{$dir_list}) {
                   10798:             my ($file) = split(/\&/,$row,2);
                   10799:             my ($file_name,$file_version,$file_ext) =
                   10800:                 &file_name_version_ext($file);
                   10801:             if (($file_name eq $answer_name) &&
                   10802:                 ($file_ext eq $answer_ext)) {
                   10803:                      # gets here if filename and extension match,
                   10804:                      # regardless of version
                   10805:                 if ($file_version ne '') {
                   10806:                     # a versioned file is found  so save it for later
                   10807:                     if ($file_version > $version) {
                   10808:                         $version = $file_version;
                   10809:                     }
                   10810:                 }
                   10811:             }
                   10812:         }
                   10813:     }
                   10814:     $version ++;
                   10815:     return($version);
                   10816: }
                   10817: 
                   10818: sub version_selected_portfile {
                   10819:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10820:     my ($answer_name,$answer_ver,$answer_ext) =
                   10821:         &file_name_version_ext($file_name);
                   10822:     my $new_answer;
                   10823:     $env{'form.copy'} =
                   10824:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10825:     if($env{'form.copy'} eq '-1') {
                   10826:         $new_answer = 'problem getting file';
                   10827:     } else {
                   10828:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10829:         my $copy_result = 
                   10830:             &finishuserfileupload($stu_name,$domain,'copy',
                   10831:                                   '/portfolio'.$directory.$new_answer);
                   10832:     }
                   10833:     undef($env{'form.copy'});
                   10834:     return ($new_answer);
                   10835: }
                   10836: 
                   10837: sub file_name_version_ext {
                   10838:     my ($file)=@_;
                   10839:     my @file_parts = split(/\./, $file);
                   10840:     my ($name,$version,$ext);
                   10841:     if (@file_parts > 1) {
                   10842:         $ext=pop(@file_parts);
                   10843:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10844:             $version=pop(@file_parts);
                   10845:         }
                   10846:         $name=join('.',@file_parts);
                   10847:     } else {
                   10848:         $name=join('.',@file_parts);
                   10849:     }
                   10850:     return($name,$version,$ext);
                   10851: }
                   10852: 
1.745     raeburn  10853: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10854: 
1.745     raeburn  10855: sub get_portfile_permissions {
                   10856:     my ($domain,$user) = @_;
1.613     albertel 10857:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10858:     my ($tmp)=keys(%current_permissions);
                   10859:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10860:     return \%current_permissions;
                   10861: }
                   10862: 
                   10863: #---------------------------------------------Get portfolio file access controls
                   10864: 
1.749     raeburn  10865: sub get_access_controls {
1.745     raeburn  10866:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10867:     my %access;
                   10868:     my $real_file = $file;
                   10869:     $file =~ s/\.meta$//;
1.745     raeburn  10870:     if (defined($file)) {
1.749     raeburn  10871:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10872:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10873:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10874:             }
                   10875:         }
1.745     raeburn  10876:     } else {
1.749     raeburn  10877:         foreach my $key (keys(%{$current_permissions})) {
                   10878:             if ($key =~ /\0accesscontrol$/) {
                   10879:                 if (defined($group)) {
                   10880:                     if ($key !~ m-^\Q$group\E/-) {
                   10881:                         next;
                   10882:                     }
                   10883:                 }
                   10884:                 my ($fullpath) = split(/\0/,$key);
                   10885:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10886:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10887:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10888:                     }
                   10889:                 }
                   10890:             }
                   10891:         }
                   10892:     }
                   10893:     return %access;
                   10894: }
                   10895: 
                   10896: sub modify_access_controls {
                   10897:     my ($file_name,$changes,$domain,$user)=@_;
                   10898:     my ($outcome,$deloutcome);
                   10899:     my %store_permissions;
                   10900:     my %new_values;
                   10901:     my %new_control;
                   10902:     my %translation;
                   10903:     my @deletions = ();
                   10904:     my $now = time;
                   10905:     if (exists($$changes{'activate'})) {
                   10906:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10907:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10908:             my $numnew = scalar(@newitems);
                   10909:             for (my $i=0; $i<$numnew; $i++) {
                   10910:                 my $newkey = $newitems[$i];
                   10911:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10912:                 if ($newkey =~ /^\d+:/) { 
                   10913:                     $newkey =~ s/^(\d+)/$newid/;
                   10914:                     $translation{$1} = $newid;
                   10915:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10916:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10917:                     $translation{$1} = $newid;
                   10918:                 }
1.749     raeburn  10919:                 $new_values{$file_name."\0".$newkey} = 
                   10920:                                           $$changes{'activate'}{$newitems[$i]};
                   10921:                 $new_control{$newkey} = $now;
                   10922:             }
                   10923:         }
                   10924:     }
                   10925:     my %todelete;
                   10926:     my %changed_items;
                   10927:     foreach my $action ('delete','update') {
                   10928:         if (exists($$changes{$action})) {
                   10929:             if (ref($$changes{$action}) eq 'HASH') {
                   10930:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10931:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10932:                     if ($action eq 'delete') { 
                   10933:                         $todelete{$itemnum} = 1;
                   10934:                     } else {
                   10935:                         $changed_items{$itemnum} = $key;
                   10936:                     }
                   10937:                 }
1.745     raeburn  10938:             }
                   10939:         }
1.749     raeburn  10940:     }
                   10941:     # get lock on access controls for file.
                   10942:     my $lockhash = {
                   10943:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10944:                                                        ':'.$env{'user.domain'},
                   10945:                    }; 
                   10946:     my $tries = 0;
                   10947:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10948:    
1.1288    damieng  10949:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10950:         $tries ++;
1.1289    damieng  10951:         sleep(0.1);
1.749     raeburn  10952:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10953:     }
                   10954:     if ($gotlock eq 'ok') {
                   10955:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10956:         my ($tmp)=keys(%curr_permissions);
                   10957:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10958:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10959:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10960:             if (ref($curr_controls) eq 'HASH') {
                   10961:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10962:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10963:                     if (defined($todelete{$itemnum})) {
                   10964:                         push(@deletions,$file_name."\0".$control_item);
                   10965:                     } else {
                   10966:                         if (defined($changed_items{$itemnum})) {
                   10967:                             $new_control{$changed_items{$itemnum}} = $now;
                   10968:                             push(@deletions,$file_name."\0".$control_item);
                   10969:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10970:                         } else {
                   10971:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10972:                         }
                   10973:                     }
1.745     raeburn  10974:                 }
                   10975:             }
                   10976:         }
1.970     raeburn  10977:         my ($group);
                   10978:         if (&is_course($domain,$user)) {
                   10979:             ($group,my $file) = split(/\//,$file_name,2);
                   10980:         }
1.749     raeburn  10981:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10982:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10983:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10984:         #  remove lock
                   10985:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10986:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10987:         my $sqlresult =
1.970     raeburn  10988:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10989:                                     $group);
1.749     raeburn  10990:     } else {
                   10991:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10992:     }
1.749     raeburn  10993:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10994: }
                   10995: 
1.827     raeburn  10996: sub make_public_indefinitely {
1.1271    raeburn  10997:     my (@requrl) = @_;
                   10998:     return &automated_portfile_access('public',\@requrl);
                   10999: }
                   11000: 
                   11001: sub automated_portfile_access {
                   11002:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11003:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11004:         return 'invalid';
                   11005:     }
1.1271    raeburn  11006:     my %urls;
                   11007:     if (ref($addsref) eq 'ARRAY') {
                   11008:         foreach my $requrl (@{$addsref}) {
                   11009:             if (&is_portfolio_url($requrl)) {
                   11010:                 unless (exists($urls{$requrl})) {
                   11011:                     $urls{$requrl} = 'add';
                   11012:                 }
                   11013:             }
                   11014:         }
                   11015:     }
                   11016:     if (ref($delsref) eq 'ARRAY') {
                   11017:         foreach my $requrl (@{$delsref}) { 
                   11018:             if (&is_portfolio_url($requrl)) {
                   11019:                 unless (exists($urls{$requrl})) {
                   11020:                     $urls{$requrl} = 'delete'; 
                   11021:                 }
                   11022:             }
                   11023:         }
                   11024:     }
                   11025:     unless (keys(%urls)) {
                   11026:         return 'invalid';
                   11027:     }
                   11028:     my $ip;
                   11029:     if ($accesstype eq 'ip') {
                   11030:         if (ref($info) eq 'HASH') {
                   11031:             if ($info->{'ip'} ne '') {
                   11032:                 $ip = $info->{'ip'};
                   11033:             }
                   11034:         }
                   11035:         if ($ip eq '') {
                   11036:             return 'invalid';
                   11037:         }
                   11038:     }
                   11039:     my $errors;
1.827     raeburn  11040:     my $now = time;
1.1271    raeburn  11041:     my %current_perms;
                   11042:     foreach my $requrl (sort(keys(%urls))) {
                   11043:         my $action;
                   11044:         if ($urls{$requrl} eq 'add') {
                   11045:             $action = 'activate';
                   11046:         } else {
                   11047:             $action = 'none';
                   11048:         }
                   11049:         my $aclnum = 0;
1.827     raeburn  11050:         my (undef,$udom,$unum,$file_name,$group) =
                   11051:             &parse_portfolio_url($requrl);
1.1271    raeburn  11052:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11053:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11054:         }
                   11055:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11056:                                                    $group,$file_name);
                   11057:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11058:             my ($num,$scope,$end,$start) = 
                   11059:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11060:             if ($scope eq $accesstype) {
                   11061:                 if (($start <= $now) && ($end == 0)) {
                   11062:                     if ($accesstype eq 'ip') {
                   11063:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11064:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11065:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11066:                                     if ($urls{$requrl} eq 'add') {
                   11067:                                         $action = 'none';
                   11068:                                         last;
                   11069:                                     } else {
                   11070:                                         $action = 'delete';
                   11071:                                         $aclnum = $num;
                   11072:                                         last;
                   11073:                                     }
                   11074:                                 }
                   11075:                             }
                   11076:                         }
                   11077:                     } elsif ($accesstype eq 'public') {
                   11078:                         if ($urls{$requrl} eq 'add') {
                   11079:                             $action = 'none';
                   11080:                             last;
                   11081:                         } else {
                   11082:                             $action = 'delete';
                   11083:                             $aclnum = $num;
                   11084:                             last;
                   11085:                         }
                   11086:                     }
                   11087:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11088:                     $action = 'update';
                   11089:                     $aclnum = $num;
1.1271    raeburn  11090:                     last;
1.827     raeburn  11091:                 }
                   11092:             }
                   11093:         }
                   11094:         if ($action eq 'none') {
1.1271    raeburn  11095:             next;
1.827     raeburn  11096:         } else {
                   11097:             my %changes;
                   11098:             my $newend = 0;
                   11099:             my $newstart = $now;
1.1271    raeburn  11100:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11101:             $changes{$action}{$newkey} = {
1.1271    raeburn  11102:                 type => $accesstype,
1.827     raeburn  11103:                 time => {
                   11104:                     start => $newstart,
                   11105:                     end   => $newend,
                   11106:                 },
                   11107:             };
1.1271    raeburn  11108:             if ($accesstype eq 'ip') {
                   11109:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11110:             }
1.827     raeburn  11111:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11112:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11113:             unless ($outcome eq 'ok') {
                   11114:                 $errors .= $outcome.' ';
                   11115:             }
1.827     raeburn  11116:         }
1.1271    raeburn  11117:     }
                   11118:     if ($errors) {
                   11119:         $errors =~ s/\s$//;
                   11120:         return $errors;
1.827     raeburn  11121:     } else {
1.1271    raeburn  11122:         return 'ok';
1.827     raeburn  11123:     }
                   11124: }
                   11125: 
1.745     raeburn  11126: #------------------------------------------------------Get Marked as Read Only
                   11127: 
                   11128: sub get_marked_as_readonly {
                   11129:     my ($domain,$user,$what,$group) = @_;
                   11130:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11131:     my @readonly_files;
1.629     banghart 11132:     my $cmp1=$what;
                   11133:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11134:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11135:         if (defined($group)) {
                   11136:             if ($file_name !~ m-^\Q$group\E/-) {
                   11137:                 next;
                   11138:             }
                   11139:         }
1.561     banghart 11140:         if (ref($value) eq "ARRAY"){
                   11141:             foreach my $stored_what (@{$value}) {
1.629     banghart 11142:                 my $cmp2=$stored_what;
1.759     albertel 11143:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11144:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11145:                 }
1.629     banghart 11146:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11147:                     push(@readonly_files, $file_name);
1.745     raeburn  11148:                     last;
1.563     banghart 11149:                 } elsif (!defined($what)) {
                   11150:                     push(@readonly_files, $file_name);
1.745     raeburn  11151:                     last;
1.561     banghart 11152:                 }
                   11153:             }
1.745     raeburn  11154:         }
1.561     banghart 11155:     }
                   11156:     return @readonly_files;
                   11157: }
1.577     banghart 11158: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11159: 
1.577     banghart 11160: sub get_marked_as_readonly_hash {
1.745     raeburn  11161:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11162:     my %readonly_files;
1.745     raeburn  11163:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11164:         if (defined($group)) {
                   11165:             if ($file_name !~ m-^\Q$group\E/-) {
                   11166:                 next;
                   11167:             }
                   11168:         }
1.577     banghart 11169:         if (ref($value) eq "ARRAY"){
                   11170:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11171:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11172:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11173:                         if ($lock_descriptor eq 'graded') {
                   11174:                             $readonly_files{$file_name} = 'graded';
                   11175:                         } elsif ($lock_descriptor eq 'handback') {
                   11176:                             $readonly_files{$file_name} = 'handback';
                   11177:                         } else {
                   11178:                             if (!exists($readonly_files{$file_name})) {
                   11179:                                 $readonly_files{$file_name} = 'locked';
                   11180:                             }
                   11181:                         }
1.745     raeburn  11182:                     }
1.750     banghart 11183:                 } 
1.577     banghart 11184:             }
                   11185:         } 
                   11186:     }
                   11187:     return %readonly_files;
                   11188: }
1.559     banghart 11189: # ------------------------------------------------------------ Unmark as Read Only
                   11190: 
                   11191: sub unmark_as_readonly {
1.629     banghart 11192:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11193:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11194:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11195:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11196:     my $symb_crs = $what;
                   11197:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11198:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11199:     my ($tmp)=keys(%current_permissions);
                   11200:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11201:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11202:     foreach my $file (@readonly_files) {
1.759     albertel 11203: 	my $clean_file = &declutter_portfile($file);
                   11204: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11205: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11206:         my @new_locks;
                   11207:         my @del_keys;
                   11208:         if (ref($current_locks) eq "ARRAY"){
                   11209:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11210:                 my $compare=$locker;
1.749     raeburn  11211:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11212:                     $compare=join('',@{$locker});
1.746     raeburn  11213:                     if ($compare ne $symb_crs) {
                   11214:                         push(@new_locks, $locker);
                   11215:                     }
1.563     banghart 11216:                 }
                   11217:             }
1.650     albertel 11218:             if (scalar(@new_locks) > 0) {
1.563     banghart 11219:                 $current_permissions{$file} = \@new_locks;
                   11220:             } else {
                   11221:                 push(@del_keys, $file);
1.613     albertel 11222:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11223:                 delete($current_permissions{$file});
1.563     banghart 11224:             }
                   11225:         }
1.561     banghart 11226:     }
1.613     albertel 11227:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11228:     return;
                   11229: }
1.512     banghart 11230: 
1.17      www      11231: # ------------------------------------------------------------ Directory lister
                   11232: 
                   11233: sub dirlist {
1.955     raeburn  11234:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11235:     $uri=~s/^\///;
                   11236:     $uri=~s/\/$//;
1.253     stredwic 11237:     my ($udom, $uname);
1.955     raeburn  11238:     if ($getuserdir) {
1.253     stredwic 11239:         $udom = $userdomain;
                   11240:         $uname = $username;
1.955     raeburn  11241:     } else {
                   11242:         (undef,$udom,$uname)=split(/\//,$uri);
                   11243:         if(defined($userdomain)) {
                   11244:             $udom = $userdomain;
                   11245:         }
                   11246:         if(defined($username)) {
                   11247:             $uname = $username;
                   11248:         }
1.253     stredwic 11249:     }
1.955     raeburn  11250:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11251: 
1.955     raeburn  11252:     $dirRoot = $perlvar{'lonDocRoot'};
                   11253:     if (defined($getpropath)) {
                   11254:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11255:         $dirRoot =~ s/\/$//;
1.955     raeburn  11256:     } elsif (defined($getuserdir)) {
                   11257:         my $subdir=$uname.'__';
                   11258:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11259:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11260:                    ."/$udom/$subdir/$uname";
                   11261:     } elsif (defined($alternateRoot)) {
                   11262:         $dirRoot = $alternateRoot;
1.751     banghart 11263:     }
1.253     stredwic 11264: 
                   11265:     if($udom) {
                   11266:         if($uname) {
1.1135    raeburn  11267:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11268:             if ($uhome eq 'no_host') {
                   11269:                 return ([],'no_host');
                   11270:             }
1.955     raeburn  11271:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11272:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11273:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11274:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11275:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11276:             } else {
                   11277:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11278:             }
1.605     matthew  11279:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11280:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11281:                 @listing_results = split(/:/,$listing);
                   11282:             } else {
                   11283:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11284:             }
1.1135    raeburn  11285:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11286:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11287:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11288:                 return ([],$listing);
                   11289:             } else {
                   11290:                 return (\@listing_results);
1.1135    raeburn  11291:             }
1.955     raeburn  11292:         } elsif(!$alternateRoot) {
1.1136    raeburn  11293:             my (%allusers,%listerror);
1.841     albertel 11294: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11295:  	    foreach my $tryserver (keys(%servers)) {
                   11296:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11297:                                   &escape($udom),$tryserver);
                   11298:                 if ($listing eq 'unknown_cmd') {
                   11299: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11300: 				      $udom, $tryserver);
                   11301:                 } else {
                   11302:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11303:                 }
1.841     albertel 11304: 		if ($listing eq 'unknown_cmd') {
                   11305: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11306: 				      $udom, $tryserver);
                   11307: 		    @listing_results = split(/:/,$listing);
                   11308: 		} else {
                   11309: 		    @listing_results =
                   11310: 			map { &unescape($_); } split(/:/,$listing);
                   11311: 		}
1.1136    raeburn  11312:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11313:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11314:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11315:                     $listerror{$tryserver} = $listing;
                   11316:                 } else {
1.841     albertel 11317: 		    foreach my $line (@listing_results) {
                   11318: 			my ($entry) = split(/&/,$line,2);
                   11319: 			$allusers{$entry} = 1;
                   11320: 		    }
                   11321: 		}
1.253     stredwic 11322:             }
1.1136    raeburn  11323:             my @alluserslist=();
1.800     albertel 11324:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11325:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11326:             }
1.1318    droeschl 11327: 
                   11328:             if (!%listerror) {
                   11329:                 # no errors
                   11330:                 return (\@alluserslist);
                   11331:             } elsif (scalar(keys(%servers)) == 1) {
                   11332:                 # one library server, one error 
                   11333:                 my ($key) = keys(%listerror);
                   11334:                 return (\@alluserslist, $listerror{$key});
                   11335:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11336:                 # con_lost indicates that we might miss data from at least one
                   11337:                 # library server
                   11338:                 return (\@alluserslist, 'con_lost');
                   11339:             } else {
                   11340:                 # multiple library servers and no con_lost -> data should be
                   11341:                 # complete. 
                   11342:                 return (\@alluserslist);
                   11343:             }
                   11344: 
1.253     stredwic 11345:         } else {
1.1136    raeburn  11346:             return ([],'missing username');
1.253     stredwic 11347:         }
1.955     raeburn  11348:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11349:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11350:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11351:         return (\@all_domains);
1.955     raeburn  11352:     } else {
1.1136    raeburn  11353:         return ([],'missing domain');
1.275     stredwic 11354:     }
                   11355: }
                   11356: 
                   11357: # --------------------------------------------- GetFileTimestamp
                   11358: # This function utilizes dirlist and returns the date stamp for
                   11359: # when it was last modified.  It will also return an error of -1
                   11360: # if an error occurs
                   11361: 
                   11362: sub GetFileTimestamp {
1.955     raeburn  11363:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11364:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11365:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11366:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11367:                                     undef,$getuserdir);
                   11368:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11369:         return -1;
                   11370:     }
                   11371:     if (ref($fileref) eq 'ARRAY') {
                   11372:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11373:         # @stats contains first the filename, then the stat output
                   11374:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11375:     } else {
                   11376:         return -1;
1.253     stredwic 11377:     }
1.26      www      11378: }
                   11379: 
1.712     albertel 11380: sub stat_file {
                   11381:     my ($uri) = @_;
1.787     albertel 11382:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11383: 
1.955     raeburn  11384:     my ($udom,$uname,$file);
1.712     albertel 11385:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11386: 	($udom,$uname,$file) =
1.811     albertel 11387: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11388: 	$file = 'userfiles/'.$file;
                   11389:     }
                   11390:     if ($uri =~ m-^/res/-) {
                   11391: 	($udom,$uname) = 
1.807     albertel 11392: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11393: 	$file = $uri;
                   11394:     }
                   11395: 
                   11396:     if (!$udom || !$uname || !$file) {
                   11397: 	# unable to handle the uri
                   11398: 	return ();
                   11399:     }
1.956     raeburn  11400:     my $getpropath;
                   11401:     if ($file =~ /^userfiles\//) {
                   11402:         $getpropath = 1;
                   11403:     }
1.1136    raeburn  11404:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11405:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11406:         return ();
                   11407:     } else {
                   11408:         if (ref($listref) eq 'ARRAY') {
                   11409:             my @stats = split('&',$listref->[0]);
                   11410: 	    shift(@stats); #filename is first
                   11411: 	    return @stats;
                   11412:         }
1.712     albertel 11413:     }
                   11414:     return ();
                   11415: }
                   11416: 
1.1313    raeburn  11417: # --------------------------------------------------------- recursedirs
                   11418: # Recursive function to traverse either a specific user's Authoring Space
                   11419: # or corresponding Published Resource Space, and populate the hash ref:
                   11420: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11421: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11422: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11423: # files in Authoring Space.
                   11424: #
                   11425: # Inputs:
                   11426: #
                   11427: # $is_home - true if current server is home server for user's space
                   11428: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11429: # $docroot - Document root (i.e., /home/httpd/html
                   11430: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11431: # $relpath - Current path (relative to top level).
                   11432: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11433: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11434: #
                   11435: # Returns: nothing
                   11436: #
                   11437: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11438: #
                   11439: # Currently used by interface/londocs.pm to create linked select boxes for
                   11440: # directory and filename to import a Course "Author" resource into a course, and
                   11441: # also to create linked select boxes for Authoring Space and Directory to choose
                   11442: # save location for creation of a new "standard" problem from the Course Editor.
                   11443: #
                   11444: 
                   11445: sub recursedirs {
                   11446:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11447:     return unless (ref($dirhashref) eq 'HASH');
                   11448:     my $currpath = $docroot.$toppath;
                   11449:     if ($relpath) {
                   11450:         $currpath .= "/$relpath";
                   11451:     }
                   11452:     my $savefile;
                   11453:     if (ref($filehashref)) {
                   11454:         $savefile = 1;
                   11455:     }
                   11456:     if ($is_home) {
                   11457:         if (opendir(my $dirh,$currpath)) {
                   11458:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11459:                 next if ($item eq '');
                   11460:                 if (-d "$currpath/$item") {
                   11461:                     my $newpath;
                   11462:                     if ($relpath) {
                   11463:                         $newpath = "$relpath/$item";
                   11464:                     } else {
                   11465:                         $newpath = $item;
                   11466:                     }
                   11467:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11468:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11469:                 } elsif ($savefile) {
                   11470:                     if ($context eq 'priv') {
                   11471:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11472:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11473:                         }
                   11474:                     } else {
                   11475:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11476:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11477:                         }
                   11478:                     }
                   11479:                 }
                   11480:             }
                   11481:             closedir($dirh);
                   11482:         }
                   11483:     } else {
                   11484:         my ($dirlistref,$listerror) =
                   11485:             &dirlist($toppath.$relpath);
                   11486:         my @dir_lines;
                   11487:         my $dirptr=16384;
                   11488:         if (ref($dirlistref) eq 'ARRAY') {
                   11489:             foreach my $dir_line (sort
                   11490:                               {
                   11491:                                   my ($afile)=split('&',$a,2);
                   11492:                                   my ($bfile)=split('&',$b,2);
                   11493:                                   return (lc($afile) cmp lc($bfile));
                   11494:                               } (@{$dirlistref})) {
                   11495:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11496:                     split(/\&/,$dir_line,16);
                   11497:                 $item =~ s/\s+$//;
                   11498:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11499:                 if ($dirptr&$testdir) {
                   11500:                     my $newpath;
                   11501:                     if ($relpath) {
                   11502:                         $newpath = "$relpath/$item";
                   11503:                     } else {
                   11504:                         $relpath = '/';
                   11505:                         $newpath = $item;
                   11506:                     }
                   11507:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11508:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11509:                 } elsif ($savefile) {
                   11510:                     if ($context eq 'priv') {
                   11511:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11512:                             $filehashref->{$relpath}{$item} = 1;
                   11513:                         }
                   11514:                     } else {
                   11515:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11516:                             $filehashref->{$relpath}{$item} = 1;
                   11517:                         }
                   11518:                     }
                   11519:                 }
                   11520:             }
                   11521:         }
                   11522:     }
                   11523:     return;
                   11524: }
                   11525: 
1.26      www      11526: # -------------------------------------------------------- Value of a Condition
                   11527: 
1.713     albertel 11528: # gets the value of a specific preevaluated condition
                   11529: #    stored in the string  $env{user.state.<cid>}
                   11530: # or looks up a condition reference in the bighash and if if hasn't
                   11531: # already been evaluated recurses into docondval to get the value of
                   11532: # the condition, then memoizing it to 
                   11533: #   $env{user.state.<cid>.<condition>}
1.40      www      11534: sub directcondval {
                   11535:     my $number=shift;
1.620     albertel 11536:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11537: 	&Apache::lonuserstate::evalstate();
                   11538:     }
1.713     albertel 11539:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11540: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11541:     } elsif ($number =~ /^_/) {
                   11542: 	my $sub_condition;
                   11543: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11544: 		&GDBM_READER(),0640)) {
                   11545: 	    $sub_condition=$bighash{'conditions'.$number};
                   11546: 	    untie(%bighash);
                   11547: 	}
                   11548: 	my $value = &docondval($sub_condition);
1.949     raeburn  11549: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11550: 	return $value;
                   11551:     }
1.620     albertel 11552:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11553:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11554:     } else {
                   11555:        return 2;
                   11556:     }
                   11557: }
                   11558: 
1.713     albertel 11559: # get the collection of conditions for this resource
1.26      www      11560: sub condval {
                   11561:     my $condidx=shift;
1.54      www      11562:     my $allpathcond='';
1.713     albertel 11563:     foreach my $cond (split(/\|/,$condidx)) {
                   11564: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11565: 	    $allpathcond.=
                   11566: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11567: 	}
1.191     harris41 11568:     }
1.54      www      11569:     $allpathcond=~s/\|$//;
1.713     albertel 11570:     return &docondval($allpathcond);
                   11571: }
                   11572: 
                   11573: #evaluates an expression of conditions
                   11574: sub docondval {
                   11575:     my ($allpathcond) = @_;
                   11576:     my $result=0;
                   11577:     if ($env{'request.course.id'}
                   11578: 	&& defined($allpathcond)) {
                   11579: 	my $operand='|';
                   11580: 	my @stack;
                   11581: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11582: 	    if ($chunk eq '(') {
                   11583: 		push @stack,($operand,$result);
                   11584: 	    } elsif ($chunk eq ')') {
                   11585: 		my $before=pop @stack;
                   11586: 		if (pop @stack eq '&') {
                   11587: 		    $result=$result>$before?$before:$result;
                   11588: 		} else {
                   11589: 		    $result=$result>$before?$result:$before;
                   11590: 		}
                   11591: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11592: 		$operand=$chunk;
                   11593: 	    } else {
                   11594: 		my $new=directcondval($chunk);
                   11595: 		if ($operand eq '&') {
                   11596: 		    $result=$result>$new?$new:$result;
                   11597: 		} else {
                   11598: 		    $result=$result>$new?$result:$new;
                   11599: 		}
                   11600: 	    }
                   11601: 	}
1.26      www      11602:     }
                   11603:     return $result;
1.421     albertel 11604: }
                   11605: 
                   11606: # ---------------------------------------------------- Devalidate courseresdata
                   11607: 
                   11608: sub devalidatecourseresdata {
                   11609:     my ($coursenum,$coursedomain)=@_;
                   11610:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11611:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11612: }
                   11613: 
1.763     www      11614: 
1.200     www      11615: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11616: #
                   11617: #  Parameters:
                   11618: #      $coursenum    - Number of the course.
                   11619: #      $coursedomain - Domain at which the course was created.
                   11620: #  Returns:
                   11621: #     A hash of the course parameters along (I think) with timestamps
                   11622: #     and version info.
1.877     foxr     11623: 
1.624     albertel 11624: sub get_courseresdata {
                   11625:     my ($coursenum,$coursedomain)=@_;
1.200     www      11626:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11627:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11628:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11629:     my %dumpreply;
1.417     albertel 11630:     unless (defined($cached)) {
1.624     albertel 11631: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11632: 	$result=\%dumpreply;
1.251     albertel 11633: 	my ($tmp) = keys(%dumpreply);
                   11634: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11635: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11636: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11637: 	    return $tmp;
1.416     albertel 11638: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11639: 	    $result=undef;
1.599     albertel 11640: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11641: 	}
                   11642:     }
1.624     albertel 11643:     return $result;
                   11644: }
                   11645: 
1.633     albertel 11646: sub devalidateuserresdata {
                   11647:     my ($uname,$udom)=@_;
                   11648:     my $hashid="$udom:$uname";
                   11649:     &devalidate_cache_new('userres',$hashid);
                   11650: }
                   11651: 
1.624     albertel 11652: sub get_userresdata {
                   11653:     my ($uname,$udom)=@_;
                   11654:     #most student don\'t have any data set, check if there is some data
                   11655:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11656: 
                   11657:     my $hashid="$udom:$uname";
                   11658:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11659:     if (!defined($cached)) {
                   11660: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11661: 	$result=\%resourcedata;
                   11662: 	&do_cache_new('userres',$hashid,$result,600);
                   11663:     }
                   11664:     my ($tmp)=keys(%$result);
                   11665:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11666: 	return $result;
                   11667:     }
                   11668:     #error 2 occurs when the .db doesn't exist
                   11669:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11670:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11671: 	    &logthis("<font color=\"blue\">WARNING:".
                   11672: 		     " Trying to get resource data for ".
                   11673: 		     $uname." at ".$udom.": ".
                   11674: 		     $tmp."</font>");
                   11675:         }
1.624     albertel 11676:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11677: 	#&EXT_cache_set($udom,$uname);
                   11678: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11679: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11680:     }
                   11681:     return $tmp;
                   11682: }
1.879     foxr     11683: #----------------------------------------------- resdata - return resource data
                   11684: #  Purpose:
                   11685: #    Return resource data for either users or for a course.
                   11686: #  Parameters:
                   11687: #     $name      - Course/user name.
                   11688: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11689: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11690: #     $mapp      - decluttered URL of enclosing map  
                   11691: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11692: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11693: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11694: #     $courseid  - CourseID (first part of param identifier).
                   11695: #     $modifier  - Middle part of param identifier.
                   11696: #     $what      - Last part of param identifier.
1.879     foxr     11697: #     @which     - Array of names of resources desired.
                   11698: #  Returns:
                   11699: #     The value of the first reasource in @which that is found in the
                   11700: #     resource hash.
                   11701: #  Exceptional Conditions:
                   11702: #     If the $type passed in is not valid (not the string 'course' or 
                   11703: #     'user', an undefined  reference is returned.
                   11704: #     If none of the resources are found, an undef is returned
1.624     albertel 11705: sub resdata {
1.1301    raeburn  11706:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11707:         $modifier,$what,@which)=@_;
1.624     albertel 11708:     my $result;
                   11709:     if ($type eq 'course') {
                   11710: 	$result=&get_courseresdata($name,$domain);
                   11711:     } elsif ($type eq 'user') {
                   11712: 	$result=&get_userresdata($name,$domain);
                   11713:     }
                   11714:     if (!ref($result)) { return $result; }    
1.251     albertel 11715:     foreach my $item (@which) {
1.1301    raeburn  11716:         if ($item->[1] eq 'course') {
                   11717:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11718:                 unless ($$recursed) {
1.1302    raeburn  11719:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11720:                     $$recursed = 1;
                   11721:                 }
                   11722:                 foreach my $item (@${recurseup}) {
                   11723:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11724:                     last if (defined($result->{$norecursechk}));
                   11725:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11726:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11727:                 }
                   11728:             }
                   11729:         }
                   11730:         if (defined($result->{$item->[0]})) {
1.927     albertel 11731: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11732: 	}
1.250     albertel 11733:     }
1.291     albertel 11734:     return undef;
1.200     www      11735: }
                   11736: 
1.1360    raeburn  11737: sub get_domain_lti {
                   11738:     my ($cdom,$context) = @_;
                   11739:     my ($name,%lti);
                   11740:     if ($context eq 'consumer') {
                   11741:         $name = 'ltitools';
                   11742:     } elsif ($context eq 'provider') {
                   11743:         $name = 'lti';
                   11744:     } else {
                   11745:         return %lti;
                   11746:     }
                   11747:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11748:     if (defined($cached)) {
                   11749:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11750:             %lti = %{$result};
1.1298    raeburn  11751:         }
                   11752:     } else {
1.1360    raeburn  11753:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11754:         if (ref($domconfig{$name}) eq 'HASH') {
                   11755:             %lti = %{$domconfig{$name}};
                   11756:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11757:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11758:                 foreach my $id (keys(%lti)) {
                   11759:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11760:                         foreach my $item ('key','secret') {
1.1360    raeburn  11761:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11762:                         }
                   11763:                     }
                   11764:                 }
                   11765:             }
1.1298    raeburn  11766:         }
                   11767:         my $cachetime = 24*60*60;
1.1360    raeburn  11768:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11769:     }
1.1360    raeburn  11770:     return %lti;
1.1298    raeburn  11771: }
                   11772: 
1.1236    raeburn  11773: sub get_numsuppfiles {
                   11774:     my ($cnum,$cdom,$ignorecache)=@_;
                   11775:     my $hashid=$cnum.':'.$cdom;
                   11776:     my ($suppcount,$cached);
                   11777:     unless ($ignorecache) {
                   11778:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11779:     }
                   11780:     unless (defined($cached)) {
                   11781:         my $chome=&homeserver($cnum,$cdom);
                   11782:         unless ($chome eq 'no_host') {
1.1366    raeburn  11783:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11784:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11785:             ($suppcount,$supptools,$errors) =
                   11786:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11787:                                                          $supptools,$errors);
1.1236    raeburn  11788:         }
                   11789:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11790:     }
                   11791:     return $suppcount;
                   11792: }
                   11793: 
1.379     matthew  11794: #
                   11795: # EXT resource caching routines
                   11796: #
                   11797: 
1.1302    raeburn  11798: {
                   11799: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11800: #
                   11801: # The course for which we cache
                   11802: my $cachedmapkey='';
                   11803: # The cached recursive maps for this course
                   11804: my %cachedmaps=();
                   11805: # When this was last done
                   11806: my $cachedmaptime='';
                   11807: 
1.379     matthew  11808: sub clear_EXT_cache_status {
1.383     albertel 11809:     &delenv('cache.EXT.');
1.379     matthew  11810: }
                   11811: 
                   11812: sub EXT_cache_status {
                   11813:     my ($target_domain,$target_user) = @_;
1.383     albertel 11814:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11815:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11816:         # We know already the user has no data
                   11817:         return 1;
                   11818:     } else {
                   11819:         return 0;
                   11820:     }
                   11821: }
                   11822: 
                   11823: sub EXT_cache_set {
                   11824:     my ($target_domain,$target_user) = @_;
1.383     albertel 11825:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11826:     #&appenv({$cachename => time});
1.379     matthew  11827: }
                   11828: 
1.28      www      11829: # --------------------------------------------------------- Value of a Variable
1.58      www      11830: sub EXT {
1.715     albertel 11831: 
1.1228    raeburn  11832:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11833:     unless ($varname) { return ''; }
1.218     albertel 11834:     #get real user name/domain, courseid and symb
                   11835:     my $courseid;
1.359     albertel 11836:     my $publicuser;
1.427     www      11837:     if ($symbparm) {
                   11838: 	$symbparm=&get_symb_from_alias($symbparm);
                   11839:     }
1.218     albertel 11840:     if (!($uname && $udom)) {
1.790     albertel 11841:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11842:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11843:     } else {
1.620     albertel 11844: 	$courseid=$env{'request.course.id'};
1.218     albertel 11845:     }
1.48      www      11846:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11847:     my $rest;
1.320     albertel 11848:     if (defined($therest[0])) {
1.48      www      11849:        $rest=join('.',@therest);
                   11850:     } else {
                   11851:        $rest='';
                   11852:     }
1.320     albertel 11853: 
1.57      www      11854:     my $qualifierrest=$qualifier;
                   11855:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11856:     my $spacequalifierrest=$space;
                   11857:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11858:     if ($realm eq 'user') {
1.48      www      11859: # --------------------------------------------------------------- user.resource
                   11860: 	if ($space eq 'resource') {
1.651     albertel 11861: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11862: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11863: 		 &&
1.744     albertel 11864: 		 ($symbparm eq &symbread()) ) {	
                   11865: 		# if we are in the middle of processing the resource the
                   11866: 		# get the value we are planning on committing
                   11867:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11868:                     return $Apache::lonhomework::results{$qualifierrest};
                   11869:                 } else {
                   11870:                     return $Apache::lonhomework::history{$qualifierrest};
                   11871:                 }
1.335     albertel 11872: 	    } else {
1.359     albertel 11873: 		my %restored;
1.620     albertel 11874: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11875: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11876: 		} else {
                   11877: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11878: 		}
1.335     albertel 11879: 		return $restored{$qualifierrest};
                   11880: 	    }
1.48      www      11881: # ----------------------------------------------------------------- user.access
                   11882:         } elsif ($space eq 'access') {
1.218     albertel 11883: 	    # FIXME - not supporting calls for a specific user
1.48      www      11884:             return &allowed($qualifier,$rest);
                   11885: # ------------------------------------------ user.preferences, user.environment
                   11886:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11887: 	    if (($uname eq $env{'user.name'}) &&
                   11888: 		($udom eq $env{'user.domain'})) {
                   11889: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11890: 	    } else {
1.359     albertel 11891: 		my %returnhash;
                   11892: 		if (!$publicuser) {
                   11893: 		    %returnhash=&userenvironment($udom,$uname,
                   11894: 						 $qualifierrest);
                   11895: 		}
1.218     albertel 11896: 		return $returnhash{$qualifierrest};
                   11897: 	    }
1.48      www      11898: # ----------------------------------------------------------------- user.course
                   11899:         } elsif ($space eq 'course') {
1.218     albertel 11900: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11901:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11902: # ------------------------------------------------------------------- user.role
                   11903:         } elsif ($space eq 'role') {
1.218     albertel 11904: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11905:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11906:             if ($qualifier eq 'value') {
                   11907: 		return $role;
                   11908:             } elsif ($qualifier eq 'extent') {
                   11909:                 return $where;
                   11910:             }
                   11911: # ----------------------------------------------------------------- user.domain
                   11912:         } elsif ($space eq 'domain') {
1.218     albertel 11913:             return $udom;
1.48      www      11914: # ------------------------------------------------------------------- user.name
                   11915:         } elsif ($space eq 'name') {
1.218     albertel 11916:             return $uname;
1.48      www      11917: # ---------------------------------------------------- Any other user namespace
1.29      www      11918:         } else {
1.359     albertel 11919: 	    my %reply;
                   11920: 	    if (!$publicuser) {
                   11921: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11922: 	    }
                   11923: 	    return $reply{$qualifierrest};
1.48      www      11924:         }
1.236     www      11925:     } elsif ($realm eq 'query') {
                   11926: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11927:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11928: 						[$spacequalifierrest]);
1.620     albertel 11929: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11930:    } elsif ($realm eq 'request') {
1.48      www      11931: # ------------------------------------------------------------- request.browser
                   11932:         if ($space eq 'browser') {
1.1145    bisitz   11933:             return $env{'browser.'.$qualifier};
1.57      www      11934: # ------------------------------------------------------------ request.filename
                   11935:         } else {
1.620     albertel 11936:             return $env{'request.'.$spacequalifierrest};
1.29      www      11937:         }
1.28      www      11938:     } elsif ($realm eq 'course') {
1.48      www      11939: # ---------------------------------------------------------- course.description
1.620     albertel 11940:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11941:     } elsif ($realm eq 'resource') {
1.165     www      11942: 
1.620     albertel 11943: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11944: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11945: 	}
1.693     albertel 11946: 
1.1232    raeburn  11947:         if ($qualifier eq '') {
                   11948: 	    if ($space eq 'title') {
                   11949: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11950: 	        return &gettitle($symbparm);
                   11951: 	    }
1.693     albertel 11952: 	
1.1232    raeburn  11953: 	    if ($space eq 'map') {
                   11954: 	        my ($map) = &decode_symb($symbparm);
                   11955: 	        return &symbread($map);
                   11956: 	    }
                   11957:             if ($space eq 'maptitle') {
                   11958:                 my ($map) = &decode_symb($symbparm);
                   11959:                 return &gettitle($map);
                   11960:             }
                   11961: 	    if ($space eq 'filename') {
                   11962: 	        if ($symbparm) {
                   11963: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11964: 	        }
                   11965: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11966: 	    }
1.1232    raeburn  11967: 
1.1233    raeburn  11968:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11969:                 if ($space eq 'visibleparts') {
                   11970:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11971:                     my $item;
                   11972:                     if (ref($navmap)) {
                   11973:                         my $res = $navmap->getBySymb($symbparm);
                   11974:                         my $parts = $res->parts();
                   11975:                         if (ref($parts) eq 'ARRAY') {
                   11976:                             $item = join(',',@{$parts});
                   11977:                         }
                   11978:                         undef($navmap);
1.1232    raeburn  11979:                     }
1.1233    raeburn  11980:                     return $item;
1.1232    raeburn  11981:                 }
                   11982:             }
                   11983:         }
1.693     albertel 11984: 
1.1301    raeburn  11985: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11986: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11987:         if (($courseid eq '') && ($cid)) {
                   11988:             $courseid = $cid;
                   11989:         }
                   11990: 	if (($symbparm && $courseid) && 
                   11991: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11992: 
1.218     albertel 11993: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11994: 
1.60      www      11995: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11996: 	    my $symbp=$symbparm;
1.1301    raeburn  11997: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11998: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11999:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12000: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12001: 	    if (($env{'user.name'} eq $uname) &&
                   12002: 		($env{'user.domain'} eq $udom)) {
                   12003: 		$section=$env{'request.course.sec'};
1.733     raeburn  12004:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12005:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12006: 	    } else {
1.539     albertel 12007: 		if (! defined($usection)) {
1.551     albertel 12008: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12009: 		} else {
                   12010: 		    $section = $usection;
                   12011: 		}
1.733     raeburn  12012:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12013: 	    }
                   12014: 
                   12015: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12016: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12017:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12018: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12019: 
1.593     albertel 12020: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12021: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12022:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12023: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12024: 
1.60      www      12025: # ----------------------------------------------------------- first, check user
1.624     albertel 12026: 
1.1301    raeburn  12027: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12028:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12029: 				       ([$courselevelr,'resource'],
                   12030: 					[$courselevelm,'map'     ],
1.1301    raeburn  12031:                                         [$courseleveli,'map'     ],
1.927     albertel 12032: 					[$courselevel, 'course'  ]));
1.931     albertel 12033: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12034: 
1.594     albertel 12035: # ------------------------------------------------ second, check some of course
1.684     raeburn  12036:             my $coursereply;
1.691     raeburn  12037:             if (@groups > 0) {
                   12038:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12039:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12040:                                        $mapp,\$recursed,\@recurseup);
                   12041:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12042:             }
1.96      www      12043: 
1.684     raeburn  12044: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12045: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12046: 				  'course',$mapp,\$recursed,\@recurseup,
                   12047:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12048: 				  ([$seclevelr,   'resource'],
                   12049: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12050:                                    [$secleveli,   'map'     ],
1.927     albertel 12051: 				   [$seclevel,    'course'  ],
                   12052: 				   [$courselevelr,'resource']));
                   12053: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12054: 
1.60      www      12055: # ------------------------------------------------------ third, check map parms
1.218     albertel 12056: 	    my %parmhash=();
                   12057: 	    my $thisparm='';
                   12058: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12059: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12060: 		    &GDBM_READER(),0640)) {
1.218     albertel 12061: 		$thisparm=$parmhash{$symbparm};
                   12062: 		untie(%parmhash);
                   12063: 	    }
1.927     albertel 12064: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12065: 	}
1.594     albertel 12066: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12067:  
                   12068:         my $what = $spacequalifierrest;
                   12069: 	$what=~s/\./\_/;
1.282     albertel 12070: 	my $filename;
                   12071: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12072: 	if ($symbparm) {
1.409     www      12073: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12074: 	} else {
1.620     albertel 12075: 	    $filename=$env{'request.filename'};
1.282     albertel 12076: 	}
1.1362    raeburn  12077:         my $toolsymb;
                   12078:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12079:             $toolsymb = $symbparm;
                   12080:         }
                   12081: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12082: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12083: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12084: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12085: 
1.1301    raeburn  12086: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12087: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12088: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12089: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12090: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12091: 				     'course',$mapp,\$recursed,\@recurseup,
                   12092:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12093: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12094:                                       [$courseleveli,'map'   ],
1.927     albertel 12095: 				      [$courselevel, 'course']));
                   12096: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12097: 	}
1.145     www      12098: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12099: 	unless ($space eq '0') {
1.336     albertel 12100: 	    my @parts=split(/_/,$space);
                   12101: 	    my $id=pop(@parts);
                   12102: 	    my $part=join('_',@parts);
                   12103: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12104: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12105: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12106: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12107: 	}
1.395     albertel 12108: 	if ($recurse) { return undef; }
1.1362    raeburn  12109: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12110: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12111: # ---------------------------------------------------- Any other user namespace
                   12112:     } elsif ($realm eq 'environment') {
                   12113: # ----------------------------------------------------------------- environment
1.620     albertel 12114: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12115: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12116: 	} else {
1.770     albertel 12117: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12118: 		return '';
                   12119: 	    }
1.219     albertel 12120: 	    my %returnhash=&userenvironment($udom,$uname,
                   12121: 					    $spacequalifierrest);
                   12122: 	    return $returnhash{$spacequalifierrest};
                   12123: 	}
1.28      www      12124:     } elsif ($realm eq 'system') {
1.48      www      12125: # ----------------------------------------------------------------- system.time
                   12126: 	if ($space eq 'time') {
                   12127: 	    return time;
                   12128:         }
1.696     albertel 12129:     } elsif ($realm eq 'server') {
                   12130: # ----------------------------------------------------------------- system.time
                   12131: 	if ($space eq 'name') {
                   12132: 	    return $ENV{'SERVER_NAME'};
                   12133:         }
1.28      www      12134:     }
1.48      www      12135:     return '';
1.61      www      12136: }
                   12137: 
1.927     albertel 12138: sub get_reply {
                   12139:     my ($reply_value) = @_;
1.940     raeburn  12140:     if (ref($reply_value) eq 'ARRAY') {
                   12141:         if (wantarray) {
                   12142: 	    return @$reply_value;
                   12143:         }
                   12144:         return $reply_value->[0];
                   12145:     } else {
                   12146:         return $reply_value;
1.927     albertel 12147:     }
                   12148: }
                   12149: 
1.691     raeburn  12150: sub check_group_parms {
1.1301    raeburn  12151:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12152:         $recursed,$recurseupref) = @_;
                   12153:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12154:                   [$what,'course']);
                   12155:     my $coursereply;
1.691     raeburn  12156:     foreach my $group (@{$groups}) {
1.1301    raeburn  12157:         my @groupitems = ();
1.691     raeburn  12158:         foreach my $level (@levels) {
1.927     albertel 12159:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12160:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12161:         }
1.1301    raeburn  12162:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12163:                                    $env{'course.'.$courseid.'.domain'},
                   12164:                                    'course',$mapp,$recursed,$recurseupref,
                   12165:                                    $courseid,'.['.$group.'].',$what,
                   12166:                                    @groupitems);
                   12167:         last if (defined($coursereply));
1.691     raeburn  12168:     }
                   12169:     return $coursereply;
                   12170: }
                   12171: 
1.1301    raeburn  12172: sub get_map_hierarchy {
1.1302    raeburn  12173:     my ($mapname,$courseid) = @_;
                   12174:     my @recurseup = ();
1.1301    raeburn  12175:     if ($mapname) {
1.1302    raeburn  12176:         if (($cachedmapkey eq $courseid) &&
                   12177:             (abs($cachedmaptime-time)<5)) {
                   12178:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12179:                 return @{$cachedmaps{$mapname}};
                   12180:             }
                   12181:         }
1.1301    raeburn  12182:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12183:         if (ref($navmap)) {
                   12184:             @recurseup = $navmap->recurseup_maps($mapname);
                   12185:             undef($navmap);
1.1302    raeburn  12186:             $cachedmaps{$mapname} = \@recurseup;
                   12187:             $cachedmaptime=time;
                   12188:             $cachedmapkey=$courseid;
1.1301    raeburn  12189:         }
                   12190:     }
                   12191:     return @recurseup;
                   12192: }
                   12193: 
1.1302    raeburn  12194: }
                   12195: 
1.691     raeburn  12196: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12197:     my ($courseid,@groups) = @_;
                   12198:     @groups = sort(@groups);
1.691     raeburn  12199:     return @groups;
                   12200: }
                   12201: 
1.395     albertel 12202: sub packages_tab_default {
1.1362    raeburn  12203:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12204:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12205: 
                   12206:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12207:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12208: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12209: 	if ($pack_type eq 'default') {
                   12210: 	    $do_default=1;
                   12211: 	} elsif ($pack_type eq 'extension') {
                   12212: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12213: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12214: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12215: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12216: 	}
                   12217:     }
                   12218:     # first look for a package that matches the requested part id
                   12219:     foreach my $package (@specifics) {
                   12220: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12221: 	next if ($pack_part ne $part);
                   12222: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12223: 	    return $packagetab{"$pack_type&$name&default"};
                   12224: 	}
                   12225:     }
                   12226:     # look for any possible matching non extension_ package
                   12227:     foreach my $package (@specifics) {
                   12228: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12229: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12230: 	    return $packagetab{"$pack_type&$name&default"};
                   12231: 	}
1.585     albertel 12232: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12233: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12234: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12235: 	}
                   12236:     }
1.738     albertel 12237:     # look for any posible extension_ match
                   12238:     foreach my $package (@extension) {
                   12239: 	my ($package,$pack_type)=@{$package};
                   12240: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12241: 	    return $packagetab{"$pack_type&$name&default"};
                   12242: 	}
                   12243: 	if (defined($packagetab{$package."&$name&default"})) {
                   12244: 	    return $packagetab{$package."&$name&default"};
                   12245: 	}
                   12246:     }
                   12247:     # look for a global default setting
                   12248:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12249: 	return $packagetab{"default&$name&default"};
                   12250:     }
1.395     albertel 12251:     return undef;
                   12252: }
                   12253: 
1.334     albertel 12254: sub add_prefix_and_part {
                   12255:     my ($prefix,$part)=@_;
                   12256:     my $keyroot;
                   12257:     if (defined($prefix) && $prefix !~ /^__/) {
                   12258: 	# prefix that has a part already
                   12259: 	$keyroot=$prefix;
                   12260:     } elsif (defined($prefix)) {
                   12261: 	# prefix that is missing a part
                   12262: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12263:     } else {
                   12264: 	# no prefix at all
                   12265: 	if (defined($part)) { $keyroot='_'.$part; }
                   12266:     }
                   12267:     return $keyroot;
                   12268: }
                   12269: 
1.71      www      12270: # ---------------------------------------------------------------- Get metadata
                   12271: 
1.599     albertel 12272: my %metaentry;
1.1070    www      12273: my %importedpartids;
1.1369    raeburn  12274: my %importedrespids;
1.71      www      12275: sub metadata {
1.1362    raeburn  12276:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12277:     $uri=&declutter($uri);
1.288     albertel 12278:     # if it is a non metadata possible uri return quickly
1.529     albertel 12279:     if (($uri eq '') || 
                   12280: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12281: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12282:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12283: 	return undef;
                   12284:     }
1.1261    raeburn  12285:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12286: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12287: 	return undef;
1.288     albertel 12288:     }
1.73      www      12289:     my $filename=$uri;
                   12290:     $uri=~s/\.meta$//;
1.172     www      12291: #
                   12292: # Is the metadata already cached?
1.177     www      12293: # Look at timestamp of caching
1.172     www      12294: # Everything is cached by the main uri, libraries are never directly cached
                   12295: #
1.428     albertel 12296:     if (!defined($liburi)) {
1.599     albertel 12297: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12298: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12299:     }
1.1362    raeburn  12300: 
                   12301: #
                   12302: # If the uri is for an external tool the file from
                   12303: # which metadata should be retrieved depends on whether
                   12304: # the tool had been configured to be gradable (set in the Course
                   12305: # Editor or Resource Editor).
                   12306: #
                   12307: # If a valid symb has been included as the third arg in the call
                   12308: # to &metadata() that can be used to retrieve the value of
                   12309: # parameter_0_gradable set for the resource, and included in the
                   12310: # uploaded map containing the tool. The value is retrieved via
                   12311: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12312: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12313: # is retrieved via &get().
                   12314: #
                   12315: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12316: # hiddenresource and encrypturl (during course initialization)
                   12317: # the map-level parameter for resource.0.gradable included in the 
                   12318: # uploaded map containing the tool will not yet have been stored
                   12319: # in the user_course_parms.db file for the user's session, so in 
                   12320: # this case fall back to retrieving gradable status from the
                   12321: # exttool_$marker.db file.
1.1362    raeburn  12322: #
                   12323: # In order to avoid an infinite loop, &metadata() will return
                   12324: # before a call to &EXT(), if the uri is for an external tool
                   12325: # and the $what for which metadata is being requested is
                   12326: # parameter_0_gradable or 0_gradable.
                   12327: #
                   12328: 
                   12329:     if ($uri =~ /ext\.tool$/) {
                   12330:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12331:             return;
                   12332:         } else {
                   12333:             my ($checked,$use_passback);
                   12334:             if ($toolsymb ne '') {
                   12335:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12336:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12337:                     $checked = 1;
                   12338:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12339:                         $use_passback = 1;
                   12340:                     }
                   12341:                 }
                   12342:             }
                   12343:             unless ($checked) {
                   12344:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12345:                 $marker=~s/\D//g;
1.1363    raeburn  12346:                 if ($marker) {
1.1362    raeburn  12347:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12348:                     $use_passback = $toolsettings{'gradable'};
                   12349:                 }
                   12350:             }
                   12351:             if ($use_passback) {
                   12352:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12353:             } else {
                   12354:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12355:             }
                   12356:         }
                   12357:     }
                   12358: 
1.428     albertel 12359:     {
1.1069    www      12360: # Imported parts would go here
1.1369    raeburn  12361:         my @origfiletagids=();
1.1069    www      12362:         my $importedparts=0;
1.1369    raeburn  12363: 
                   12364: # Imported responseids would go here
                   12365:         my $importedresponses=0;
1.172     www      12366: #
                   12367: # Is this a recursive call for a library?
                   12368: #
1.599     albertel 12369: #	if (! exists($metacache{$uri})) {
                   12370: #	    $metacache{$uri}={};
                   12371: #	}
1.924     albertel 12372: 	my $cachetime = 60*60;
1.171     www      12373:         if ($liburi) {
                   12374: 	    $liburi=&declutter($liburi);
                   12375:             $filename=$liburi;
1.401     bowersj2 12376:         } else {
1.599     albertel 12377: 	    &devalidate_cache_new('meta',$uri);
                   12378: 	    undef(%metaentry);
1.401     bowersj2 12379: 	}
1.140     www      12380:         my %metathesekeys=();
1.73      www      12381:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12382: 	my $metastring;
1.1140    www      12383: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12384: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12385: 	    $metastring = 
1.929     albertel 12386: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12387: 					  ('grade_target' => 'meta'));
                   12388: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12389: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12390:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12391: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12392: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12393: 	    $metastring=&getfile($file);
1.489     albertel 12394: 	}
1.208     albertel 12395:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12396:         my $token;
1.140     www      12397:         undef %metathesekeys;
1.71      www      12398:         while ($token=$parser->get_token) {
1.339     albertel 12399: 	    if ($token->[0] eq 'S') {
                   12400: 		if (defined($token->[2]->{'package'})) {
1.172     www      12401: #
                   12402: # This is a package - get package info
                   12403: #
1.339     albertel 12404: 		    my $package=$token->[2]->{'package'};
                   12405: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12406: 		    if (defined($token->[2]->{'id'})) { 
                   12407: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12408: 		    }
1.599     albertel 12409: 		    if ($metaentry{':packages'}) {
                   12410: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12411: 		    } else {
1.599     albertel 12412: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12413: 		    }
1.736     albertel 12414: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12415: 			my $part=$keyroot;
                   12416: 			$part=~s/^\_//;
1.736     albertel 12417: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12418: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12419: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12420: 			    # ignore package.tab specified default values
                   12421:                             # here &package_tab_default() will fetch those
                   12422: 			    if ($subp eq 'default') { next; }
1.736     albertel 12423: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12424: 			    my $unikey;
                   12425: 			    if ($pack =~ /_0$/) {
                   12426: 				$unikey='parameter_0_'.$name;
                   12427: 				$part=0;
                   12428: 			    } else {
                   12429: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12430: 			    }
1.339     albertel 12431: 			    if ($subp eq 'display') {
                   12432: 				$value.=' [Part: '.$part.']';
                   12433: 			    }
1.599     albertel 12434: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12435: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12436: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12437: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12438: 			    }
1.599     albertel 12439: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12440: 				$metaentry{':'.$unikey}=
                   12441: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12442: 			    }
1.339     albertel 12443: 			}
                   12444: 		    }
                   12445: 		} else {
1.172     www      12446: #
                   12447: # This is not a package - some other kind of start tag
1.339     albertel 12448: #
                   12449: 		    my $entry=$token->[1];
1.1068    www      12450: 		    my $unikey='';
1.175     www      12451: 
1.339     albertel 12452: 		    if ($entry eq 'import') {
1.175     www      12453: #
                   12454: # Importing a library here
1.339     albertel 12455: #
1.1067    www      12456:                         my $location=$parser->get_text('/import');
                   12457:                         my $dir=$filename;
                   12458:                         $dir=~s|[^/]*$||;
                   12459:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12460: 
                   12461:                         my $importid=$token->[2]->{'id'};
1.1068    www      12462:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12463: #
                   12464: # Check metadata for imported file to
                   12465: # see if it contained response items
                   12466: #
1.1372    raeburn  12467:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12468:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12469:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12470:                                                            $depthcount+1));
                   12471:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12472:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12473:                                                              undef,$depthcount+1);
                   12474:                             if ($libresponseorder ne '') {
                   12475:                                 if ($#origfiletagids<0) {
                   12476:                                     undef(%importedrespids);
                   12477:                                     undef(%importedpartids);
                   12478:                                 }
1.1373    raeburn  12479:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12480:                                 if (@respids) {
                   12481:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12482:                                 }
                   12483:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12484:                                     $importedresponses = 1;
1.1369    raeburn  12485: # We need to get the original file and the imported file to get the response order correct
                   12486: # Load and inspect original file
1.1372    raeburn  12487:                                     if ($#origfiletagids<0) {
                   12488:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12489:                                         $origfile=&getfile($origfilelocation);
                   12490:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12491:                                     }
1.1369    raeburn  12492:                                 }
                   12493:                             }
                   12494:                         }
1.1370    raeburn  12495: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12496: # hash populated for imported library file
                   12497:                         %metaentry = %currmetaentry;
                   12498:                         undef(%currmetaentry);
1.1374    raeburn  12499:                         if ($importmode eq 'part') {
1.1068    www      12500: # Import as part(s)
1.1069    www      12501:                            $importedparts=1;
                   12502: # We need to get the original file and the imported file to get the part order correct
                   12503: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12504: # Load and inspect original file if we didn't do that already
                   12505:                            if ($#origfiletagids<0) {
                   12506:                                undef(%importedrespids);
                   12507:                                undef(%importedpartids);
                   12508:                                if ($origfile eq '') {
                   12509:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12510:                                    $origfile=&getfile($origfilelocation);
                   12511:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12512:                                }
1.1070    www      12513:                            }
1.1372    raeburn  12514:                            my @impfilepartids;
                   12515: # If <partorder> tag is included in metadata for the imported file
                   12516: # get the parts in the imported file from that.
                   12517:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12518:                                %currmetaentry = %metaentry;
                   12519:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12520:                                                             $depthcount+1);
                   12521:                                %metaentry = %currmetaentry;
                   12522:                                undef(%currmetaentry);
                   12523:                                if ($libpartorder ne '') {
                   12524:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12525:                                }
                   12526:                            } else {
                   12527: # If no <partorder> tag available, load and inspect imported file
                   12528:                                my $impfile=&getfile($location);
                   12529:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12530:                            }
1.1069    www      12531:                            if ($#impfilepartids>=0) {
                   12532: # This problem had parts
1.1070    www      12533:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12534:                            } else {
                   12535: # Importing by turning a single problem into a problem part
                   12536: # It gets the import-tags ID as part-ID
                   12537:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12538:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12539:                            }
1.1068    www      12540:                         } else {
1.1374    raeburn  12541: # Import as problem or as normal import
                   12542:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12543:                             unless ($importmode eq 'problem') {
1.1068    www      12544: # Normal import
1.1374    raeburn  12545:                                 if (defined($token->[2]->{'id'})) {
                   12546:                                     $unikey.='_'.$token->[2]->{'id'};
                   12547:                                 }
                   12548:                             }
                   12549: # Check metadata for imported file to
                   12550: # see if it contained parts
                   12551:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12552:                                 %currmetaentry = %metaentry;
                   12553:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12554:                                                              $depthcount+1);
                   12555:                                 %metaentry = %currmetaentry;
                   12556:                                 undef(%currmetaentry);
                   12557:                                 if ($libpartorder ne '') {
                   12558:                                     $importedparts = 1;
                   12559:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12560:                                 }
                   12561:                             }
1.1067    www      12562:                         }
1.339     albertel 12563: 			if ($depthcount<20) {
1.736     albertel 12564: 			    my $metadata = 
1.1362    raeburn  12565: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12566: 					  $depthcount+1);
                   12567: 			    foreach my $meta (split(',',$metadata)) {
                   12568: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12569: 				$metathesekeys{$meta}=1;
1.339     albertel 12570: 			    }
1.1068    www      12571:                         }
1.1067    www      12572: 		    } else {
                   12573: #
                   12574: # Not importing, some other kind of non-package, non-library start tag
                   12575: # 
                   12576:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12577:                         if (defined($token->[2]->{'id'})) {
                   12578:                             $unikey.='_'.$token->[2]->{'id'};
                   12579:                         }
1.339     albertel 12580: 			if (defined($token->[2]->{'name'})) { 
                   12581: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12582: 			}
                   12583: 			$metathesekeys{$unikey}=1;
1.736     albertel 12584: 			foreach my $param (@{$token->[3]}) {
                   12585: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12586: 				$token->[2]->{$param};
1.339     albertel 12587: 			}
                   12588: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12589: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12590: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12591: 		 # only ws inside the tag, and not in default, so use default
                   12592: 		 # as value
1.599     albertel 12593: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12594: 			} elsif ( $internaltext =~ /\S/ ) {
                   12595: 		  # something interesting inside the tag
                   12596: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12597: 			} else {
1.908     albertel 12598: 		  # no interesting values, don't set a default
1.339     albertel 12599: 			}
1.172     www      12600: # end of not-a-package not-a-library import
1.339     albertel 12601: 		    }
1.172     www      12602: # end of not-a-package start tag
1.339     albertel 12603: 		}
1.172     www      12604: # the next is the end of "start tag"
1.339     albertel 12605: 	    }
                   12606: 	}
1.483     albertel 12607: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12608: 	$extension = lc($extension);
                   12609: 	if ($extension eq 'htm') { $extension='html'; }
                   12610: 
1.737     albertel 12611: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12612: 	    #no specific packages #how's our extension
                   12613: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12614: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12615: 					 \%metathesekeys);
                   12616: 	}
1.883     albertel 12617: 
                   12618: 	if (!exists($metaentry{':packages'})
                   12619: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12620: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12621: 		#no specific packages well let's get default then
                   12622: 		if ($key!~/^default&/) { next; }
1.488     albertel 12623: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12624: 					     \%metathesekeys);
                   12625: 	    }
                   12626: 	}
1.338     www      12627: # are there custom rights to evaluate
1.599     albertel 12628: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12629: 
1.338     www      12630:     #
                   12631:     # Importing a rights file here
1.339     albertel 12632:     #
                   12633: 	    unless ($depthcount) {
1.599     albertel 12634: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12635: 		my $dir=$filename;
                   12636: 		$dir=~s|[^/]*$||;
                   12637: 		$location=&filelocation($dir,$location);
1.736     albertel 12638: 		my $rights_metadata =
1.1362    raeburn  12639: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12640: 			      $depthcount+1);
                   12641: 		foreach my $rights (split(',',$rights_metadata)) {
                   12642: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12643: 		    $metathesekeys{$rights}=1;
1.339     albertel 12644: 		}
                   12645: 	    }
                   12646: 	}
1.737     albertel 12647: 	# uniqifiy package listing
                   12648: 	my %seen;
                   12649: 	my @uniq_packages =
                   12650: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12651: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12652: 
1.1369    raeburn  12653:         if (($importedresponses) || ($importedparts)) {
                   12654:             if ($importedparts) {
1.1070    www      12655: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12656:                 $metaentry{':partorder'}='';
                   12657:                 $metathesekeys{'partorder'}=1;
                   12658:             }
                   12659:             if ($importedresponses) {
                   12660: # We had imported responses and need to rebuil responseorder
                   12661:                 $metaentry{':responseorder'}='';
                   12662:                 $metathesekeys{'responseorder'}=1;
                   12663:             }
                   12664:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12665:                 my $origid = $origfiletagids[$index+1];
                   12666:                 if ($origfiletagids[$index] eq 'part') {
                   12667: # Original part, part of the problem
                   12668:                     if ($importedparts) {
                   12669:                         $metaentry{':partorder'}.=','.$origid;
                   12670:                     }
                   12671:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12672:                     if ($importedparts) {
                   12673: # We have imported parts at this position
1.1373    raeburn  12674:                         if ($importedpartids{$origid} ne '') {
                   12675:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12676:                         }
1.1369    raeburn  12677:                     }
                   12678:                     if ($importedresponses) {
                   12679: # We have imported responses at this position
1.1373    raeburn  12680:                         if ($importedrespids{$origid} ne '') {
                   12681:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12682:                         }
                   12683:                     }
                   12684:                 } else {
                   12685: # Original response item, part of the problem
                   12686:                     if ($importedresponses) {
                   12687:                         $metaentry{':responseorder'}.=','.$origid;
                   12688:                     }
                   12689:                 }
                   12690:             }
                   12691:             if ($importedparts) {
                   12692:                 $metaentry{':partorder'}=~s/^\,//;
                   12693:             }
                   12694:             if ($importedresponses) {
                   12695:                 $metaentry{':responseorder'}=~s/^\,//;
                   12696:             }
1.1070    www      12697:         }
1.737     albertel 12698: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12699: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12700: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12701:         unless ($liburi) {
                   12702: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12703:         }
1.177     www      12704: # this is the end of "was not already recently cached
1.71      www      12705:     }
1.599     albertel 12706:     return $metaentry{':'.$what};
1.261     albertel 12707: }
                   12708: 
1.488     albertel 12709: sub metadata_create_package_def {
1.483     albertel 12710:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12711:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12712:     if ($subp eq 'default') { next; }
                   12713:     
1.599     albertel 12714:     if (defined($metaentry{':packages'})) {
                   12715: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12716:     } else {
1.599     albertel 12717: 	$metaentry{':packages'}=$package;
1.483     albertel 12718:     }
                   12719:     my $value=$packagetab{$key};
                   12720:     my $unikey;
                   12721:     $unikey='parameter_0_'.$name;
1.599     albertel 12722:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12723:     $$metathesekeys{$unikey}=1;
1.599     albertel 12724:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12725: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12726:     }
1.599     albertel 12727:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12728: 	$metaentry{':'.$unikey}=
                   12729: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12730:     }
                   12731: }
                   12732: 
1.261     albertel 12733: sub metadata_generate_part0 {
                   12734:     my ($metadata,$metacache,$uri) = @_;
                   12735:     my %allnames;
1.737     albertel 12736:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12737: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12738: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12739: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12740: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12741: 	    $allnames{$name}=$part;
                   12742: 	  }
                   12743: 	}
                   12744:     }
                   12745:     foreach my $name (keys(%allnames)) {
                   12746:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12747:       my $key=":parameter_0_$name";
1.261     albertel 12748:       $$metacache{"$key.part"}='0';
                   12749:       $$metacache{"$key.name"}=$name;
1.428     albertel 12750:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12751: 					   $allnames{$name}.'_'.$name.
                   12752: 					   '.type'};
1.428     albertel 12753:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12754: 			     '.display'};
1.644     www      12755:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12756:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12757:       $$metacache{"$key.display"}=$olddis;
                   12758:     }
1.71      www      12759: }
                   12760: 
1.764     albertel 12761: # ------------------------------------------------------ Devalidate title cache
                   12762: 
                   12763: sub devalidate_title_cache {
                   12764:     my ($url)=@_;
                   12765:     if (!$env{'request.course.id'}) { return; }
                   12766:     my $symb=&symbread($url);
                   12767:     if (!$symb) { return; }
                   12768:     my $key=$env{'request.course.id'}."\0".$symb;
                   12769:     &devalidate_cache_new('title',$key);
                   12770: }
                   12771: 
1.1014    droeschl 12772: # ------------------------------------------------- Get the title of a course
                   12773: 
                   12774: sub current_course_title {
                   12775:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12776: }
1.301     www      12777: # ------------------------------------------------- Get the title of a resource
                   12778: 
                   12779: sub gettitle {
                   12780:     my $urlsymb=shift;
                   12781:     my $symb=&symbread($urlsymb);
1.534     albertel 12782:     if ($symb) {
1.620     albertel 12783: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12784: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12785: 	if (defined($cached)) { 
                   12786: 	    return $result;
                   12787: 	}
1.534     albertel 12788: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12789: 	my $title='';
1.907     albertel 12790: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12791: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12792: 	} else {
                   12793: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12794: 		    &GDBM_READER(),0640)) {
                   12795: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12796: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12797: 		untie(%bighash);
                   12798: 	    }
1.534     albertel 12799: 	}
                   12800: 	$title=~s/\&colon\;/\:/gs;
                   12801: 	if ($title) {
1.1159    www      12802: # Remember both $symb and $title for dynamic metadata
                   12803:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12804:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12805: # Cache this title and then return it
1.599     albertel 12806: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12807: 	}
                   12808: 	$urlsymb=$url;
                   12809:     }
                   12810:     my $title=&metadata($urlsymb,'title');
                   12811:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12812:     return $title;
1.301     www      12813: }
1.613     albertel 12814: 
1.614     albertel 12815: sub get_slot {
                   12816:     my ($which,$cnum,$cdom)=@_;
                   12817:     if (!$cnum || !$cdom) {
1.790     albertel 12818: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12819: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12820: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12821:     }
1.703     albertel 12822:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12823:     my %slotinfo;
                   12824:     if (exists($remembered{$key})) {
                   12825: 	$slotinfo{$which} = $remembered{$key};
                   12826:     } else {
                   12827: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12828: 	&Apache::lonhomework::showhash(%slotinfo);
                   12829: 	my ($tmp)=keys(%slotinfo);
                   12830: 	if ($tmp=~/^error:/) { return (); }
                   12831: 	$remembered{$key} = $slotinfo{$which};
                   12832:     }
1.616     albertel 12833:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12834: 	return %{$slotinfo{$which}};
                   12835:     }
                   12836:     return $slotinfo{$which};
1.614     albertel 12837: }
1.1150    raeburn  12838: 
                   12839: sub get_reservable_slots {
                   12840:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12841:     my $now = time;
                   12842:     my $reservable_info;
                   12843:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12844:     if (exists($remembered{$key})) {
                   12845:         $reservable_info = $remembered{$key};
                   12846:     } else {
                   12847:         my %resv;
                   12848:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12849:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12850:         $reservable_info = \%resv;
                   12851:         $remembered{$key} = $reservable_info;
                   12852:     }
                   12853:     return $reservable_info;
                   12854: }
                   12855: 
                   12856: sub get_course_slots {
                   12857:     my ($cnum,$cdom) = @_;
                   12858:     my $hashid=$cnum.':'.$cdom;
                   12859:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12860:     if (defined($cached)) {
                   12861:         if (ref($result) eq 'HASH') {
                   12862:             return %{$result};
                   12863:         }
                   12864:     } else {
                   12865:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12866:         my ($tmp) = keys(%slots);
                   12867:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12868:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12869:             return %slots;
                   12870:         }
                   12871:     }
                   12872:     return;
                   12873: }
                   12874: 
                   12875: sub devalidate_slots_cache {
                   12876:     my ($cnum,$cdom)=@_;
                   12877:     my $hashid=$cnum.':'.$cdom;
                   12878:     &devalidate_cache_new('allslots',$hashid);
                   12879: }
                   12880: 
1.1181    raeburn  12881: sub get_coursechange {
                   12882:     my ($cdom,$cnum) = @_;
                   12883:     if ($cdom eq '' || $cnum eq '') {
                   12884:         return unless ($env{'request.course.id'});
                   12885:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12886:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12887:     }
                   12888:     my $hashid=$cdom.'_'.$cnum;
                   12889:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12890:     if ((defined($cached)) && ($change ne '')) {
                   12891:         return $change;
                   12892:     } else {
                   12893:         my %crshash;
                   12894:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12895:         if ($crshash{'internal.contentchange'} eq '') {
                   12896:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12897:             if ($change eq '') {
                   12898:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12899:                 $change = $crshash{'internal.created'};
                   12900:             }
                   12901:         } else {
                   12902:             $change = $crshash{'internal.contentchange'};
                   12903:         }
                   12904:         my $cachetime = 600;
                   12905:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12906:     }
                   12907:     return $change;
                   12908: }
                   12909: 
                   12910: sub devalidate_coursechange_cache {
                   12911:     my ($cnum,$cdom)=@_;
                   12912:     my $hashid=$cnum.':'.$cdom;
                   12913:     &devalidate_cache_new('crschange',$hashid);
                   12914: }
                   12915: 
1.31      www      12916: # ------------------------------------------------- Update symbolic store links
                   12917: 
                   12918: sub symblist {
                   12919:     my ($mapname,%newhash)=@_;
1.438     www      12920:     $mapname=&deversion(&declutter($mapname));
1.31      www      12921:     my %hash;
1.620     albertel 12922:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12923:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12924:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12925: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12926: 		next if ($url eq 'last_known'
                   12927: 			 && $env{'form.no_update_last_known'});
                   12928: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12929: 						    $newhash{$url}->[1],
                   12930: 						    $newhash{$url}->[0]);
1.191     harris41 12931:             }
1.31      www      12932:             if (untie(%hash)) {
                   12933: 		return 'ok';
                   12934:             }
                   12935:         }
                   12936:     }
                   12937:     return 'error';
1.212     www      12938: }
                   12939: 
                   12940: # --------------------------------------------------------------- Verify a symb
                   12941: 
                   12942: sub symbverify {
1.1190    raeburn  12943:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12944:     my $thisfn=$thisurl;
1.439     www      12945:     $thisfn=&declutter($thisfn);
1.215     www      12946: # direct jump to resource in page or to a sequence - will construct own symbs
                   12947:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12948: # check URL part
1.409     www      12949:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12950: 
1.431     www      12951:     unless ($url eq $thisfn) { return 0; }
1.213     www      12952: 
1.216     www      12953:     $symb=&symbclean($symb);
1.510     www      12954:     $thisurl=&deversion($thisurl);
1.439     www      12955:     $thisfn=&deversion($thisfn);
1.213     www      12956: 
                   12957:     my %bighash;
                   12958:     my $okay=0;
1.431     www      12959: 
1.620     albertel 12960:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12961:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12962:         my $noclutter;
1.1032    raeburn  12963:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12964:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12965:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12966:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12967:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12968:                 $noclutter = 1;
                   12969:             }
                   12970:         }
                   12971:         my $ids;
                   12972:         if ($noclutter) {
                   12973:             $ids=$bighash{'ids_'.$thisurl};
                   12974:         } else {
                   12975:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12976:         }
1.1102    raeburn  12977:         unless ($ids) {
                   12978:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12979:             $ids=$bighash{$idkey};
1.216     www      12980:         }
                   12981:         if ($ids) {
                   12982: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12983:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12984:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12985:             }
1.800     albertel 12986: 	    foreach my $id (split(/\,/,$ids)) {
                   12987: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12988:                if (
                   12989:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12990:    eq $symb) {
                   12991:                    if (ref($encstate)) {
                   12992:                        $$encstate = $bighash{'encrypted_'.$id};
                   12993:                    }
1.620     albertel 12994: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12995: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12996:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12997: 		       $okay=1;
1.1202    raeburn  12998:                        last;
1.582     albertel 12999: 		   }
                   13000: 	       }
1.216     www      13001: 	   }
                   13002:         }
1.213     www      13003: 	untie(%bighash);
                   13004:     }
                   13005:     return $okay;
1.31      www      13006: }
                   13007: 
1.210     www      13008: # --------------------------------------------------------------- Clean-up symb
                   13009: 
                   13010: sub symbclean {
                   13011:     my $symb=shift;
1.568     albertel 13012:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13013: # remove version from map
                   13014:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13015: 
1.210     www      13016: # remove version from URL
                   13017:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13018: 
1.507     www      13019: # remove wrapper
                   13020: 
1.510     www      13021:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13022:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13023:     return $symb;
1.409     www      13024: }
                   13025: 
                   13026: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13027: 
                   13028: sub encode_symb {
                   13029:     my ($map,$resid,$url)=@_;
                   13030:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13031: }
1.409     www      13032: 
                   13033: sub decode_symb {
1.568     albertel 13034:     my $symb=shift;
                   13035:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13036:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13037:     return (&fixversion($map),$resid,&fixversion($url));
                   13038: }
                   13039: 
                   13040: sub fixversion {
                   13041:     my $fn=shift;
1.609     banghart 13042:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13043:     my %bighash;
                   13044:     my $uri=&clutter($fn);
1.620     albertel 13045:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13046: # is this cached?
1.599     albertel 13047:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13048:     if (defined($cached)) { return $result; }
                   13049: # unfortunately not cached, or expired
1.620     albertel 13050:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13051: 	    &GDBM_READER(),0640)) {
                   13052:  	if ($bighash{'version_'.$uri}) {
                   13053:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13054:  	    unless (($version eq 'mostrecent') || 
                   13055: 		    ($version==&getversion($uri))) {
1.440     www      13056:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13057:  	    }
                   13058:  	}
                   13059:  	untie %bighash;
1.413     www      13060:     }
1.599     albertel 13061:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13062: }
                   13063: 
                   13064: sub deversion {
                   13065:     my $url=shift;
                   13066:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13067:     return $url;
1.210     www      13068: }
                   13069: 
1.31      www      13070: # ------------------------------------------------------ Return symb list entry
                   13071: 
                   13072: sub symbread {
1.1282    raeburn  13073:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  13074:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  13075:     if (defined($env{$cache_str})) {
                   13076:         if ($ignorecachednull) {
                   13077:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13078:         } else {
                   13079:             return $env{$cache_str};
                   13080:         }
                   13081:     }
1.242     www      13082: # no filename provided? try from environment
1.1265    raeburn  13083:     unless ($thisfn) {
1.620     albertel 13084:         if ($env{'request.symb'}) {
                   13085: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13086: 	}
1.620     albertel 13087: 	$thisfn=$env{'request.filename'};
1.44      www      13088:     }
1.569     albertel 13089:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13090: # is that filename actually a symb? Verify, clean, and return
                   13091:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13092: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 13093: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13094: 	}
1.242     www      13095:     }
1.44      www      13096:     $thisfn=declutter($thisfn);
1.31      www      13097:     my %hash;
1.37      www      13098:     my %bighash;
                   13099:     my $syval='';
1.620     albertel 13100:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13101:         my $targetfn = $thisfn;
1.609     banghart 13102:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13103:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13104:         }
1.687     albertel 13105: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13106: 	    $targetfn=$1;
                   13107: 	}
1.620     albertel 13108:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13109:                       &GDBM_READER(),0640)) {
1.481     raeburn  13110: 	    $syval=$hash{$targetfn};
1.37      www      13111:             untie(%hash);
                   13112:         }
                   13113: # ---------------------------------------------------------- There was an entry
                   13114:         if ($syval) {
1.601     albertel 13115: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13116: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13117: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13118: 		    #return $env{$cache_str}='';
1.601     albertel 13119: 		#}    
                   13120: 		#$syval.=$1;
                   13121: 	    #}
1.37      www      13122:         } else {
                   13123: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13124:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13125:                             &GDBM_READER(),0640)) {
1.37      www      13126: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13127:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13128:               unless ($ids) { 
                   13129:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13130:               }
                   13131:               unless ($ids) {
                   13132: # alias?
                   13133: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13134:               }
1.37      www      13135:               if ($ids) {
                   13136: # ------------------------------------------------------------------- Has ID(s)
                   13137:                  my @possibilities=split(/\,/,$ids);
1.39      www      13138:                  if ($#possibilities==0) {
                   13139: # ----------------------------------------------- There is only one possibility
1.37      www      13140: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13141: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13142: 						    $resid,$thisfn);
1.1282    raeburn  13143:                      if (ref($possibles) eq 'HASH') {
                   13144:                          $possibles->{$syval} = 1;    
                   13145:                      }
                   13146:                      if ($checkforblock) {
                   13147:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   13148:                          if (@blockers) {
                   13149:                              $syval = '';
                   13150:                              return;
                   13151:                          }
                   13152:                      }
                   13153:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13154: # ------------------------------------------ There is more than one possibility
                   13155:                      my $realpossible=0;
1.800     albertel 13156:                      foreach my $id (@possibilities) {
                   13157: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13158:                          my $canaccess;
                   13159:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13160:                              $canaccess = 1;
                   13161:                          } else { 
                   13162:                              $canaccess = &allowed('bre',$file);
                   13163:                          }
                   13164:                          if ($canaccess) {
                   13165:          		     my ($mapid,$resid)=split(/\./,$id);
                   13166:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13167:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13168: 						             $resid,$thisfn);
                   13169:                                  if (ref($possibles) eq 'HASH') {
                   13170:                                      $possibles->{$syval} = 1;
                   13171:                                  }
                   13172:                                  if ($checkforblock) {
                   13173:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   13174:                                      unless (@blockers > 0) {
                   13175:                                          $syval = $poss_syval;
                   13176:                                          $realpossible++;
                   13177:                                      }
                   13178:                                  } else {
                   13179:                                      $syval = $poss_syval;
                   13180:                                      $realpossible++;
                   13181:                                  }
                   13182:                              }
1.39      www      13183: 			 }
1.191     harris41 13184:                      }
1.39      www      13185: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13186:                  } else {
                   13187:                      $syval='';
1.37      www      13188:                  }
                   13189: 	      }
1.1282    raeburn  13190:               untie(%bighash);
1.481     raeburn  13191:            }
1.31      www      13192:         }
1.62      www      13193:         if ($syval) {
1.620     albertel 13194: 	    return $env{$cache_str}=$syval;
1.62      www      13195:         }
1.31      www      13196:     }
1.949     raeburn  13197:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13198:     return $env{$cache_str}='';
1.31      www      13199: }
                   13200: 
                   13201: # ---------------------------------------------------------- Return random seed
                   13202: 
1.32      www      13203: sub numval {
                   13204:     my $txt=shift;
                   13205:     $txt=~tr/A-J/0-9/;
                   13206:     $txt=~tr/a-j/0-9/;
                   13207:     $txt=~tr/K-T/0-9/;
                   13208:     $txt=~tr/k-t/0-9/;
                   13209:     $txt=~tr/U-Z/0-5/;
                   13210:     $txt=~tr/u-z/0-5/;
                   13211:     $txt=~s/\D//g;
1.564     albertel 13212:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13213:     return int($txt);
1.368     albertel 13214: }
                   13215: 
1.484     albertel 13216: sub numval2 {
                   13217:     my $txt=shift;
                   13218:     $txt=~tr/A-J/0-9/;
                   13219:     $txt=~tr/a-j/0-9/;
                   13220:     $txt=~tr/K-T/0-9/;
                   13221:     $txt=~tr/k-t/0-9/;
                   13222:     $txt=~tr/U-Z/0-5/;
                   13223:     $txt=~tr/u-z/0-5/;
                   13224:     $txt=~s/\D//g;
                   13225:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13226:     my $total;
                   13227:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13228:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13229:     return int($total);
                   13230: }
                   13231: 
1.575     albertel 13232: sub numval3 {
                   13233:     use integer;
                   13234:     my $txt=shift;
                   13235:     $txt=~tr/A-J/0-9/;
                   13236:     $txt=~tr/a-j/0-9/;
                   13237:     $txt=~tr/K-T/0-9/;
                   13238:     $txt=~tr/k-t/0-9/;
                   13239:     $txt=~tr/U-Z/0-5/;
                   13240:     $txt=~tr/u-z/0-5/;
                   13241:     $txt=~s/\D//g;
                   13242:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13243:     my $total;
                   13244:     foreach my $val (@txts) { $total+=$val; }
                   13245:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13246:     return $total;
                   13247: }
                   13248: 
1.675     albertel 13249: sub digest {
                   13250:     my ($data)=@_;
                   13251:     my $digest=&Digest::MD5::md5($data);
                   13252:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13253:     my ($e,$f);
                   13254:     {
                   13255:         use integer;
                   13256:         $e=($a+$b);
                   13257:         $f=($c+$d);
                   13258:         if ($_64bit) {
                   13259:             $e=(($e<<32)>>32);
                   13260:             $f=(($f<<32)>>32);
                   13261:         }
                   13262:     }
                   13263:     if (wantarray) {
                   13264: 	return ($e,$f);
                   13265:     } else {
                   13266: 	my $g;
                   13267: 	{
                   13268: 	    use integer;
                   13269: 	    $g=($e+$f);
                   13270: 	    if ($_64bit) {
                   13271: 		$g=(($g<<32)>>32);
                   13272: 	    }
                   13273: 	}
                   13274: 	return $g;
                   13275:     }
                   13276: }
                   13277: 
1.368     albertel 13278: sub latest_rnd_algorithm_id {
1.675     albertel 13279:     return '64bit5';
1.366     albertel 13280: }
1.32      www      13281: 
1.503     albertel 13282: sub get_rand_alg {
                   13283:     my ($courseid)=@_;
1.790     albertel 13284:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13285:     if ($courseid) {
1.620     albertel 13286: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13287:     }
                   13288:     return &latest_rnd_algorithm_id();
                   13289: }
                   13290: 
1.562     albertel 13291: sub validCODE {
                   13292:     my ($CODE)=@_;
                   13293:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13294:     return 0;
                   13295: }
                   13296: 
1.491     albertel 13297: sub getCODE {
1.620     albertel 13298:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13299:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13300: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13301: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13302: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13303:     }
                   13304:     return undef;
                   13305: }
1.1133    foxr     13306: #
                   13307: #  Determines the random seed for a specific context:
                   13308: #
                   13309: # parameters:
                   13310: #   symb      - in course context the symb for the seed.
                   13311: #   course_id - The course id of the form domain_coursenum.
                   13312: #   domain    - Domain for the user.
                   13313: #   course    - Course for the user.
                   13314: #   cenv      - environment of the course.
                   13315: #
                   13316: # NOTE:
                   13317: #   All parameters are picked out of the environment if missing
                   13318: #   or not defined.
                   13319: #   If a symb cannot be determined the current time is used instead.
                   13320: #
                   13321: #  For a given well defined symb, courside, domain, username,
                   13322: #  and course environment, the seed is reproducible.
                   13323: #
1.31      www      13324: sub rndseed {
1.1133    foxr     13325:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13326:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13327:     if (!defined($symb)) {
1.366     albertel 13328: 	unless ($symb=$wsymb) { return time; }
                   13329:     }
1.1146    foxr     13330:     if (!defined $courseid) { 
                   13331: 	$courseid=$wcourseid; 
                   13332:     }
                   13333:     if (!defined $domain) { $domain=$wdomain; }
                   13334:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13335: 
                   13336:     my $which;
                   13337:     if (defined($cenv->{'rndseed'})) {
                   13338: 	$which = $cenv->{'rndseed'};
                   13339:     } else {
                   13340: 	$which =&get_rand_alg($courseid);
                   13341:     }
1.491     albertel 13342:     if (defined(&getCODE())) {
1.1133    foxr     13343: 
1.675     albertel 13344: 	if ($which eq '64bit5') {
                   13345: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13346: 	} elsif ($which eq '64bit4') {
1.575     albertel 13347: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13348: 	} else {
                   13349: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13350: 	}
1.675     albertel 13351:     } elsif ($which eq '64bit5') {
                   13352: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13353:     } elsif ($which eq '64bit4') {
                   13354: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13355:     } elsif ($which eq '64bit3') {
                   13356: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13357:     } elsif ($which eq '64bit2') {
                   13358: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13359:     } elsif ($which eq '64bit') {
                   13360: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13361:     }
                   13362:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13363: }
                   13364: 
                   13365: sub rndseed_32bit {
                   13366:     my ($symb,$courseid,$domain,$username)=@_;
                   13367:     {
                   13368: 	use integer;
                   13369: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13370: 	my $symbseed=numval($symb) << 22;
                   13371: 	my $namechck=unpack("%32C*",$username) << 17;
                   13372: 	my $nameseed=numval($username) << 12;
                   13373: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13374: 	my $courseseed=unpack("%32C*",$courseid);
                   13375: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13376: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13377: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13378: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13379: 	return $num;
                   13380:     }
                   13381: }
                   13382: 
                   13383: sub rndseed_64bit {
                   13384:     my ($symb,$courseid,$domain,$username)=@_;
                   13385:     {
                   13386: 	use integer;
                   13387: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13388: 	my $symbseed=numval($symb) << 10;
                   13389: 	my $namechck=unpack("%32S*",$username);
                   13390: 	
                   13391: 	my $nameseed=numval($username) << 21;
                   13392: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13393: 	my $courseseed=unpack("%32S*",$courseid);
                   13394: 	
                   13395: 	my $num1=$symbchck+$symbseed+$namechck;
                   13396: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13397: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13398: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13399: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13400: 	return "$num1,$num2";
1.155     albertel 13401:     }
1.366     albertel 13402: }
                   13403: 
1.443     albertel 13404: sub rndseed_64bit2 {
                   13405:     my ($symb,$courseid,$domain,$username)=@_;
                   13406:     {
                   13407: 	use integer;
                   13408: 	# strings need to be an even # of cahracters long, it it is odd the
                   13409:         # last characters gets thrown away
                   13410: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13411: 	my $symbseed=numval($symb) << 10;
                   13412: 	my $namechck=unpack("%32S*",$username.' ');
                   13413: 	
                   13414: 	my $nameseed=numval($username) << 21;
1.501     albertel 13415: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13416: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13417: 	
                   13418: 	my $num1=$symbchck+$symbseed+$namechck;
                   13419: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13420: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13421: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13422: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13423: 	return "$num1,$num2";
                   13424:     }
                   13425: }
                   13426: 
                   13427: sub rndseed_64bit3 {
                   13428:     my ($symb,$courseid,$domain,$username)=@_;
                   13429:     {
                   13430: 	use integer;
                   13431: 	# strings need to be an even # of cahracters long, it it is odd the
                   13432:         # last characters gets thrown away
                   13433: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13434: 	my $symbseed=numval2($symb) << 10;
                   13435: 	my $namechck=unpack("%32S*",$username.' ');
                   13436: 	
                   13437: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13438: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13439: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13440: 	
                   13441: 	my $num1=$symbchck+$symbseed+$namechck;
                   13442: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13443: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13444: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13445: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13446: 	
1.503     albertel 13447: 	return "$num1:$num2";
1.443     albertel 13448:     }
                   13449: }
                   13450: 
1.575     albertel 13451: sub rndseed_64bit4 {
                   13452:     my ($symb,$courseid,$domain,$username)=@_;
                   13453:     {
                   13454: 	use integer;
                   13455: 	# strings need to be an even # of cahracters long, it it is odd the
                   13456:         # last characters gets thrown away
                   13457: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13458: 	my $symbseed=numval3($symb) << 10;
                   13459: 	my $namechck=unpack("%32S*",$username.' ');
                   13460: 	
                   13461: 	my $nameseed=numval3($username) << 21;
                   13462: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13463: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13464: 	
                   13465: 	my $num1=$symbchck+$symbseed+$namechck;
                   13466: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13467: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13468: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13469: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13470: 	
1.575     albertel 13471: 	return "$num1:$num2";
                   13472:     }
                   13473: }
                   13474: 
1.675     albertel 13475: sub rndseed_64bit5 {
                   13476:     my ($symb,$courseid,$domain,$username)=@_;
                   13477:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13478:     return "$num1:$num2";
                   13479: }
                   13480: 
1.366     albertel 13481: sub rndseed_CODE_64bit {
                   13482:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13483:     {
1.366     albertel 13484: 	use integer;
1.443     albertel 13485: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13486: 	my $symbseed=numval2($symb);
1.491     albertel 13487: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13488: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13489: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13490: 	my $num1=$symbseed+$CODEchck;
                   13491: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13492: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13493: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13494: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13495: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13496: 	return "$num1:$num2";
1.366     albertel 13497:     }
                   13498: }
                   13499: 
1.575     albertel 13500: sub rndseed_CODE_64bit4 {
                   13501:     my ($symb,$courseid,$domain,$username)=@_;
                   13502:     {
                   13503: 	use integer;
                   13504: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13505: 	my $symbseed=numval3($symb);
                   13506: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13507: 	my $CODEseed=numval3(&getCODE());
                   13508: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13509: 	my $num1=$symbseed+$CODEchck;
                   13510: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13511: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13512: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13513: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13514: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13515: 	return "$num1:$num2";
                   13516:     }
                   13517: }
                   13518: 
1.675     albertel 13519: sub rndseed_CODE_64bit5 {
                   13520:     my ($symb,$courseid,$domain,$username)=@_;
                   13521:     my $code = &getCODE();
                   13522:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13523:     return "$num1:$num2";
                   13524: }
                   13525: 
1.366     albertel 13526: sub setup_random_from_rndseed {
                   13527:     my ($rndseed)=@_;
1.503     albertel 13528:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13529:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13530:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13531:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13532:         } else {
                   13533:             &Math::Random::random_set_seed($num1,$num2);
                   13534:         }
1.366     albertel 13535:     } else {
                   13536: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13537:     }
1.36      albertel 13538: }
                   13539: 
1.474     albertel 13540: sub latest_receipt_algorithm_id {
1.835     albertel 13541:     return 'receipt3';
1.474     albertel 13542: }
                   13543: 
1.480     www      13544: sub recunique {
                   13545:     my $fucourseid=shift;
                   13546:     my $unique;
1.835     albertel 13547:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13548: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13549: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13550:     } else {
                   13551: 	$unique=$perlvar{'lonReceipt'};
                   13552:     }
                   13553:     return unpack("%32C*",$unique);
                   13554: }
                   13555: 
                   13556: sub recprefix {
                   13557:     my $fucourseid=shift;
                   13558:     my $prefix;
1.835     albertel 13559:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13560: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13561: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13562:     } else {
                   13563: 	$prefix=$perlvar{'lonHostID'};
                   13564:     }
                   13565:     return unpack("%32C*",$prefix);
                   13566: }
                   13567: 
1.76      www      13568: sub ireceipt {
1.474     albertel 13569:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13570: 
                   13571:     my $return =&recprefix($fucourseid).'-';
                   13572: 
                   13573:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13574: 	$env{'request.state'} eq 'construct') {
                   13575: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13576: 	return $return;
                   13577:     }
                   13578: 
1.76      www      13579:     my $cuname=unpack("%32C*",$funame);
                   13580:     my $cudom=unpack("%32C*",$fudom);
                   13581:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13582:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13583:     my $cunique=&recunique($fucourseid);
1.474     albertel 13584:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13585:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13586: 
1.790     albertel 13587: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13588: 			       
                   13589: 	$return.= ($cunique%$cuname+
                   13590: 		   $cunique%$cudom+
                   13591: 		   $cusymb%$cuname+
                   13592: 		   $cusymb%$cudom+
                   13593: 		   $cucourseid%$cuname+
                   13594: 		   $cucourseid%$cudom+
                   13595: 		   $cpart%$cuname+
                   13596: 		   $cpart%$cudom);
                   13597:     } else {
                   13598: 	$return.= ($cunique%$cuname+
                   13599: 		   $cunique%$cudom+
                   13600: 		   $cusymb%$cuname+
                   13601: 		   $cusymb%$cudom+
                   13602: 		   $cucourseid%$cuname+
                   13603: 		   $cucourseid%$cudom);
                   13604:     }
                   13605:     return $return;
1.76      www      13606: }
                   13607: 
                   13608: sub receipt {
1.474     albertel 13609:     my ($part)=@_;
1.790     albertel 13610:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13611:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13612: }
1.260     ng       13613: 
1.790     albertel 13614: sub whichuser {
                   13615:     my ($passedsymb)=@_;
                   13616:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13617:     if (defined($env{'form.grade_symb'})) {
                   13618: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13619: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13620: 	if (!$allowed &&
                   13621: 	    exists($env{'request.course.sec'}) &&
                   13622: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13623: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13624: 			      '/'.$env{'request.course.sec'});
                   13625: 	}
                   13626: 	if ($allowed) {
                   13627: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13628: 	    $courseid=$tmp_courseid;
                   13629: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13630: 	    ($name)=&get_env_multiple('form.grade_username');
                   13631: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13632: 	}
                   13633:     }
                   13634:     if (!$passedsymb) {
                   13635: 	$symb=&symbread();
                   13636:     } else {
                   13637: 	$symb=$passedsymb;
                   13638:     }
                   13639:     $courseid=$env{'request.course.id'};
                   13640:     $domain=$env{'user.domain'};
                   13641:     $name=$env{'user.name'};
                   13642:     if ($name eq 'public' && $domain eq 'public') {
                   13643: 	if (!defined($env{'form.username'})) {
                   13644: 	    $env{'form.username'}.=time.rand(10000000);
                   13645: 	}
                   13646: 	$name.=$env{'form.username'};
                   13647:     }
                   13648:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13649: 
                   13650: }
                   13651: 
1.36      albertel 13652: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13653: # returns either the contents of the file or 
                   13654: # -1 if the file doesn't exist
1.481     raeburn  13655: #
                   13656: # if the target is a file that was uploaded via DOCS, 
                   13657: # a check will be made to see if a current copy exists on the local server,
                   13658: # if it does this will be served, otherwise a copy will be retrieved from
                   13659: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13660: # the local server.   
1.472     albertel 13661: 
1.36      albertel 13662: sub getfile {
1.538     albertel 13663:     my ($file) = @_;
1.609     banghart 13664:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13665:     &repcopy($file);
                   13666:     return &readfile($file);
                   13667: }
                   13668: 
                   13669: sub repcopy_userfile {
                   13670:     my ($file)=@_;
1.1142    raeburn  13671:     my $londocroot = $perlvar{'lonDocRoot'};
                   13672:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13673:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13674:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13675: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13676:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13677:     if (-e "$file") {
1.828     www      13678: # we already have a local copy, check it out
1.538     albertel 13679: 	my @fileinfo = stat($file);
1.828     www      13680: 	my $rtncode;
                   13681: 	my $info;
1.538     albertel 13682: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13683: 	if ($lwpresp ne 'ok') {
1.828     www      13684: # there is no such file anymore, even though we had a local copy
1.482     albertel 13685: 	    if ($rtncode eq '404') {
1.538     albertel 13686: 		unlink($file);
1.482     albertel 13687: 	    }
                   13688: 	    return -1;
                   13689: 	}
                   13690: 	if ($info < $fileinfo[9]) {
1.828     www      13691: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13692: 	    return 'ok';
1.828     www      13693: 	} else {
                   13694: # the file is outdated, get rid of it
                   13695: 	    unlink($file);
1.482     albertel 13696: 	}
1.828     www      13697:     }
                   13698: # one way or the other, at this point, we don't have the file
                   13699: # construct the correct path for the file
                   13700:     my @parts = ($cdom,$cnum); 
                   13701:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13702: 	push @parts, split(/\//,$1);
                   13703:     }
                   13704:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13705:     foreach my $part (@parts) {
                   13706: 	$path .= '/'.$part;
                   13707: 	if (!-e $path) {
                   13708: 	    mkdir($path,0770);
1.482     albertel 13709: 	}
                   13710:     }
1.828     www      13711: # now the path exists for sure
                   13712: # get a user agent
                   13713:     my $transferfile=$file.'.in.transfer';
                   13714: # FIXME: this should flock
                   13715:     if (-e $transferfile) { return 'ok'; }
                   13716:     my $request;
                   13717:     $uri=~s/^\///;
1.980     raeburn  13718:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  13719:     my $hostname = &hostname($homeserver);
1.980     raeburn  13720:     my $protocol = $protocol{$homeserver};
                   13721:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13722:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  13723:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13724: # did it work?
                   13725:     if ($response->is_error()) {
                   13726: 	unlink($transferfile);
                   13727: 	&logthis("Userfile repcopy failed for $uri");
                   13728: 	return -1;
                   13729:     }
                   13730: # worked, rename the transfer file
                   13731:     rename($transferfile,$file);
1.607     raeburn  13732:     return 'ok';
1.481     raeburn  13733: }
                   13734: 
1.517     albertel 13735: sub tokenwrapper {
                   13736:     my $uri=shift;
1.980     raeburn  13737:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13738:     $uri=~s|^/||;
1.620     albertel 13739:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13740:     my $token=$1;
1.552     albertel 13741:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13742:     if ($udom && $uname && $file) {
                   13743: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13744:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13745:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  13746:         my $hostname = &hostname($homeserver);
1.980     raeburn  13747:         my $protocol = $protocol{$homeserver};
                   13748:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13749:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13750:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13751:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13752:     } else {
                   13753:         return '/adm/notfound.html';
                   13754:     }
                   13755: }
                   13756: 
1.828     www      13757: # call with reqtype HEAD: get last modification time
                   13758: # call with reqtype GET: get the file contents
                   13759: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13760: #
1.481     raeburn  13761: sub getuploaded {
                   13762:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13763:     $uri=~s/^\///;
1.980     raeburn  13764:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  13765:     my $hostname = &hostname($homeserver);
1.980     raeburn  13766:     my $protocol = $protocol{$homeserver};
                   13767:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13768:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13769:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13770:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13771:     $$rtncode = $response->code;
1.482     albertel 13772:     if (! $response->is_success()) {
                   13773: 	return 'failed';
                   13774:     }      
                   13775:     if ($reqtype eq 'HEAD') {
1.486     www      13776: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13777:     } elsif ($reqtype eq 'GET') {
                   13778: 	$$info = $response->content;
1.472     albertel 13779:     }
1.482     albertel 13780:     return 'ok';
1.36      albertel 13781: }
                   13782: 
1.481     raeburn  13783: sub readfile {
                   13784:     my $file = shift;
                   13785:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13786:     my $fh;
1.1359    raeburn  13787:     open($fh,"<",$file);
1.481     raeburn  13788:     my $a='';
1.800     albertel 13789:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13790:     return $a;
                   13791: }
                   13792: 
1.36      albertel 13793: sub filelocation {
1.590     banghart 13794:     my ($dir,$file) = @_;
                   13795:     my $location;
                   13796:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13797: 
                   13798:     if ($file =~ m-^/adm/-) {
                   13799: 	$file=~s-^/adm/wrapper/-/-;
                   13800: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13801:     }
1.882     albertel 13802: 
1.1139    www      13803:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13804:         $location = $file;
1.609     banghart 13805:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13806:         my ($udom,$uname,$filename)=
1.811     albertel 13807:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13808:         my $home=&homeserver($uname,$udom);
                   13809:         my $is_me=0;
                   13810:         my @ids=&current_machine_ids();
                   13811:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13812:         if ($is_me) {
1.1117    foxr     13813:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13814:         } else {
                   13815:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13816:   	      $udom.'/'.$uname.'/'.$filename;
                   13817:         }
1.882     albertel 13818:     } elsif ($file =~ m-^/adm/-) {
                   13819: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13820:     } else {
                   13821:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13822:         $file=~s:^/(res|priv)/:/:;
                   13823:         my $space=$1;
1.590     banghart 13824:         if ( !( $file =~ m:^/:) ) {
                   13825:             $location = $dir. '/'.$file;
                   13826:         } else {
1.1142    raeburn  13827:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13828:         }
1.59      albertel 13829:     }
1.590     banghart 13830:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13831:     while ($location=~m{/\.\./}) {
                   13832: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13833: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13834: 	} else {
                   13835: 	    $location=~ s{/\.\./}{/}g;
                   13836: 	}
                   13837:     } #remove dir/..
1.590     banghart 13838:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13839:     return $location;
1.46      www      13840: }
1.36      albertel 13841: 
1.46      www      13842: sub hreflocation {
                   13843:     my ($dir,$file)=@_;
1.980     raeburn  13844:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13845: 	$file=filelocation($dir,$file);
1.700     albertel 13846:     } elsif ($file=~m-^/adm/-) {
                   13847: 	$file=~s-^/adm/wrapper/-/-;
                   13848: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13849:     }
                   13850:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13851: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13852:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13853: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13854: 	        {/uploaded/$1/$2/}x;
1.46      www      13855:     }
1.913     albertel 13856:     if ($file=~ m{^/userfiles/}) {
                   13857: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13858:     }
1.462     albertel 13859:     return $file;
1.465     albertel 13860: }
                   13861: 
1.1139    www      13862: 
                   13863: 
                   13864: 
                   13865: 
1.465     albertel 13866: sub current_machine_domains {
1.853     albertel 13867:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13868: }
                   13869: 
                   13870: sub machine_domains {
                   13871:     my ($hostname) = @_;
1.465     albertel 13872:     my @domains;
1.838     albertel 13873:     my %hostname = &all_hostnames();
1.465     albertel 13874:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13875: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13876: 	if ($hostname eq $name) {
1.844     albertel 13877: 	    push(@domains,&host_domain($id));
1.465     albertel 13878: 	}
                   13879:     }
                   13880:     return @domains;
                   13881: }
                   13882: 
                   13883: sub current_machine_ids {
1.853     albertel 13884:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13885: }
                   13886: 
                   13887: sub machine_ids {
                   13888:     my ($hostname) = @_;
                   13889:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13890:     my @ids;
1.888     albertel 13891:     my %name_to_host = &all_names();
1.889     albertel 13892:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13893: 	return @{ $name_to_host{$hostname} };
                   13894:     }
                   13895:     return;
1.31      www      13896: }
                   13897: 
1.824     raeburn  13898: sub additional_machine_domains {
                   13899:     my @domains;
1.1359    raeburn  13900:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13901:     while( my $line = <$fh>) {
                   13902:         $line =~ s/\s//g;
                   13903:         push(@domains,$line);
                   13904:     }
                   13905:     return @domains;
                   13906: }
                   13907: 
                   13908: sub default_login_domain {
                   13909:     my $domain = $perlvar{'lonDefDomain'};
                   13910:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13911:     foreach my $posdom (&current_machine_domains(),
                   13912:                         &additional_machine_domains()) {
                   13913:         if (lc($posdom) eq lc($testdomain)) {
                   13914:             $domain=$posdom;
                   13915:             last;
                   13916:         }
                   13917:     }
                   13918:     return $domain;
                   13919: }
                   13920: 
1.1398    raeburn  13921: sub uses_sts {
                   13922:     my ($ignore_cache) = @_;
                   13923:     my $lonhost = $perlvar{'lonHostID'};
                   13924:     my $hostname = &hostname($lonhost);
                   13925:     my $sts_on;
                   13926:     if ($protocol{$lonhost} eq 'https') {
                   13927:         my $cachetime = 12*3600;
                   13928:         if (!$ignore_cache) {
                   13929:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13930:             if (defined($cached)) {
                   13931:                 return $sts_on;
                   13932:             }
                   13933:         }
                   13934:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13935:         my $request=new HTTP::Request('HEAD',$url);
                   13936:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   13937:         if ($response->is_success) {
                   13938:             my $has_sts = $response->header('Strict-Transport-Security');
                   13939:             if ($has_sts eq '') {
                   13940:                 $sts_on = 0;
                   13941:             } else {
                   13942:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13943:                     my $maxage = $1;
                   13944:                     if ($maxage) {
                   13945:                         $sts_on = 1;
                   13946:                     } else {
                   13947:                         $sts_on = 0;
                   13948:                     }
                   13949:                 } else {
                   13950:                     $sts_on = 0;
                   13951:                 }
                   13952:             }
                   13953:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13954:         }
                   13955:     }
                   13956:     return;
                   13957: }
                   13958: 
1.31      www      13959: # ------------------------------------------------------------- Declutters URLs
                   13960: 
                   13961: sub declutter {
                   13962:     my $thisfn=shift;
1.569     albertel 13963:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13964:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13965:         $thisfn=~s{^/home/httpd/html}{};
                   13966:     }
1.31      www      13967:     $thisfn=~s/^\///;
1.697     albertel 13968:     $thisfn=~s|^adm/wrapper/||;
                   13969:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13970:     $thisfn=~s/^res\///;
1.1172    bisitz   13971:     $thisfn=~s/^priv\///;
1.1032    raeburn  13972:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13973:         $thisfn=~s/\?.+$//;
                   13974:     }
1.268     www      13975:     return $thisfn;
                   13976: }
                   13977: 
                   13978: # ------------------------------------------------------------- Clutter up URLs
                   13979: 
                   13980: sub clutter {
                   13981:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13982:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13983: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13984:        $thisfn='/res'.$thisfn; 
                   13985:     }
1.1031    raeburn  13986:     if ($thisfn !~m|^/adm|) {
                   13987: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13988: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13989: 	} else {
                   13990: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13991: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13992: 	    if ($embstyle eq 'ssi'
                   13993: 		|| ($embstyle eq 'hdn')
                   13994: 		|| ($embstyle eq 'rat')
                   13995: 		|| ($embstyle eq 'prv')
                   13996: 		|| ($embstyle eq 'ign')) {
                   13997: 		#do nothing with these
                   13998: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13999: 		|| ($embstyle eq 'emb')
                   14000: 		|| ($embstyle eq 'wrp')) {
                   14001: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14002: 	    } elsif ($embstyle eq 'unk'
                   14003: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14004: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14005: 	    } else {
1.718     www      14006: #		&logthis("Got a blank emb style");
1.695     albertel 14007: 	    }
1.694     albertel 14008: 	}
1.1343    raeburn  14009:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14010:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14011:     }
1.31      www      14012:     return $thisfn;
1.12      www      14013: }
                   14014: 
1.787     albertel 14015: sub clutter_with_no_wrapper {
                   14016:     my $uri = &clutter(shift);
                   14017:     if ($uri =~ m-^/adm/-) {
                   14018: 	$uri =~ s-^/adm/wrapper/-/-;
                   14019: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14020:     }
                   14021:     return $uri;
                   14022: }
                   14023: 
1.557     albertel 14024: sub freeze_escape {
                   14025:     my ($value)=@_;
                   14026:     if (ref($value)) {
                   14027: 	$value=&nfreeze($value);
                   14028: 	return '__FROZEN__'.&escape($value);
                   14029:     }
                   14030:     return &escape($value);
                   14031: }
                   14032: 
1.11      www      14033: 
1.557     albertel 14034: sub thaw_unescape {
                   14035:     my ($value)=@_;
                   14036:     if ($value =~ /^__FROZEN__/) {
                   14037: 	substr($value,0,10,undef);
                   14038: 	$value=&unescape($value);
                   14039: 	return &thaw($value);
                   14040:     }
                   14041:     return &unescape($value);
                   14042: }
                   14043: 
1.436     albertel 14044: sub correct_line_ends {
                   14045:     my ($result)=@_;
                   14046:     $$result =~s/\r\n/\n/mg;
                   14047:     $$result =~s/\r/\n/mg;
1.415     albertel 14048: }
1.1       albertel 14049: # ================================================================ Main Program
                   14050: 
1.184     www      14051: sub goodbye {
1.204     albertel 14052:    &logthis("Starting Shut down");
1.443     albertel 14053: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14054:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14055: #converted
1.599     albertel 14056: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14057:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14058: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14059: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14060: #1.1 only
1.870     albertel 14061: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14062: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14063: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14064: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14065:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14066:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14067:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14068:    &flushcourselogs();
                   14069:    &logthis("Shutting down");
                   14070: }
                   14071: 
1.852     albertel 14072: sub get_dns {
1.1210    raeburn  14073:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14074:     if (!$ignore_cache) {
                   14075: 	my ($content,$cached)=
                   14076: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14077: 	if ($cached) {
1.1210    raeburn  14078: 	    &$func($content,$hashref);
1.869     albertel 14079: 	    return;
                   14080: 	}
                   14081:     }
                   14082: 
                   14083:     my %alldns;
1.1379    raeburn  14084:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14085:         foreach my $dns (<$config>) {
                   14086: 	    next if ($dns !~ /^\^(\S*)/x);
                   14087:             my $line = $1;
                   14088:             my ($host,$protocol) = split(/:/,$line);
                   14089:             if ($protocol ne 'https') {
                   14090:                 $protocol = 'http';
                   14091:             }
                   14092: 	    $alldns{$host} = $protocol;
1.979     raeburn  14093:         }
1.1379    raeburn  14094:         close($config);
1.869     albertel 14095:     }
                   14096:     while (%alldns) {
1.1263    raeburn  14097: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  14098: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  14099:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  14100:         delete($alldns{$dns});
1.852     albertel 14101: 	next if ($response->is_error());
1.1379    raeburn  14102:         if ($url eq '/adm/dns/loncapaCRL') {
                   14103:             return &$func($response);
                   14104:         } else {
                   14105: 	    my @content = split("\n",$response->content);
                   14106: 	    unless ($nocache) {
                   14107: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14108: 	    }
                   14109: 	    &$func(\@content,$hashref);
                   14110:             return;
                   14111:         }
                   14112:     }
                   14113:     my $which = (split('/',$url,4))[3];
                   14114:     if ($which eq 'loncapaCRL') {
                   14115:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14116:         if (-e $diskfile) {
                   14117:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14118:         } else {
                   14119:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14120:         }
                   14121:     } else {
                   14122:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14123:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14124:             my @content = <$config>;
                   14125:             close($config);
                   14126:             &$func(\@content,$hashref);
                   14127:         }
1.852     albertel 14128:     }
1.1210    raeburn  14129:     return;
                   14130: }
                   14131: 
                   14132: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14133: sub parse_dns_checksums_tab {
1.1210    raeburn  14134:     my ($lines,$hashref) = @_;
1.1264    raeburn  14135:     my $lonhost = $perlvar{'lonHostID'};
                   14136:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14137:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14138:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14139:     my $webconfdir = '/etc/httpd/conf';
                   14140:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14141:         $webconfdir = '/etc/apache2';
                   14142:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14143:         if ($1 >= 10) {
                   14144:             $webconfdir = '/etc/apache2';
                   14145:         }
                   14146:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14147:         if ($1 >= 10.0) {
                   14148:             $webconfdir = '/etc/apache2';
                   14149:         }
                   14150:     }
1.1210    raeburn  14151:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14152:     my (%chksum,%revnum);
                   14153:     if (ref($lines) eq 'ARRAY') {
                   14154:         chomp(@{$lines});
1.1238    raeburn  14155:         my $version = shift(@{$lines});
                   14156:         if ($version eq $release) {  
1.1210    raeburn  14157:             foreach my $line (@{$lines}) {
1.1238    raeburn  14158:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14159:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14160:                     if ($webconfdir eq '/etc/apache2') {
                   14161:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14162:                     }
                   14163:                 }
1.1238    raeburn  14164:                 $chksum{$file} = $shasum;
                   14165:                 $revnum{$file} = $version;
1.1210    raeburn  14166:             }
                   14167:             if (ref($hashref) eq 'HASH') {
                   14168:                 %{$hashref} = (
                   14169:                                 sums     => \%chksum,
                   14170:                                 versions => \%revnum,
                   14171:                               );
                   14172:             }
                   14173:         }
                   14174:     }
1.869     albertel 14175:     return;
1.852     albertel 14176: }
1.1210    raeburn  14177: 
                   14178: sub fetch_dns_checksums {
1.1238    raeburn  14179:     my %checksums;
                   14180:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14181:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14182:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14183:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14184:              \%checksums);
1.1210    raeburn  14185:     return \%checksums;
                   14186: }
                   14187: 
1.1379    raeburn  14188: sub fetch_crl_pemfile {
                   14189:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14190: }
                   14191: 
                   14192: sub save_crl_pem {
                   14193:     my ($response) = @_;
1.1380    raeburn  14194:     my ($msg,$hadchanges);
1.1379    raeburn  14195:     if (ref($response)) {
                   14196:         my $now = time;
                   14197:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14198:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14199:         if (open(my $fh,'>',"$tmpcrl")) {
                   14200:             print $fh $response->content;
                   14201:             close($fh);
                   14202:             if (-e $lonca) {
                   14203:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14204:                     my $check = <PIPE>;
                   14205:                     close(PIPE);
                   14206:                     chomp($check);
                   14207:                     if ($check eq 'verify OK') {
                   14208:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  14209:                         my $backup;
1.1379    raeburn  14210:                         if (-e $dest) {
1.1380    raeburn  14211:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   14212:                                 $backup = 'ok';
                   14213:                             }
1.1379    raeburn  14214:                         }
                   14215:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   14216:                             $msg = 'ok';
1.1380    raeburn  14217:                             if ($backup) {
                   14218:                                 my (%oldnums,%newnums);
                   14219:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   14220:                                     while (<PIPE>) {
                   14221:                                         $oldnums{(split(/:/))[1]} = 1;
                   14222:                                     }
                   14223:                                     close(PIPE);
                   14224:                                 }
                   14225:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   14226:                                     while(<PIPE>) {
                   14227:                                         $newnums{(split(/:/))[1]} = 1;
                   14228:                                     }
                   14229:                                     close(PIPE);
                   14230:                                 }
                   14231:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   14232:                                     unless (exists($oldnums{$key})) {
                   14233:                                         $hadchanges = 1;
                   14234:                                         last;
                   14235:                                     }
                   14236:                                 }
                   14237:                                 unless ($hadchanges) {
                   14238:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   14239:                                         unless (exists($newnums{$key})) {
                   14240:                                             $hadchanges = 1;
                   14241:                                             last;
                   14242:                                         }
                   14243:                                     }
                   14244:                                 }
                   14245:                             }
1.1379    raeburn  14246:                         }
                   14247:                     } else {
                   14248:                         unlink($tmpcrl);
                   14249:                     }
                   14250:                 } else {
                   14251:                     unlink($tmpcrl);
                   14252:                 }
                   14253:             } else {
                   14254:                 unlink($tmpcrl);
                   14255:             }
                   14256:         }
                   14257:     }
1.1380    raeburn  14258:     return ($msg,$hadchanges);
1.1379    raeburn  14259: }
                   14260: 
1.327     albertel 14261: # ------------------------------------------------------------ Read domain file
                   14262: {
1.852     albertel 14263:     my $loaded;
1.846     albertel 14264:     my %domain;
                   14265: 
1.852     albertel 14266:     sub parse_domain_tab {
                   14267: 	my ($lines) = @_;
                   14268: 	foreach my $line (@$lines) {
                   14269: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14270: 
1.846     albertel 14271: 	    chomp($line);
1.852     albertel 14272: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14273: 	    my %this_domain;
                   14274: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14275: 			       'lang_def', 'city', 'longi', 'lati',
                   14276: 			       'primary') {
                   14277: 		$this_domain{$field} = shift(@elements);
                   14278: 	    }
                   14279: 	    $domain{$name} = \%this_domain;
1.852     albertel 14280: 	}
                   14281:     }
1.864     albertel 14282: 
                   14283:     sub reset_domain_info {
                   14284: 	undef($loaded);
                   14285: 	undef(%domain);
                   14286:     }
                   14287: 
1.852     albertel 14288:     sub load_domain_tab {
1.1293    raeburn  14289: 	my ($ignore_cache,$nocache) = @_;
                   14290: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14291: 	my $fh;
1.1359    raeburn  14292: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14293: 	    my @lines = <$fh>;
                   14294: 	    &parse_domain_tab(\@lines);
1.448     albertel 14295: 	}
1.852     albertel 14296: 	close($fh);
                   14297: 	$loaded = 1;
1.327     albertel 14298:     }
1.846     albertel 14299: 
                   14300:     sub domain {
1.852     albertel 14301: 	&load_domain_tab() if (!$loaded);
                   14302: 
1.846     albertel 14303: 	my ($name,$what) = @_;
                   14304: 	return if ( !exists($domain{$name}) );
                   14305: 
                   14306: 	if (!$what) {
                   14307: 	    return $domain{$name}{'description'};
                   14308: 	}
                   14309: 	return $domain{$name}{$what};
                   14310:     }
1.974     raeburn  14311: 
                   14312:     sub domain_info {
                   14313:         &load_domain_tab() if (!$loaded);
                   14314:         return %domain;
                   14315:     }
                   14316: 
1.327     albertel 14317: }
                   14318: 
                   14319: 
1.1       albertel 14320: # ------------------------------------------------------------- Read hosts file
                   14321: {
1.838     albertel 14322:     my %hostname;
1.844     albertel 14323:     my %hostdom;
1.845     albertel 14324:     my %libserv;
1.852     albertel 14325:     my $loaded;
1.888     albertel 14326:     my %name_to_host;
1.1074    raeburn  14327:     my %internetdom;
1.1107    raeburn  14328:     my %LC_dns_serv;
1.852     albertel 14329: 
                   14330:     sub parse_hosts_tab {
                   14331: 	my ($file) = @_;
                   14332: 	foreach my $configline (@$file) {
                   14333: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14334:             chomp($configline);
                   14335: 	    if ($configline =~ /^\^/) {
                   14336:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14337:                     $LC_dns_serv{$1} = 1;
                   14338:                 }
                   14339:                 next;
                   14340:             }
1.1074    raeburn  14341: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14342: 	    $name=~s/\s//g;
                   14343: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  14344:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14345:                     my $curr = $hostname{$id};
                   14346:                     my $skip;
                   14347:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14348:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14349:                             $skip = 1;
                   14350:                         } else {
                   14351:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14352:                         }
                   14353:                     }
                   14354:                     unless ($skip) {
                   14355:                         push(@{$name_to_host{$name}},$id);
                   14356:                     }
                   14357:                 } else {
                   14358:                     push(@{$name_to_host{$name}},$id);
                   14359:                 }
1.852     albertel 14360: 		$hostname{$id}=$name;
                   14361: 		$hostdom{$id}=$domain;
                   14362: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14363:                 if (defined($protocol)) {
                   14364:                     if ($protocol eq 'https') {
                   14365:                         $protocol{$id} = $protocol;
                   14366:                     } else {
                   14367:                         $protocol{$id} = 'http'; 
                   14368:                     }
1.968     raeburn  14369:                 } else {
1.969     raeburn  14370:                     $protocol{$id} = 'http';
1.968     raeburn  14371:                 }
1.1074    raeburn  14372:                 if (defined($intdom)) {
                   14373:                     $internetdom{$id} = $intdom;
                   14374:                 }
1.852     albertel 14375: 	    }
                   14376: 	}
                   14377:     }
1.864     albertel 14378:     
                   14379:     sub reset_hosts_info {
1.897     albertel 14380: 	&purge_remembered();
1.864     albertel 14381: 	&reset_domain_info();
                   14382: 	&reset_hosts_ip_info();
1.1339    raeburn  14383:         undef(%internetdom);
1.892     albertel 14384: 	undef(%name_to_host);
1.864     albertel 14385: 	undef(%hostname);
                   14386: 	undef(%hostdom);
                   14387: 	undef(%libserv);
                   14388: 	undef($loaded);
                   14389:     }
1.1       albertel 14390: 
1.852     albertel 14391:     sub load_hosts_tab {
1.1293    raeburn  14392: 	my ($ignore_cache,$nocache) = @_;
                   14393: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  14394: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14395: 	my @config = <$config>;
                   14396: 	&parse_hosts_tab(\@config);
                   14397: 	close($config);
                   14398: 	$loaded=1;
1.1       albertel 14399:     }
1.852     albertel 14400: 
1.838     albertel 14401:     sub hostname {
1.852     albertel 14402: 	&load_hosts_tab() if (!$loaded);
                   14403: 
1.838     albertel 14404: 	my ($lonid) = @_;
                   14405: 	return $hostname{$lonid};
                   14406:     }
1.845     albertel 14407: 
1.838     albertel 14408:     sub all_hostnames {
1.852     albertel 14409: 	&load_hosts_tab() if (!$loaded);
                   14410: 
1.838     albertel 14411: 	return %hostname;
                   14412:     }
1.845     albertel 14413: 
1.888     albertel 14414:     sub all_names {
1.1293    raeburn  14415:         my ($ignore_cache,$nocache) = @_;
                   14416: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14417: 
                   14418: 	return %name_to_host;
                   14419:     }
                   14420: 
1.974     raeburn  14421:     sub all_host_domain {
                   14422:         &load_hosts_tab() if (!$loaded);
                   14423:         return %hostdom;
                   14424:     }
                   14425: 
1.1339    raeburn  14426:     sub all_host_intdom {
                   14427:         &load_hosts_tab() if (!$loaded);
                   14428:         return %internetdom;
                   14429:     }
                   14430: 
1.845     albertel 14431:     sub is_library {
1.852     albertel 14432: 	&load_hosts_tab() if (!$loaded);
                   14433: 
1.845     albertel 14434: 	return exists($libserv{$_[0]});
                   14435:     }
                   14436: 
                   14437:     sub all_library {
1.852     albertel 14438: 	&load_hosts_tab() if (!$loaded);
                   14439: 
1.845     albertel 14440: 	return %libserv;
                   14441:     }
                   14442: 
1.1062    droeschl 14443:     sub unique_library {
                   14444: 	#2x reverse removes all hostnames that appear more than once
                   14445:         my %unique = reverse &all_library();
                   14446:         return reverse %unique;
                   14447:     }
                   14448: 
1.841     albertel 14449:     sub get_servers {
1.852     albertel 14450: 	&load_hosts_tab() if (!$loaded);
                   14451: 
1.841     albertel 14452: 	my ($domain,$type) = @_;
                   14453: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14454: 	                                          : %hostname;
                   14455: 	my %result;
1.842     albertel 14456: 	if (ref($domain) eq 'ARRAY') {
                   14457: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14458: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14459: 		    $result{$host} = $hostname;
                   14460: 		}
                   14461: 	    }
                   14462: 	} else {
                   14463: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14464: 		if ($hostdom{$host} eq $domain) {
                   14465: 		    $result{$host} = $hostname;
                   14466: 		}
1.841     albertel 14467: 	    }
                   14468: 	}
                   14469: 	return %result;
                   14470:     }
1.845     albertel 14471: 
1.1062    droeschl 14472:     sub get_unique_servers {
                   14473:         my %unique = reverse &get_servers(@_);
                   14474: 	return reverse %unique;
                   14475:     }
                   14476: 
1.844     albertel 14477:     sub host_domain {
1.852     albertel 14478: 	&load_hosts_tab() if (!$loaded);
                   14479: 
1.844     albertel 14480: 	my ($lonid) = @_;
                   14481: 	return $hostdom{$lonid};
                   14482:     }
                   14483: 
1.841     albertel 14484:     sub all_domains {
1.852     albertel 14485: 	&load_hosts_tab() if (!$loaded);
                   14486: 
1.841     albertel 14487: 	my %seen;
                   14488: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14489: 	return @uniq;
                   14490:     }
1.1074    raeburn  14491: 
                   14492:     sub internet_dom {
                   14493:         &load_hosts_tab() if (!$loaded);
                   14494: 
                   14495:         my ($lonid) = @_;
                   14496:         return $internetdom{$lonid};
                   14497:     }
1.1107    raeburn  14498: 
                   14499:     sub is_LC_dns {
                   14500:         &load_hosts_tab() if (!$loaded);
                   14501: 
                   14502:         my ($hostname) = @_;
                   14503:         return exists($LC_dns_serv{$hostname});
                   14504:     }
                   14505: 
1.1       albertel 14506: }
                   14507: 
1.847     albertel 14508: { 
                   14509:     my %iphost;
1.856     albertel 14510:     my %name_to_ip;
                   14511:     my %lonid_to_ip;
1.869     albertel 14512: 
1.847     albertel 14513:     sub get_hosts_from_ip {
                   14514: 	my ($ip) = @_;
                   14515: 	my %iphosts = &get_iphost();
                   14516: 	if (ref($iphosts{$ip})) {
                   14517: 	    return @{$iphosts{$ip}};
                   14518: 	}
                   14519: 	return;
1.839     albertel 14520:     }
1.864     albertel 14521:     
                   14522:     sub reset_hosts_ip_info {
                   14523: 	undef(%iphost);
                   14524: 	undef(%name_to_ip);
                   14525: 	undef(%lonid_to_ip);
                   14526:     }
1.856     albertel 14527: 
                   14528:     sub get_host_ip {
                   14529: 	my ($lonid) = @_;
                   14530: 	if (exists($lonid_to_ip{$lonid})) {
                   14531: 	    return $lonid_to_ip{$lonid};
                   14532: 	}
                   14533: 	my $name=&hostname($lonid);
                   14534:    	my $ip = gethostbyname($name);
                   14535: 	return if (!$ip || length($ip) ne 4);
                   14536: 	$ip=inet_ntoa($ip);
                   14537: 	$name_to_ip{$name}   = $ip;
                   14538: 	$lonid_to_ip{$lonid} = $ip;
                   14539: 	return $ip;
                   14540:     }
1.847     albertel 14541:     
                   14542:     sub get_iphost {
1.1293    raeburn  14543: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14544: 
1.869     albertel 14545: 	if (!$ignore_cache) {
                   14546: 	    if (%iphost) {
                   14547: 		return %iphost;
                   14548: 	    }
                   14549: 	    my ($ip_info,$cached)=
                   14550: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14551: 	    if ($cached) {
                   14552: 		%iphost      = %{$ip_info->[0]};
                   14553: 		%name_to_ip  = %{$ip_info->[1]};
                   14554: 		%lonid_to_ip = %{$ip_info->[2]};
                   14555: 		return %iphost;
                   14556: 	    }
                   14557: 	}
1.894     albertel 14558: 
                   14559: 	# get yesterday's info for fallback
                   14560: 	my %old_name_to_ip;
                   14561: 	my ($ip_info,$cached)=
                   14562: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14563: 	if ($cached) {
                   14564: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14565: 	}
                   14566: 
1.1293    raeburn  14567: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14568: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14569: 	    my $ip;
                   14570: 	    if (!exists($name_to_ip{$name})) {
                   14571: 		$ip = gethostbyname($name);
                   14572: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14573: 		    if (defined($old_name_to_ip{$name})) {
                   14574: 			$ip = $old_name_to_ip{$name};
                   14575: 			&logthis("Can't find $name defaulting to old $ip");
                   14576: 		    } else {
                   14577: 			&logthis("Name $name no IP found");
                   14578: 			next;
                   14579: 		    }
                   14580: 		} else {
                   14581: 		    $ip=inet_ntoa($ip);
1.847     albertel 14582: 		}
                   14583: 		$name_to_ip{$name} = $ip;
                   14584: 	    } else {
                   14585: 		$ip = $name_to_ip{$name};
1.653     albertel 14586: 	    }
1.888     albertel 14587: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14588: 		$lonid_to_ip{$id} = $ip;
                   14589: 	    }
                   14590: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14591: 	}
1.1293    raeburn  14592:         unless ($nocache) {
                   14593: 	    &do_cache_new('iphost','iphost',
                   14594: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14595: 		          48*60*60);
                   14596:         }
1.869     albertel 14597: 
1.847     albertel 14598: 	return %iphost;
1.598     albertel 14599:     }
                   14600: 
1.992     raeburn  14601:     #
                   14602:     #  Given a DNS returns the loncapa host name for that DNS 
                   14603:     # 
                   14604:     sub host_from_dns {
                   14605:         my ($dns) = @_;
                   14606:         my @hosts;
                   14607:         my $ip;
                   14608: 
1.993     raeburn  14609:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14610:             $ip = $name_to_ip{$dns};
                   14611:         }
                   14612:         if (!$ip) {
                   14613:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14614:             if (length($ip) == 4) { 
                   14615: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14616:             }
                   14617:         }
                   14618:         if ($ip) {
                   14619: 	    @hosts = get_hosts_from_ip($ip);
                   14620: 	    return $hosts[0];
                   14621:         }
                   14622:         return undef;
1.986     foxr     14623:     }
1.992     raeburn  14624: 
1.1074    raeburn  14625:     sub get_internet_names {
                   14626:         my ($lonid) = @_;
                   14627:         return if ($lonid eq '');
                   14628:         my ($idnref,$cached)=
                   14629:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14630:         if ($cached) {
                   14631:             return $idnref;
                   14632:         }
                   14633:         my $ip = &get_host_ip($lonid);
                   14634:         my @hosts = &get_hosts_from_ip($ip);
                   14635:         my %iphost = &get_iphost();
                   14636:         my (@idns,%seen);
                   14637:         foreach my $id (@hosts) {
                   14638:             my $dom = &host_domain($id);
                   14639:             my $prim_id = &domain($dom,'primary');
                   14640:             my $prim_ip = &get_host_ip($prim_id);
                   14641:             next if ($seen{$prim_ip});
                   14642:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14643:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14644:                     my $intdom = &internet_dom($id);
                   14645:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14646:                         push(@idns,$intdom);
                   14647:                     }
                   14648:                 }
                   14649:             }
                   14650:             $seen{$prim_ip} = 1;
                   14651:         }
1.1219    raeburn  14652:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14653:     }
                   14654: 
1.986     foxr     14655: }
                   14656: 
1.1079    raeburn  14657: sub all_loncaparevs {
1.1249    raeburn  14658:     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  14659: }
                   14660: 
1.1227    raeburn  14661: # ---------------------------------------------------------- Read loncaparev table
                   14662: {
                   14663:     sub load_loncaparevs { 
                   14664:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14665:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14666:                 while (my $configline=<$config>) {
                   14667:                     chomp($configline);
                   14668:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14669:                     $loncaparevs{$hostid}=$loncaparev;
                   14670:                 }
                   14671:                 close($config);
                   14672:             }
                   14673:         }
                   14674:     }
                   14675: }
                   14676: 
                   14677: # ---------------------------------------------------------- Read serverhostID table
                   14678: {
                   14679:     sub load_serverhomeIDs {
                   14680:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14681:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14682:                 while (my $configline=<$config>) {
                   14683:                     chomp($configline);
                   14684:                     my ($name,$id)=split(/:/,$configline);
                   14685:                     $serverhomeIDs{$name}=$id;
                   14686:                 }
                   14687:                 close($config);
                   14688:             }
                   14689:         }
                   14690:     }
                   14691: }
                   14692: 
                   14693: 
1.862     albertel 14694: BEGIN {
                   14695: 
                   14696: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14697:     unless ($readit) {
                   14698: {
                   14699:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14700:     %perlvar = (%perlvar,%{$configvars});
                   14701: }
                   14702: 
                   14703: 
1.1       albertel 14704: # ------------------------------------------------------ Read spare server file
                   14705: {
1.1359    raeburn  14706:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14707: 
                   14708:     while (my $configline=<$config>) {
                   14709:        chomp($configline);
1.284     matthew  14710:        if ($configline) {
1.784     albertel 14711: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14712: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14713: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14714:        }
                   14715:     }
1.448     albertel 14716:     close($config);
1.1       albertel 14717: }
1.11      www      14718: # ------------------------------------------------------------ Read permissions
                   14719: {
1.1359    raeburn  14720:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14721: 
                   14722:     while (my $configline=<$config>) {
1.448     albertel 14723: 	chomp($configline);
                   14724: 	if ($configline) {
                   14725: 	    my ($role,$perm)=split(/ /,$configline);
                   14726: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14727: 	}
1.11      www      14728:     }
1.448     albertel 14729:     close($config);
1.11      www      14730: }
                   14731: 
                   14732: # -------------------------------------------- Read plain texts for permissions
                   14733: {
1.1359    raeburn  14734:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14735: 
                   14736:     while (my $configline=<$config>) {
1.448     albertel 14737: 	chomp($configline);
                   14738: 	if ($configline) {
1.742     raeburn  14739: 	    my ($short,@plain)=split(/:/,$configline);
                   14740:             %{$prp{$short}} = ();
                   14741: 	    if (@plain > 0) {
                   14742:                 $prp{$short}{'std'} = $plain[0];
                   14743:                 for (my $i=1; $i<@plain; $i++) {
                   14744:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14745:                 }
                   14746:             }
1.448     albertel 14747: 	}
1.135     www      14748:     }
1.448     albertel 14749:     close($config);
1.135     www      14750: }
                   14751: 
                   14752: # ---------------------------------------------------------- Read package table
                   14753: {
1.1359    raeburn  14754:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14755: 
                   14756:     while (my $configline=<$config>) {
1.483     albertel 14757: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14758: 	chomp($configline);
                   14759: 	my ($short,$plain)=split(/:/,$configline);
                   14760: 	my ($pack,$name)=split(/\&/,$short);
                   14761: 	if ($plain ne '') {
                   14762: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14763: 	    $packagetab{$short}=$plain; 
                   14764: 	}
1.11      www      14765:     }
1.448     albertel 14766:     close($config);
1.329     matthew  14767: }
                   14768: 
1.1073    raeburn  14769: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14770: 
                   14771: &load_loncaparevs();
1.1073    raeburn  14772: 
1.1074    raeburn  14773: # ---------------------------------------------------------- Read serverhostID table
                   14774: 
1.1227    raeburn  14775: &load_serverhomeIDs();
                   14776: 
                   14777: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14778: {
                   14779:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14780:     if (-e $file) {
                   14781:         my $parser = HTML::LCParser->new($file);
                   14782:         while (my $token = $parser->get_token()) {
                   14783:             if ($token->[0] eq 'S') {
                   14784:                 my $item = $token->[1];
                   14785:                 my $name = $token->[2]{'name'};
                   14786:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14787:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14788:                 my $namematch = $token->[2]{'namematch'};
                   14789:                 if ($item eq 'parameter') {
                   14790:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14791:                         my $release = $parser->get_text();
                   14792:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14793:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14794:                     }
                   14795:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14796:                     my $release = $parser->get_text();
                   14797:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14798:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14799:                 }
                   14800:             }
                   14801:         }
                   14802:     }
1.1073    raeburn  14803: }
                   14804: 
1.1138    raeburn  14805: # ---------------------------------------------------------- Read managers table
                   14806: {
                   14807:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14808:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14809:             while (my $configline=<$config>) {
                   14810:                 chomp($configline);
                   14811:                 next if ($configline =~ /^\#/);
                   14812:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14813:                     $managerstab{$configline} = 1;
                   14814:                 }
                   14815:             }
                   14816:             close($config);
                   14817:         }
                   14818:     }
                   14819: }
                   14820: 
1.329     matthew  14821: # ------------- set up temporary directory
                   14822: {
1.1117    foxr     14823:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14824: 
1.11      www      14825: }
                   14826: 
1.1405    raeburn  14827: # ------------- set default texengine (domain default overrides this)
                   14828: {
                   14829:     $deftex = LONCAPA::texengine();
                   14830: }
                   14831: 
1.794     albertel 14832: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14833: 				'compress_threshold'=> 20_000,
                   14834:  			        });
1.185     www      14835: 
1.281     www      14836: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14837: $dumpcount=0;
1.958     www      14838: $locknum=0;
1.22      www      14839: 
1.163     harris41 14840: &logtouch();
1.672     albertel 14841: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14842: $readit=1;
1.564     albertel 14843:     {
                   14844: 	use integer;
                   14845: 	my $test=(2**32)+1;
1.568     albertel 14846: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14847: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14848:     }
1.195     www      14849: }
1.1       albertel 14850: }
1.179     www      14851: 
1.1       albertel 14852: 1;
1.191     harris41 14853: __END__
                   14854: 
1.243     albertel 14855: =pod
                   14856: 
1.191     harris41 14857: =head1 NAME
                   14858: 
1.243     albertel 14859: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14860: 
                   14861: =head1 SYNOPSIS
                   14862: 
1.243     albertel 14863: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14864: 
                   14865:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14866: 
1.243     albertel 14867: Common parameters:
                   14868: 
                   14869: =over 4
                   14870: 
                   14871: =item *
                   14872: 
                   14873: $uname : an internal username (if $cname expecting a course Id specifically)
                   14874: 
                   14875: =item *
                   14876: 
                   14877: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14878: 
                   14879: =item *
                   14880: 
                   14881: $symb : a resource instance identifier
                   14882: 
                   14883: =item *
                   14884: 
                   14885: $namespace : the name of a .db file that contains the data needed or
                   14886: being set.
                   14887: 
                   14888: =back
                   14889: 
1.394     bowersj2 14890: =head1 OVERVIEW
1.191     harris41 14891: 
1.394     bowersj2 14892: lonnet provides subroutines which interact with the
                   14893: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14894: about classes, users, and resources.
1.243     albertel 14895: 
                   14896: For many of these objects you can also use this to store data about
                   14897: them or modify them in various ways.
1.191     harris41 14898: 
1.394     bowersj2 14899: =head2 Symbs
1.191     harris41 14900: 
1.394     bowersj2 14901: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14902: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14903: map, the resource number of the resource in the map, and the URL of
                   14904: the resource itself. The latter is somewhat redundant, but might help
                   14905: if maps change.
                   14906: 
                   14907: An example is
                   14908: 
                   14909:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14910: 
                   14911: The respective map entry is
                   14912: 
                   14913:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14914:   title="Problem 2">
                   14915:  </resource>
                   14916: 
                   14917: Symbs are used by the random number generator, as well as to store and
                   14918: restore data specific to a certain instance of for example a problem.
                   14919: 
                   14920: =head2 Storing And Retrieving Data
                   14921: 
                   14922: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14923: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14924: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14925: is is the non-critical message twin of cstore. These functions are for
                   14926: handlers to store a perl hash to a user's permanent data space in an
                   14927: easy manner, and to retrieve it again on another call. It is expected
                   14928: that a handler would use this once at the beginning to retrieve data,
                   14929: and then again once at the end to send only the new data back.
                   14930: 
                   14931: The data is stored in the user's data directory on the user's
                   14932: homeserver under the ID of the course.
                   14933: 
                   14934: The hash that is returned by restore will have all of the previous
                   14935: value for all of the elements of the hash.
                   14936: 
                   14937: Example:
                   14938: 
                   14939:  #creating a hash
                   14940:  my %hash;
                   14941:  $hash{'foo'}='bar';
                   14942: 
                   14943:  #storing it
                   14944:  &Apache::lonnet::cstore(\%hash);
                   14945: 
                   14946:  #changing a value
                   14947:  $hash{'foo'}='notbar';
                   14948: 
                   14949:  #adding a new value
                   14950:  $hash{'bar'}='foo';
                   14951:  &Apache::lonnet::cstore(\%hash);
                   14952: 
                   14953:  #retrieving the hash
                   14954:  my %history=&Apache::lonnet::restore();
                   14955: 
                   14956:  #print the hash
                   14957:  foreach my $key (sort(keys(%history))) {
                   14958:    print("\%history{$key} = $history{$key}");
                   14959:  }
                   14960: 
                   14961: Will print out:
1.191     harris41 14962: 
1.394     bowersj2 14963:  %history{1:foo} = bar
                   14964:  %history{1:keys} = foo:timestamp
                   14965:  %history{1:timestamp} = 990455579
                   14966:  %history{2:bar} = foo
                   14967:  %history{2:foo} = notbar
                   14968:  %history{2:keys} = foo:bar:timestamp
                   14969:  %history{2:timestamp} = 990455580
                   14970:  %history{bar} = foo
                   14971:  %history{foo} = notbar
                   14972:  %history{timestamp} = 990455580
                   14973:  %history{version} = 2
                   14974: 
                   14975: Note that the special hash entries C<keys>, C<version> and
                   14976: C<timestamp> were added to the hash. C<version> will be equal to the
                   14977: total number of versions of the data that have been stored. The
                   14978: C<timestamp> attribute will be the UNIX time the hash was
                   14979: stored. C<keys> is available in every historical section to list which
                   14980: keys were added or changed at a specific historical revision of a
                   14981: hash.
                   14982: 
                   14983: B<Warning>: do not store the hash that restore returns directly. This
                   14984: will cause a mess since it will restore the historical keys as if the
                   14985: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14986: 
1.394     bowersj2 14987: Calling convention:
1.191     harris41 14988: 
1.1225    raeburn  14989:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14990:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14991: 
1.394     bowersj2 14992: For more detailed information, see lonnet specific documentation.
1.191     harris41 14993: 
1.394     bowersj2 14994: =head1 RETURN MESSAGES
1.191     harris41 14995: 
1.394     bowersj2 14996: =over 4
1.191     harris41 14997: 
1.394     bowersj2 14998: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14999: 
1.394     bowersj2 15000: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15001: when the connection is brought back up
1.191     harris41 15002: 
1.394     bowersj2 15003: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15004: for later delivery
1.191     harris41 15005: 
1.967     bisitz   15006: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15007: 
1.394     bowersj2 15008: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15009: that was requested
1.191     harris41 15010: 
1.243     albertel 15011: =back
1.191     harris41 15012: 
1.243     albertel 15013: =head1 PUBLIC SUBROUTINES
1.191     harris41 15014: 
1.243     albertel 15015: =head2 Session Environment Functions
1.191     harris41 15016: 
1.243     albertel 15017: =over 4
1.191     harris41 15018: 
1.394     bowersj2 15019: =item * 
                   15020: X<appenv()>
1.949     raeburn  15021: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15022: the user envirnoment file, and will be restored for each access this
1.620     albertel 15023: user makes during this session, also modifies the %env for the current
1.949     raeburn  15024: process. Optional rolesarrayref - if defined contains a reference to an array
                   15025: of roles which are exempt from the restriction on modifying user.role entries 
                   15026: in the user's environment.db and in %env.    
1.191     harris41 15027: 
                   15028: =item *
1.394     bowersj2 15029: X<delenv()>
1.987     raeburn  15030: B<delenv($delthis,$regexp)>: removes all items from the session
                   15031: environment file that begin with $delthis. If the 
                   15032: optional second arg - $regexp - is true, $delthis is treated as a 
                   15033: regular expression, otherwise \Q$delthis\E is used. 
                   15034: The values are also deleted from the current processes %env.
1.191     harris41 15035: 
1.795     albertel 15036: =item * get_env_multiple($name) 
                   15037: 
                   15038: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15039: values may be defined and end up as an array ref.
                   15040: 
                   15041: returns an array of values
                   15042: 
1.243     albertel 15043: =back
                   15044: 
                   15045: =head2 User Information
1.191     harris41 15046: 
1.243     albertel 15047: =over 4
1.191     harris41 15048: 
                   15049: =item *
1.394     bowersj2 15050: X<queryauthenticate()>
                   15051: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15052: authentication scheme
                   15053: 
                   15054: =item *
1.394     bowersj2 15055: X<authenticate()>
1.1073    raeburn  15056: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15057: authenticate user from domain's lib servers (first use the current
                   15058: one). C<$upass> should be the users password.
1.1073    raeburn  15059: $checkdefauth is optional (value is 1 if a check should be made to
                   15060:    authenticate user using default authentication method, and allow
                   15061:    account creation if username does not have account in the domain).
                   15062: $clientcancheckhost is optional (value is 1 if checking whether the
                   15063:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15064: 
                   15065: =item *
1.394     bowersj2 15066: X<homeserver()>
                   15067: B<homeserver($uname,$udom)>: find the server which has
                   15068: the user's directory and files (there must be only one), this caches
                   15069: the answer, and also caches if there is a borken connection.
1.191     harris41 15070: 
                   15071: =item *
1.394     bowersj2 15072: X<idget()>
1.1300    raeburn  15073: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   15074: a list of student/employee IDs or clicker IDs
                   15075: (student/employee IDs are a unique resource in a domain, there must be 
                   15076: only 1 ID per username, and only 1 username per ID in a specific domain).
                   15077: clickerIDs are not necessarily unique, as students might share clickers.
                   15078: (returns hash: id=>name,id=>name)
1.191     harris41 15079: 
                   15080: =item *
1.394     bowersj2 15081: X<idrget()>
                   15082: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15083: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15084: 
                   15085: =item *
1.394     bowersj2 15086: X<idput()>
1.1300    raeburn  15087: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   15088: names and associated student/employee IDs or clicker IDs.
                   15089: 
                   15090: =item *
                   15091: X<iddel()>
                   15092: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15093: student/employee ID or clicker ID username look-ups from domain.
                   15094: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15095: If no $uhome is provided, it will be determined usig &homeserver()
                   15096: for each user.  If no $namespace is provided, the default is ids.
                   15097: 
                   15098: =item *
                   15099: X<updateclickers()>
                   15100: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15101: clicker ID-to-username look-ups in clickers.db on library server.
                   15102: Permitted actions are add or del (i.e., add or delete). The 
                   15103: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15104: value is an escaped comma-separated list of usernames (for whom the
                   15105: library server is the homeserver), who registered that particular ID.
                   15106: If $critical is true, the update will be sent via &critical, otherwise
                   15107: &reply() will be used.
1.191     harris41 15108: 
                   15109: =item *
1.394     bowersj2 15110: X<rolesinit()>
1.1169    droeschl 15111: B<rolesinit($udom,$username)>: get user privileges.
                   15112: returns user role, first access and timer interval hashes
1.243     albertel 15113: 
                   15114: =item *
1.1171    droeschl 15115: X<privileged()>
                   15116: B<privileged($username,$domain)>: returns a true if user has a
                   15117: privileged and active role (i.e. su or dc), false otherwise.
                   15118: 
                   15119: =item *
1.551     albertel 15120: X<getsection()>
                   15121: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15122: course $cname, return section name/number or '' for "not in course"
                   15123: and '-1' for "no section"
                   15124: 
                   15125: =item *
1.394     bowersj2 15126: X<userenvironment()>
                   15127: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15128: passed in @what from the requested user's environment, returns a hash
                   15129: 
1.858     raeburn  15130: =item * 
                   15131: X<userlog_query()>
1.859     albertel 15132: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15133: activity.log file. %filters defines filters applied when parsing the
                   15134: log file. These can be start or end timestamps, or the type of action
                   15135: - log to look for Login or Logout events, check for Checkin or
                   15136: Checkout, role for role selection. The response is in the form
                   15137: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15138: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15139: 
1.243     albertel 15140: =back
                   15141: 
                   15142: =head2 User Roles
                   15143: 
                   15144: =over 4
                   15145: 
                   15146: =item *
                   15147: 
1.1284    raeburn  15148: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15149: returns codes for allowed actions.
                   15150: 
                   15151: The first argument is required, all others are optional.
                   15152: 
                   15153: $priv is the privilege being checked.
                   15154: $uri contains additional information about what is being checked for access (e.g.,
                   15155: URL, course ID etc.). 
                   15156: $symb is the unique resource instance identifier in a course; if needed,
                   15157: but not provided, it will be retrieved via a call to &symbread(). 
                   15158: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15159: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15160: files).
                   15161: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15162: prevents recursive calls to &allowed.
                   15163: 
1.243     albertel 15164:  F: full access
                   15165:  U,I,K: authentication modes (cxx only)
                   15166:  '': forbidden
                   15167:  1: user needs to choose course
                   15168:  2: browse allowed
1.766     albertel 15169:  A: passphrase authentication needed
1.1284    raeburn  15170:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  15171:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15172: 
                   15173: =item *
                   15174: 
1.1192    raeburn  15175: constructaccess($url,$setpriv) : check for access to construction space URL
                   15176: 
                   15177: See if the owner domain and name in the URL match those in the
                   15178: expected environment.  If so, return three element list
                   15179: ($ownername,$ownerdomain,$ownerhome).
                   15180: 
                   15181: Otherwise return the null string.
                   15182: 
                   15183: If second argument 'setpriv' is true, it assigns the privileges,
                   15184: and returns the same three element list, unless the owner has
                   15185: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15186: in which case the null string is returned.
                   15187: 
                   15188: =item *
                   15189: 
1.1326    raeburn  15190: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15191: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15192: for system, domain, and course level. $uname and $udom are optional (current
                   15193: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15194: 
                   15195: =item *
                   15196: 
1.988     raeburn  15197: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15198: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15199: $type is Course (default) or Community.
1.988     raeburn  15200: If $forcedefault evaluates to true, text returned will be default 
                   15201: text for $type. Otherwise, if this is a course, the text returned 
                   15202: will be a custom name for the role (if defined in the course's 
                   15203: environment).  If no custom name is defined the default is returned.
                   15204:    
1.832     raeburn  15205: =item *
                   15206: 
1.1219    raeburn  15207: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15208: All arguments are optional. Returns a hash of a roles, either for
                   15209: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15210: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15211: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15212: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15213: For each key, value is set to colon-separated start and end times for
                   15214: the role.  If no username and domain are specified, will default to
1.934     raeburn  15215: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15216: of role statuses (active, future or previous), roles 
                   15217: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15218: to restrict the list of roles reported. If no array ref is 
                   15219: provided for types, will default to return only active roles.
1.834     albertel 15220: 
1.1195    raeburn  15221: =item *
                   15222: 
                   15223: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  15224: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   15225: 
                   15226: Additional optional arguments are: $type (if role checking is to be restricted 
                   15227: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  15228: available roles) or future (roles available in the future), and
                   15229: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  15230: have active Domain Coordinator role in course's domain or in additional
                   15231: domains (specified in 'Domains to check for privileged users' in course
                   15232: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15233: 
                   15234: =item *
                   15235: 
                   15236: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15237: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15238: $possdomains and $possroles are optional array refs -- to domains to check and
                   15239: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15240: users' roles.db to check for a dc or su role in any domain. This can be
                   15241: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15242: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15243: this then allows &privileged_by_domain() to be used, which caches the identity
                   15244: of privileged users, eliminating the need for repeated calls to &dump().
                   15245: 
                   15246: =item *
                   15247: 
                   15248: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15249: where the outer hash keys are domains specified in the $possdomains array ref,
                   15250: next inner hash keys are privileged roles specified in the $roles array ref,
                   15251: and the innermost hash contains key = value pairs for username:domain = end:start
                   15252: for active or future "privileged" users with that role in that domain. To avoid
                   15253: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15254: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  15255: 
1.243     albertel 15256: =back
                   15257: 
                   15258: =head2 User Modification
                   15259: 
                   15260: =over 4
                   15261: 
                   15262: =item *
                   15263: 
1.957     raeburn  15264: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15265: user for the level given by URL.  Optional start and end dates (leave empty
                   15266: string or zero for "no date")
1.191     harris41 15267: 
                   15268: =item *
                   15269: 
1.243     albertel 15270: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15271: change a users, password, possible return values are: ok,
                   15272: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15273: refused
1.191     harris41 15274: 
                   15275: =item *
                   15276: 
1.243     albertel 15277: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15278: 
                   15279: =item *
                   15280: 
1.1058    raeburn  15281: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15282:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15283: 
                   15284: will update user information (firstname,middlename,lastname,generation,
                   15285: permanentemail), and if forceid is true, student/employee ID also.
                   15286: A user's institutional affiliation(s) can also be updated.
                   15287: User information fields will not be overwritten with empty entries 
                   15288: unless the field is included in the $candelete array reference.
                   15289: This array is included when a single user is modified via "Manage Users",
                   15290: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15291: 
                   15292: =item *
                   15293: 
1.286     matthew  15294: modifystudent
                   15295: 
1.957     raeburn  15296: modify a student's enrollment and identification information.
1.1235    raeburn  15297: The course id is resolved based on the current user's environment.  
                   15298: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15299: associated with a course.
                   15300: 
1.297     matthew  15301: This call is essentially a wrapper for lonnet::modifyuser and
                   15302: lonnet::modify_student_enrollment
1.286     matthew  15303: 
                   15304: Inputs: 
                   15305: 
                   15306: =over 4
                   15307: 
1.957     raeburn  15308: =item B<$udom> Student's loncapa domain
1.286     matthew  15309: 
1.957     raeburn  15310: =item B<$uname> Student's loncapa login name
1.286     matthew  15311: 
1.964     bisitz   15312: =item B<$uid> Student/Employee ID
1.286     matthew  15313: 
1.957     raeburn  15314: =item B<$umode> Student's authentication mode
1.286     matthew  15315: 
1.957     raeburn  15316: =item B<$upass> Student's password
1.286     matthew  15317: 
1.957     raeburn  15318: =item B<$first> Student's first name
1.286     matthew  15319: 
1.957     raeburn  15320: =item B<$middle> Student's middle name
1.286     matthew  15321: 
1.957     raeburn  15322: =item B<$last> Student's last name
1.286     matthew  15323: 
1.957     raeburn  15324: =item B<$gene> Student's generation
1.286     matthew  15325: 
1.957     raeburn  15326: =item B<$usec> Student's section in course
1.286     matthew  15327: 
                   15328: =item B<$end> Unix time of the roles expiration
                   15329: 
                   15330: =item B<$start> Unix time of the roles start date
                   15331: 
                   15332: =item B<$forceid> If defined, allow $uid to be changed
                   15333: 
                   15334: =item B<$desiredhome> server to use as home server for student
                   15335: 
1.957     raeburn  15336: =item B<$email> Student's permanent e-mail address
                   15337: 
                   15338: =item B<$type> Type of enrollment (auto or manual)
                   15339: 
1.963     raeburn  15340: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15341: 
                   15342: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15343: 
1.963     raeburn  15344: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15345: 
1.963     raeburn  15346: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15347: 
1.1216    raeburn  15348: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15349: 
                   15350: =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  15351: 
1.286     matthew  15352: =back
1.297     matthew  15353: 
                   15354: =item *
                   15355: 
                   15356: modify_student_enrollment
                   15357: 
1.1235    raeburn  15358: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15359: 'role.request.course' must be defined for this function to proceed.
                   15360: 
                   15361: Inputs:
                   15362: 
                   15363: =over 4
                   15364: 
1.1235    raeburn  15365: =item $udom, student's domain
1.297     matthew  15366: 
1.1235    raeburn  15367: =item $uname, student's name
1.297     matthew  15368: 
1.1235    raeburn  15369: =item $uid, student's user id
1.297     matthew  15370: 
1.1235    raeburn  15371: =item $first, student's first name
1.297     matthew  15372: 
                   15373: =item $middle
                   15374: 
                   15375: =item $last
                   15376: 
                   15377: =item $gene
                   15378: 
                   15379: =item $usec
                   15380: 
                   15381: =item $end
                   15382: 
                   15383: =item $start
                   15384: 
1.957     raeburn  15385: =item $type
                   15386: 
                   15387: =item $locktype
                   15388: 
                   15389: =item $cid
                   15390: 
                   15391: =item $selfenroll
                   15392: 
                   15393: =item $context
                   15394: 
1.1216    raeburn  15395: =item $credits, number of credits student will earn from this class
                   15396: 
1.1314    raeburn  15397: =item $instsec, institutional course section code for student
                   15398: 
1.297     matthew  15399: =back
                   15400: 
1.191     harris41 15401: 
                   15402: =item *
                   15403: 
1.243     albertel 15404: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15405: custom role; give a custom role to a user for the level given by URL.  Specify
                   15406: name and domain of role author, and role name
1.191     harris41 15407: 
                   15408: =item *
                   15409: 
1.243     albertel 15410: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15411: 
                   15412: =item *
                   15413: 
1.243     albertel 15414: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15415: 
                   15416: =back
                   15417: 
                   15418: =head2 Course Infomation
                   15419: 
                   15420: =over 4
1.191     harris41 15421: 
                   15422: =item *
                   15423: 
1.1118    foxr     15424: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15425: specified course id, including all environment settings for the
                   15426: course, the description of the course will be in the hash under the
                   15427: key 'description'
1.191     harris41 15428: 
1.1118    foxr     15429: $options is an optional parameter that if supplied is a hash reference that controls
                   15430: what how this function works.  It has the following key/values:
                   15431: 
                   15432: =over 4
                   15433: 
                   15434: =item freshen_cache
                   15435: 
                   15436: If defined, and the environment cache for the course is valid, it is 
                   15437: returned in the returned hash.
                   15438: 
                   15439: =item one_time
                   15440: 
                   15441: If defined, the last cache time is set to _now_
                   15442: 
                   15443: =item user
                   15444: 
                   15445: If defined, the supplied username is used instead of the current user.
                   15446: 
                   15447: 
                   15448: =back
                   15449: 
1.191     harris41 15450: =item *
                   15451: 
1.624     albertel 15452: resdata($name,$domain,$type,@which) : request for current parameter
                   15453: setting for a specific $type, where $type is either 'course' or 'user',
                   15454: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15455: answers for 10 minutes.
1.243     albertel 15456: 
1.877     foxr     15457: =item *
                   15458: 
                   15459: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15460: data base, returning a hash that is keyed by the resource name and has
                   15461: values that are the resource value.  I believe that the timestamps and
                   15462: versions are also returned.
                   15463: 
1.1236    raeburn  15464: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15465: supplemental content area. This routine caches the number of files for 
                   15466: 10 minutes.
                   15467: 
1.243     albertel 15468: =back
                   15469: 
                   15470: =head2 Course Modification
                   15471: 
                   15472: =over 4
1.191     harris41 15473: 
                   15474: =item *
                   15475: 
1.243     albertel 15476: writecoursepref($courseid,%prefs) : write preferences (environment
                   15477: database) for a course
1.191     harris41 15478: 
                   15479: =item *
                   15480: 
1.1011    raeburn  15481: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15482: 
                   15483: =item *
                   15484: 
1.1038    raeburn  15485: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15486: 
1.1167    droeschl 15487: =item *
                   15488: 
                   15489: is_course($courseid), is_course($cdom, $cnum)
                   15490: 
                   15491: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15492: two component version $cdom, $cnum. It checks if the specified course exists.
                   15493: 
                   15494: Returns:
                   15495:     undef if the course doesn't exist, otherwise
                   15496:     in scalar context the combined courseid.
                   15497:     in list context the two components of the course identifier, domain and 
                   15498:     courseid.    
                   15499: 
1.243     albertel 15500: =back
                   15501: 
1.1401    raeburn  15502: =head2 Bubblesheet Configuration
                   15503: 
                   15504: =over 4
                   15505: 
                   15506: =item *
                   15507: 
                   15508: get_scantron_config($which)
                   15509: 
                   15510: $which - the name of the configuration to parse from the file.
                   15511: 
                   15512: Parses and returns the bubblesheet configuration line selected as a
                   15513: hash of configuration file fields.
                   15514: 
                   15515: 
                   15516: Returns:
                   15517:     If the named configuration is not in the file, an empty
                   15518:     hash is returned.
                   15519: 
                   15520:     a hash with the fields
                   15521:       name         - internal name for the this configuration setup
                   15522:       description  - text to display to operator that describes this config
                   15523:       CODElocation - if 0 or the string 'none'
                   15524:                           - no CODE exists for this config
                   15525:                      if -1 || the string 'letter'
                   15526:                           - a CODE exists for this config and is
                   15527:                             a string of letters
                   15528:                      Unsupported value (but planned for future support)
                   15529:                           if a positive integer
                   15530:                                - The CODE exists as the first n items from
                   15531:                                  the question section of the form
                   15532:                           if the string 'number'
                   15533:                                - The CODE exists for this config and is
                   15534:                                  a string of numbers
                   15535:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15536:                      the CODE starts
                   15537:       CODElength  - length of the CODE
                   15538:       IDstart     - column where the student/employee ID starts
                   15539:       IDlength    - length of the student/employee ID info
                   15540:       Qstart      - column where the information from the bubbled
                   15541:                     'questions' start
                   15542:       Qlength     - number of columns comprising a single bubble line from
                   15543:                     the sheet. (usually either 1 or 10)
                   15544:       Qon         - either a single character representing the character used
                   15545:                     to signal a bubble was chosen in the positional setup, or
                   15546:                     the string 'letter' if the letter of the chosen bubble is
                   15547:                     in the final, or 'number' if a number representing the
                   15548:                     chosen bubble is in the file (1->A 0->J)
                   15549:       Qoff        - the character used to represent that a bubble was
                   15550:                     left blank
                   15551:       PaperID     - if the scanning process generates a unique number for each
                   15552:                     sheet scanned the column that this ID number starts in
                   15553:       PaperIDlength - number of columns that comprise the unique ID number
                   15554:                       for the sheet of paper
                   15555:       FirstName   - column that the first name starts in
                   15556:       FirstNameLength - number of columns that the first name spans
                   15557:       LastName    - column that the last name starts in
                   15558:       LastNameLength - number of columns that the last name spans
                   15559:       BubblesPerRow - number of bubbles available in each row used to
                   15560:                       bubble an answer. (If not specified, 10 assumed).
                   15561: 
                   15562: 
                   15563: =item *
                   15564: 
                   15565: get_scantronformat_file($cdom)
                   15566: 
                   15567: $cdom - the course's domain (optional); if not supplied, uses
                   15568: domain for current $env{'request.course.id'}.
                   15569: 
                   15570: Returns an array containing lines from the scantron format file for
                   15571: the domain of the course.
                   15572: 
                   15573: If a url for a custom.tab file is listed in domain's configuration.db,
                   15574: lines are from this file.
                   15575: 
                   15576: Otherwise, if a default.tab has been published in RES space by the
                   15577: domainconfig user, lines are from this file.
                   15578: 
                   15579: Otherwise, fall back to getting lines from the legacy file on the
                   15580: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15581: 
                   15582: =back
                   15583: 
1.243     albertel 15584: =head2 Resource Subroutines
                   15585: 
                   15586: =over 4
1.191     harris41 15587: 
                   15588: =item *
                   15589: 
1.243     albertel 15590: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15591: 
                   15592: =item *
                   15593: 
1.243     albertel 15594: repcopy($filename) : subscribes to the requested file, and attempts to
                   15595: replicate from the owning library server, Might return
1.607     raeburn  15596: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15597: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15598: resource. Expects the local filesystem pathname
                   15599: (/home/httpd/html/res/....)
                   15600: 
                   15601: =back
                   15602: 
                   15603: =head2 Resource Information
                   15604: 
                   15605: =over 4
1.191     harris41 15606: 
                   15607: =item *
                   15608: 
1.1228    raeburn  15609: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15610: and returns the value of a variety of different possible values,
                   15611: $varname should be a request string, and the other parameters can be
                   15612: used to specify who and what one is asking about. Ordinarily, $cid 
                   15613: does not need to be specified, as it is retrived from 
                   15614: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15615: within lonuserstate::loadmap() when initializing a course, before
                   15616: $env{'request.course.id'} has been set, so it needs to be provided
                   15617: in that one case.
1.243     albertel 15618: 
                   15619: Possible values for $varname are environment.lastname (or other item
                   15620: from the envirnment hash), user.name (or someother aspect about the
                   15621: user), resource.0.maxtries (or some other part and parameter of a
                   15622: resource)
1.204     albertel 15623: 
                   15624: =item *
                   15625: 
1.243     albertel 15626: directcondval($number) : get current value of a condition; reads from a state
                   15627: string
1.204     albertel 15628: 
                   15629: =item *
                   15630: 
1.243     albertel 15631: condval($condidx) : value of condition index based on state
1.204     albertel 15632: 
                   15633: =item *
                   15634: 
1.1362    raeburn  15635: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15636: resource's metadata, $what should be either a specific key, or either
                   15637: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15638: packages that this resource currently uses, the last 3 arguments are 
                   15639: only used internally for recursive metadata.
                   15640: 
                   15641: the toolsymb is only used where the uri is for an external tool (for which
                   15642: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15643: 
1.1371    raeburn  15644: this function automatically caches all requests except any made recursively
                   15645: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15646: defined).
1.191     harris41 15647: 
                   15648: =item *
                   15649: 
1.243     albertel 15650: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15651: network of library servers; returns file handle of where SQL and regex results
                   15652: will be stored for query
1.191     harris41 15653: 
                   15654: =item *
                   15655: 
1.1282    raeburn  15656: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15657: return symbolic list entry (all arguments optional). 
                   15658: 
                   15659: Args: filename is the filename (including path) for the file for which a symb 
                   15660: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15661: to check access status if more than one resource was found in the bighash 
                   15662: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15663: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15664: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15665: cause possible symbs to be checked to determine if they are subject to content
                   15666: blocking, if so they will not be included as possible symbs; possibles is a
                   15667: ref to a hash, which, as a side effect, will be populated with all possible 
                   15668: symbs (content blocking not tested).
                   15669:  
1.243     albertel 15670: returns the data handle
1.191     harris41 15671: 
                   15672: =item *
                   15673: 
1.1190    raeburn  15674: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15675: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15676: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15677: on failure, user must be in a course, as it assumes the existence of
                   15678: the course initial hash, and uses $env('request.course.id'}.  The third
                   15679: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15680: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15681: encrypted; otherwise it will be null.  
1.191     harris41 15682: 
                   15683: =item *
                   15684: 
1.243     albertel 15685: symbclean($symb) : removes versions numbers from a symb, returns the
                   15686: cleaned symb
1.191     harris41 15687: 
                   15688: =item *
                   15689: 
1.243     albertel 15690: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15691: course map, user must be in a course for it to work.
1.191     harris41 15692: 
                   15693: =item *
                   15694: 
1.243     albertel 15695: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15696: 
                   15697: =item *
                   15698: 
1.243     albertel 15699: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15700: a random seed, all arguments are optional, if they aren't sent it uses the
                   15701: environment to derive them. Note: if symb isn't sent and it can't get one
                   15702: from &symbread it will use the current time as its return value
1.191     harris41 15703: 
                   15704: =item *
                   15705: 
1.243     albertel 15706: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15707: unfakeable, receipt
1.191     harris41 15708: 
                   15709: =item *
                   15710: 
1.620     albertel 15711: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15712: 
                   15713: =item *
                   15714: 
1.243     albertel 15715: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15716: 
                   15717: =item *
                   15718: 
1.243     albertel 15719: 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 15720: 
                   15721: =item *
                   15722: 
1.243     albertel 15723: 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 15724: 
                   15725: =item *
                   15726: 
1.243     albertel 15727: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15728: 
                   15729: =item *
                   15730: 
1.243     albertel 15731: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15732: forcing spreadsheet to reevaluate the resource scores next time.
                   15733: 
1.1195    raeburn  15734: =item * 
                   15735: 
1.1196    raeburn  15736: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15737: when viewing in course context.
1.1195    raeburn  15738: 
1.1196    raeburn  15739:  input: six args -- filename (decluttered), course number, course domain,
                   15740:                     url, symb (if registered) and group (if this is a 
                   15741:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15742: 
1.1196    raeburn  15743:  output: array of five scalars --
1.1195    raeburn  15744:          $cfile -- url for file editing if editable on current server
                   15745:          $home -- homeserver of resource (i.e., for author if published,
                   15746:                                           or course if uploaded.).
                   15747:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15748:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15749:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15750: 
                   15751: =item *
                   15752: 
                   15753: is_course_upload($file,$cnum,$cdom)
                   15754: 
                   15755: Used in course context to determine if current file was uploaded to 
                   15756: the course (i.e., would be found in /userfiles/docs on the course's 
                   15757: homeserver.
                   15758: 
                   15759:   input: 3 args -- filename (decluttered), course number and course domain.
                   15760:   output: boolean -- 1 if file was uploaded.
                   15761: 
1.243     albertel 15762: =back
                   15763: 
                   15764: =head2 Storing/Retreiving Data
                   15765: 
                   15766: =over 4
1.191     harris41 15767: 
                   15768: =item *
                   15769: 
1.1269    raeburn  15770: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15771: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15772: the remaining args aren't required and if they aren't passed or are '' they will
                   15773: be derived from the env (with the exception of $laststore, which is an 
                   15774: optional arg used when a user's submission is stored in grading).
                   15775: $laststore is $version=$timestamp, where $version is the most recent version
                   15776: number retrieved for the corresponding $symb in the $namespace db file, and
                   15777: $timestamp is the timestamp for that transaction (UNIX time).
                   15778: $laststore is currently only passed when cstore() is called by 
                   15779: structuretags::finalize_storage().
1.191     harris41 15780: 
                   15781: =item *
                   15782: 
1.1269    raeburn  15783: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15784: but uses critical subroutine
1.191     harris41 15785: 
                   15786: =item *
                   15787: 
1.243     albertel 15788: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15789: all args are optional
1.191     harris41 15790: 
                   15791: =item *
                   15792: 
1.717     albertel 15793: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15794: dumps the complete (or key matching regexp) namespace into a hash
                   15795: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15796: normally &store()ed into
                   15797: 
                   15798: $range should be either an integer '100' (give me the first 100
                   15799:                                            matching records)
                   15800:               or be  two integers sperated by a - with no spaces
                   15801:                  '30-50' (give me the 30th through the 50th matching
                   15802:                           records)
                   15803: 
                   15804: 
                   15805: =item *
                   15806: 
1.1269    raeburn  15807: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15808: replaces a &store() version of data with a replacement set of data
                   15809: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15810: reference. If $tolog is true, the transaction is logged in the courselog
                   15811: with an action=PUTSTORE.
1.717     albertel 15812: 
                   15813: =item *
                   15814: 
1.243     albertel 15815: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15816: works very similar to store/cstore, but all data is stored in a
                   15817: temporary location and can be reset using tmpreset, $storehash should
                   15818: be a hash reference, returns nothing on success
1.191     harris41 15819: 
                   15820: =item *
                   15821: 
1.243     albertel 15822: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15823: similar to restore, but all data is stored in a temporary location and
                   15824: can be reset using tmpreset. Returns a hash of values on success,
                   15825: error string otherwise.
1.191     harris41 15826: 
                   15827: =item *
                   15828: 
1.243     albertel 15829: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15830: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15831: 
                   15832: =item *
                   15833: 
1.243     albertel 15834: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15835: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15836: 
                   15837: =item *
                   15838: 
1.243     albertel 15839: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15840: namesp ($udom and $uname are optional)
1.191     harris41 15841: 
                   15842: =item *
                   15843: 
1.702     albertel 15844: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15845: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15846: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15847: 
1.702     albertel 15848: $range should be either an integer '100' (give me the first 100
                   15849:                                            matching records)
                   15850:               or be  two integers sperated by a - with no spaces
                   15851:                  '30-50' (give me the 30th through the 50th matching
                   15852:                           records)
1.449     matthew  15853: =item *
                   15854: 
                   15855: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15856: $store can be a scalar, an array reference, or if the amount to be 
                   15857: incremented is > 1, a hash reference.
                   15858: 
                   15859: ($udom and $uname are optional)
1.191     harris41 15860: 
                   15861: =item *
                   15862: 
1.243     albertel 15863: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15864: ($udom and $uname are optional)
1.191     harris41 15865: 
                   15866: =item *
                   15867: 
1.243     albertel 15868: cput($namespace,$storehash,$udom,$uname) : critical put
                   15869: ($udom and $uname are optional)
1.191     harris41 15870: 
                   15871: =item *
                   15872: 
1.748     albertel 15873: newput($namespace,$storehash,$udom,$uname) :
                   15874: 
                   15875: Attempts to store the items in the $storehash, but only if they don't
                   15876: currently exist, if this succeeds you can be certain that you have 
                   15877: successfully created a new key value pair in the $namespace db.
                   15878: 
                   15879: 
                   15880: Args:
                   15881:  $namespace: name of database to store values to
                   15882:  $storehash: hashref to store to the db
                   15883:  $udom: (optional) domain of user containing the db
                   15884:  $uname: (optional) name of user caontaining the db
                   15885: 
                   15886: Returns:
                   15887:  'ok' -> succeeded in storing all keys of $storehash
                   15888:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15889:                         least <key> already existed in the db (other
                   15890:                         requested keys may also already exist)
1.967     bisitz   15891:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15892:  'con_lost' -> unable to contact request server
                   15893:  'refused' -> action was not allowed by remote machine
                   15894: 
                   15895: 
                   15896: =item *
                   15897: 
1.243     albertel 15898: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15899: reference filled in from namesp (encrypts the return communication)
                   15900: ($udom and $uname are optional)
1.191     harris41 15901: 
                   15902: =item *
                   15903: 
1.243     albertel 15904: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15905: critical subroutine
                   15906: 
1.806     raeburn  15907: =item *
                   15908: 
1.860     raeburn  15909: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15910: array reference filled in from namespace found in domain level on either
                   15911: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15912: 
                   15913: =item *
                   15914: 
1.860     raeburn  15915: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15916: domain level either on specified domain server ($uhome) or primary domain 
                   15917: server ($udom and $uhome are optional)
1.806     raeburn  15918: 
1.943     raeburn  15919: =item * 
                   15920: 
1.1240    raeburn  15921: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15922: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15923: the target domain.
                   15924: 
                   15925: May also include additional key => value pairs for the following groups:
                   15926: 
                   15927: =over
                   15928: 
                   15929: =item
                   15930: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15931: 
                   15932: =over
                   15933: 
                   15934: =item defaultquota, authorquota
                   15935: 
                   15936: =back
                   15937: 
                   15938: =item
                   15939: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15940: portfolio for users).
                   15941: 
                   15942: =over
                   15943: 
                   15944: =item
                   15945: aboutme, blog, webdav, portfolio
                   15946: 
                   15947: =back
                   15948: 
                   15949: =item
                   15950: requestcourses: ability to request courses, and how requests are processed.
                   15951: 
                   15952: =over
                   15953: 
                   15954: =item
1.1305    raeburn  15955: official, unofficial, community, textbook, placement
1.1240    raeburn  15956: 
                   15957: =back
                   15958: 
                   15959: =item
                   15960: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15961: 
                   15962: =over
                   15963: 
                   15964: =item
1.1256    raeburn  15965: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15966: 
                   15967: =back
                   15968: 
                   15969: =item
                   15970: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15971: for course's uploaded content.
                   15972: 
                   15973: =over
                   15974: 
                   15975: =item
1.1246    raeburn  15976: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15977: communityquota, textbookquota, placementquota
1.1240    raeburn  15978: 
                   15979: =back
                   15980: 
                   15981: =item
                   15982: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15983: on your servers.
                   15984: 
                   15985: =over
                   15986: 
                   15987: =item 
                   15988: remotesessions, hostedsessions
                   15989: 
                   15990: =back
                   15991: 
                   15992: =back
                   15993: 
                   15994: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15995: utility to create a configuration.db file on a domain's primary library server 
                   15996: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15997: -- corresponding values are authentication type (internal, krb4, krb5,
                   15998: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15999: will be available. Values are retrieved from cache (if current), unless the
                   16000: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16001: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16002: 
                   16003: Typical usage:
1.943     raeburn  16004: 
1.1240    raeburn  16005: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16006: 
1.243     albertel 16007: =back
                   16008: 
                   16009: =head2 Network Status Functions
                   16010: 
                   16011: =over 4
1.191     harris41 16012: 
                   16013: =item *
                   16014: 
1.1137    raeburn  16015: dirlist() : return directory list based on URI (first arg).
                   16016: 
                   16017: Inputs: 1 required, 5 optional.
                   16018: 
                   16019: =over
                   16020: 
                   16021: =item 
                   16022: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16023: 
                   16024: =item
                   16025: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16026: 
                   16027: =item
                   16028: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16029: 
                   16030: =item
                   16031: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16032: 
                   16033: =item
                   16034: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16035: 
                   16036: =item 
                   16037: $alternateRoot - path to prepend in place of path from $uri.
                   16038: 
                   16039: =back
                   16040: 
                   16041: Returns: Array of up to two items.
                   16042: 
                   16043: =over
                   16044: 
                   16045: a reference to an array of files/subdirectories
                   16046: 
                   16047: =over
                   16048: 
                   16049: Each element in the array of files/subdirectories is a & separated list of
                   16050: item name and the result of running stat on the item.  If dirlist was requested
                   16051: for a file instead of a directory, the item name will be ''. For a directory 
                   16052: listing, if the item is a metadata file, the element will end &N&M 
                   16053: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16054: default copyright set (1).  
                   16055: 
                   16056: =back
                   16057: 
                   16058: a scalar containing error condition (if encountered).
                   16059: 
                   16060: =over
                   16061: 
                   16062: =item 
                   16063: no_host (no homeserver identified for $username:$domain).
                   16064: 
                   16065: =item 
                   16066: no_such_host (server contacted for listing not identified as valid host).
                   16067: 
                   16068: =item 
                   16069: con_lost (connection to remote server failed).
                   16070: 
                   16071: =item 
                   16072: refused (invalid $username:$domain received on lond side).
                   16073: 
                   16074: =item 
                   16075: no_such_dir (directory at specified path on lond side does not exist). 
                   16076: 
                   16077: =item 
                   16078: empty (directory at specified path on lond side is empty).
                   16079: 
                   16080: =over
                   16081: 
                   16082: This is currently not encountered because the &ls3, &ls2, 
                   16083: &ls (_handler) routines on the lond side do not filter out
                   16084: . and .. from a directory listing. 
                   16085: 
                   16086: =back
                   16087: 
                   16088: =back
                   16089: 
                   16090: =back
1.191     harris41 16091: 
                   16092: =item *
                   16093: 
1.243     albertel 16094: spareserver() : find server with least workload from spare.tab
                   16095: 
1.986     foxr     16096: 
                   16097: =item *
                   16098: 
                   16099: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16100: if there is no corresponding loncapa host.
                   16101: 
1.243     albertel 16102: =back
                   16103: 
1.986     foxr     16104: 
1.243     albertel 16105: =head2 Apache Request
                   16106: 
                   16107: =over 4
1.191     harris41 16108: 
                   16109: =item *
                   16110: 
1.243     albertel 16111: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16112: localhost, posts hash
                   16113: 
                   16114: =back
                   16115: 
                   16116: =head2 Data to String to Data
                   16117: 
                   16118: =over 4
1.191     harris41 16119: 
                   16120: =item *
                   16121: 
1.243     albertel 16122: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16123: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16124: 
                   16125: =item *
                   16126: 
1.243     albertel 16127: hashref2str($hashref) : convert a hashref into a string complete with
                   16128: escaping and '=' and '&' separators, supports elements that are
                   16129: arrayrefs and hashrefs
1.191     harris41 16130: 
                   16131: =item *
                   16132: 
1.243     albertel 16133: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16134: with escaping and '&' separators, supports elements that are arrayrefs
                   16135: and hashrefs
1.191     harris41 16136: 
                   16137: =item *
                   16138: 
1.243     albertel 16139: str2hash($string) : convert string to hash using unescaping and
                   16140: splitting on '=' and '&', supports elements that are arrayrefs and
                   16141: hashrefs
1.191     harris41 16142: 
                   16143: =item *
                   16144: 
1.243     albertel 16145: str2array($string) : convert string to hash using unescaping and
                   16146: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16147: 
                   16148: =back
                   16149: 
                   16150: =head2 Logging Routines
                   16151: 
                   16152: 
                   16153: These routines allow one to make log messages in the lonnet.log and
                   16154: lonnet.perm logfiles.
1.191     harris41 16155: 
1.1119    foxr     16156: =over 4
                   16157: 
1.191     harris41 16158: =item *
                   16159: 
1.243     albertel 16160: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16161: 
                   16162: =item *
                   16163: 
1.243     albertel 16164: logthis() : append message to the normal lonnet.log file, it gets
                   16165: preiodically rolled over and deleted.
1.191     harris41 16166: 
                   16167: =item *
                   16168: 
1.243     albertel 16169: logperm() : append a permanent message to lonnet.perm.log, this log
                   16170: file never gets deleted by any automated portion of the system, only
                   16171: messages of critical importance should go in here.
                   16172: 
1.1119    foxr     16173: 
1.243     albertel 16174: =back
                   16175: 
                   16176: =head2 General File Helper Routines
                   16177: 
                   16178: =over 4
1.191     harris41 16179: 
                   16180: =item *
                   16181: 
1.481     raeburn  16182: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16183: (a) files in /uploaded
                   16184:   (i) If a local copy of the file exists - 
                   16185:       compares modification date of local copy with last-modified date for 
                   16186:       definitive version stored on home server for course. If local copy is 
                   16187:       stale, requests a new version from the home server and stores it. 
                   16188:       If the original has been removed from the home server, then local copy 
                   16189:       is unlinked.
                   16190:   (ii) If local copy does not exist -
                   16191:       requests the file from the home server and stores it. 
                   16192:   
                   16193:   If $caller is 'uploadrep':  
                   16194:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16195:     for request for files originally uploaded via DOCS. 
                   16196:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16197:   
                   16198:   Otherwise:
                   16199:      This indicates a call from the content generation phase of the request.
                   16200:      -  returns the entire contents of the file or -1.
                   16201:      
                   16202: (b) files in /res
                   16203:    - returns the entire contents of a file or -1; 
                   16204:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16205: 
1.712     albertel 16206: 
                   16207: =item *
                   16208: 
                   16209: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16210:                   reference
                   16211: 
                   16212: returns either a stat() list of data about the file or an empty list
                   16213: if the file doesn't exist or couldn't find out about it (connection
                   16214: problems or user unknown)
                   16215: 
1.191     harris41 16216: =item *
                   16217: 
1.243     albertel 16218: filelocation($dir,$file) : returns file system location of a file
                   16219: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16220: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16221: and a file of ../bob will become /a/bob)
1.191     harris41 16222: 
                   16223: =item *
                   16224: 
                   16225: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16226: filelocation except for hrefs
                   16227: 
                   16228: =item *
                   16229: 
1.1261    raeburn  16230: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16231: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16232: 
1.243     albertel 16233: =back
                   16234: 
1.608     albertel 16235: =head2 Usererfile file routines (/uploaded*)
                   16236: 
                   16237: =over 4
                   16238: 
                   16239: =item *
                   16240: 
                   16241: userfileupload(): main rotine for putting a file in a user or course's
                   16242:                   filespace, arguments are,
                   16243: 
1.620     albertel 16244:  formname - required - this is the name of the element in $env where the
1.608     albertel 16245:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16246:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16247:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16248:  context - if coursedoc, store the file in the course of the active role
                   16249:              of the current user; 
                   16250:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16251:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16252:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16253:          if undefined, it will be placed in "unknown"
                   16254: 
                   16255:  (This routine calls clean_filename() to remove any dangerous
                   16256:  characters from the filename, and then calls finuserfileupload() to
                   16257:  complete the transaction)
                   16258: 
                   16259:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16260:  and /adm/notfound.html if unsuccessful
                   16261: 
                   16262: =item *
                   16263: 
                   16264: clean_filename(): routine for cleaing a filename up for storage in
                   16265:                  userfile space, argument is:
                   16266: 
                   16267:  filename - proposed filename
                   16268: 
                   16269: returns: the new clean filename
                   16270: 
                   16271: =item *
                   16272: 
1.1090    raeburn  16273: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16274: userspace, probably shouldn't be called directly
                   16275: 
                   16276:   docuname: username or courseid of destination for the file
                   16277:   docudom: domain of user/course of destination for the file
                   16278:   formname: same as for userfileupload()
1.1090    raeburn  16279:   fname: filename (including subdirectories) for the file
                   16280:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  16281:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16282:   allfiles: reference to hash used to store objects found by parser
                   16283:   codebase: reference to hash used for codebases of java objects found by parser
                   16284:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16285:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16286:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16287:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16288:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16289:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16290:   mimetype: reference to scalar to accommodate mime type determined
                   16291:             from File::MMagic if $parser = parse.
1.608     albertel 16292: 
                   16293:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16294:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16295:  was 'overwrite').
                   16296:  
1.608     albertel 16297: 
                   16298: =item *
                   16299: 
                   16300: renameuserfile(): renames an existing userfile to a new name
                   16301: 
                   16302:   Args:
                   16303:    docuname: username or courseid of destination for the file
                   16304:    docudom: domain of user/course of destination for the file
                   16305:    old: current file name (including any subdirs under userfiles)
                   16306:    new: desired file name (including any subdirs under userfiles)
                   16307: 
                   16308: =item *
                   16309: 
                   16310: mkdiruserfile(): creates a directory is a userfiles dir
                   16311: 
                   16312:   Args:
                   16313:    docuname: username or courseid of destination for the file
                   16314:    docudom: domain of user/course of destination for the file
                   16315:    dir: dir to create (including any subdirs under userfiles)
                   16316: 
                   16317: =item *
                   16318: 
                   16319: removeuserfile(): removes a file that exists in userfiles
                   16320: 
                   16321:   Args:
                   16322:    docuname: username or courseid of destination for the file
                   16323:    docudom: domain of user/course of destination for the file
                   16324:    fname: filname to delete (including any subdirs under userfiles)
                   16325: 
                   16326: =item *
                   16327: 
                   16328: removeuploadedurl(): convience function for removeuserfile()
                   16329: 
                   16330:   Args:
                   16331:    url:  a full /uploaded/... url to delete
                   16332: 
1.747     albertel 16333: =item * 
                   16334: 
                   16335: get_portfile_permissions():
                   16336:   Args:
                   16337:     domain: domain of user or course contain the portfolio files
                   16338:     user: name of user or num of course contain the portfolio files
                   16339:   Returns:
                   16340:     hashref of a dump of the proper file_permissions.db
                   16341:    
                   16342: 
                   16343: =item * 
                   16344: 
                   16345: get_access_controls():
                   16346: 
                   16347: Args:
                   16348:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16349:   group: (optional) the group you want the files associated with
                   16350:   file: (optional) the file you want access info on
                   16351: 
                   16352: Returns:
1.749     raeburn  16353:     a hash (keys are file names) of hashes containing
                   16354:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16355:         values are XML containing access control settings (see below) 
1.747     albertel 16356: 
                   16357: Internal notes:
                   16358: 
1.749     raeburn  16359:  access controls are stored in file_permissions.db as key=value pairs.
                   16360:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16361:         where scope -> public,guest,course,group,domains or users.
                   16362:               end -> UNIX time for end of access (0 -> no end date)
                   16363:               start -> UNIX time for start of access
                   16364: 
                   16365:     value -> XML description of access control
                   16366:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16367:             <start></start>
                   16368:             <end></end>
                   16369: 
                   16370:             <password></password>  for scope type = guest
                   16371: 
                   16372:             <domain></domain>     for scope type = course or group
                   16373:             <number></number>
                   16374:             <roles id="">
                   16375:              <role></role>
                   16376:              <access></access>
                   16377:              <section></section>
                   16378:              <group></group>
                   16379:             </roles>
                   16380: 
                   16381:             <dom></dom>         for scope type = domains
                   16382: 
                   16383:             <users>             for scope type = users
                   16384:              <user>
                   16385:               <uname></uname>
                   16386:               <udom></udom>
                   16387:              </user>
                   16388:             </users>
                   16389:            </scope> 
                   16390:               
                   16391:  Access data is also aggregated for each file in an additional key=value pair:
                   16392:  key -> path to file/file_name\0accesscontrol 
                   16393:  value -> reference to hash
                   16394:           hash contains key = value pairs
                   16395:           where key = uniqueID:scope_end_start
                   16396:                 value = UNIX time record was last updated
                   16397: 
                   16398:           Used to improve speed of look-ups of access controls for each file.  
                   16399:  
                   16400:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16401: 
1.1198    raeburn  16402: =item *
                   16403: 
1.749     raeburn  16404: modify_access_controls():
                   16405: 
                   16406: Modifies access controls for a portfolio file
                   16407: Args
                   16408: 1. file name
                   16409: 2. reference to hash of required changes,
                   16410: 3. domain
                   16411: 4. username
                   16412:   where domain,username are the domain of the portfolio owner 
                   16413:   (either a user or a course) 
                   16414: 
                   16415: Returns:
                   16416: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16417: 2. result of deletions ('ok' or 'error', with error message).
                   16418: 3. reference to hash of any new or updated access controls.
                   16419: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16420:    key = integer (inbound ID)
1.1198    raeburn  16421:    value = uniqueID
                   16422: 
                   16423: =item *
                   16424: 
                   16425: get_timebased_id():
                   16426: 
                   16427: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   16428: course via the Course Editor (e.g., folders, composite pages, 
                   16429: group bulletin boards).
                   16430: 
                   16431: Args: (first three required; six others optional)
                   16432: 
                   16433: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16434:    docssequence, or name of group
                   16435: 
                   16436: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16437:    e.g., num, boardids
                   16438: 
                   16439: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   16440:    file will be named nohist_namespace.db
                   16441: 
                   16442: 4. cdom: domain of course; default is current course domain from %env
                   16443: 
                   16444: 5. cnum: course number; default is current course number from %env
                   16445: 
                   16446: 6. idtype: set to concat if an additional digit is to be appended to the 
                   16447:    unix timestamp to form the suffix, if the plain timestamp is already
                   16448:    in use.  Default is to not do this, but simply increment the unix 
                   16449:    timestamp by 1 until a unique key is obtained.
                   16450: 
                   16451: 7. who: holder of locking key; defaults to user:domain for user.
                   16452: 
                   16453: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   16454:    retrying); default is 3.
                   16455: 
                   16456: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   16457: 
                   16458: Returns:
                   16459: 
                   16460: 1. suffix obtained (numeric)
                   16461: 
                   16462: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16463: 
                   16464: 3. error: contains (localized) error message if an error occurred.
                   16465: 
1.747     albertel 16466: 
1.608     albertel 16467: =back
                   16468: 
1.243     albertel 16469: =head2 HTTP Helper Routines
                   16470: 
                   16471: =over 4
                   16472: 
1.191     harris41 16473: =item *
                   16474: 
                   16475: escape() : unpack non-word characters into CGI-compatible hex codes
                   16476: 
                   16477: =item *
                   16478: 
                   16479: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16480: 
1.243     albertel 16481: =back
                   16482: 
                   16483: =head1 PRIVATE SUBROUTINES
                   16484: 
                   16485: =head2 Underlying communication routines (Shouldn't call)
                   16486: 
                   16487: =over 4
                   16488: 
                   16489: =item *
                   16490: 
                   16491: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16492: 
                   16493: =item *
                   16494: 
                   16495: reply() : uses subreply to send a message to remote machine, logs all failures
                   16496: 
                   16497: =item *
                   16498: 
                   16499: critical() : passes a critical message to another server; if cannot
                   16500: get through then place message in connection buffer directory and
                   16501: returns con_delayed, if incapable of saving message, returns
                   16502: con_failed
                   16503: 
                   16504: =item *
                   16505: 
                   16506: reconlonc() : tries to reconnect lonc client processes.
                   16507: 
                   16508: =back
                   16509: 
                   16510: =head2 Resource Access Logging
                   16511: 
                   16512: =over 4
                   16513: 
                   16514: =item *
                   16515: 
                   16516: flushcourselogs() : flush (save) buffer logs and access logs
                   16517: 
                   16518: =item *
                   16519: 
                   16520: courselog($what) : save message for course in hash
                   16521: 
                   16522: =item *
                   16523: 
                   16524: courseacclog($what) : save message for course using &courselog().  Perform
                   16525: special processing for specific resource types (problems, exams, quizzes, etc).
                   16526: 
1.191     harris41 16527: =item *
                   16528: 
                   16529: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16530: as a PerlChildExitHandler
1.243     albertel 16531: 
                   16532: =back
                   16533: 
                   16534: =head2 Other
                   16535: 
                   16536: =over 4
                   16537: 
                   16538: =item *
                   16539: 
                   16540: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16541: 
                   16542: =back
                   16543: 
                   16544: =cut
1.877     foxr     16545: 

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