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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1415  ! raeburn     4: # $Id: lonnet.pm,v 1.1414 2019/07/25 20:23:59 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.1411    raeburn  1085: sub delusersession {
                   1086:     my ($lonid,$udom,$uname) = @_;
                   1087:     my $uprimary_id = &domain($udom,'primary');
                   1088:     my $uintdom = &internet_dom($uprimary_id);
                   1089:     my $intdom = &internet_dom($lonid);
                   1090:     my $serverhomedom = &host_domain($lonid);
                   1091:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1092:         return &reply(join(':','delusersession',
                   1093:                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1094:     }
                   1095:     return;
                   1096: }
                   1097: 
1.1389    raeburn  1098: # check if user's browser sent load balancer cookie and server still has session
                   1099: # and is not overloaded.
                   1100: sub check_for_balancer_cookie {
                   1101:     my ($r,$update_mtime) = @_;
                   1102:     my ($otherserver,$cookie);
                   1103:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1104:     if (exists($cookies{'balanceID'})) {
                   1105:         my $balid = $cookies{'balanceID'};
                   1106:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1107:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1108:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1109:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1110:                 my ($possudom,$possuname) = ($1,$2);
                   1111:                 my $has_session = 0;
                   1112:                 if ((&domain($possudom) ne '') &&
                   1113:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1114:                     my $try_server;
                   1115:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1116:                     if ($opened) {
                   1117:                         flock($idf,LOCK_SH);
                   1118:                         while (my $line = <$idf>) {
                   1119:                             chomp($line);
                   1120:                             if (&hostname($line) ne '') {
                   1121:                                 $try_server = $line;
                   1122:                                 last;
                   1123:                             }
                   1124:                         }
                   1125:                         close($idf);
                   1126:                         if (($try_server) &&
                   1127:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1128:                             my $lowest_load = 30000;
                   1129:                             ($otherserver,$lowest_load) =
                   1130:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1131:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1132:                                 $has_session = 1;
                   1133:                             } else {
                   1134:                                 undef($otherserver);
                   1135:                             }
                   1136:                         }
                   1137:                     }
                   1138:                 }
                   1139:                 if ($has_session) {
                   1140:                     if ($update_mtime) {
                   1141:                         my $atime = my $mtime = time;
                   1142:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1143:                     }
                   1144:                 } else {
                   1145:                     unlink("$balancedir/$cookie.id");
                   1146:                 }
                   1147:             }
                   1148:         }
                   1149:     }
                   1150:     return ($otherserver,$cookie);
                   1151: }
                   1152: 
                   1153: sub delbalcookie {
                   1154:     my ($cookie,$balancer) =@_;
                   1155:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1156:         my ($udom,$uname) = ($1,$2);
                   1157:         my $uprimary_id = &domain($udom,'primary');
                   1158:         my $uintdom = &internet_dom($uprimary_id);
                   1159:         my $intdom = &internet_dom($balancer);
                   1160:         my $serverhomedom = &host_domain($balancer);
                   1161:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1162:             return &reply("delbalcookie:$cookie",$balancer);
                   1163:         }
                   1164:     }
                   1165: }
                   1166: 
1.914     albertel 1167: # -------------------------------- ask if server already has a session for user
                   1168: sub has_user_session {
                   1169:     my ($lonid,$udom,$uname) = @_;
                   1170:     my $result = &reply(join(':','userhassession',
                   1171: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1172:     return 1 if ($result eq 'ok');
                   1173: 
                   1174:     return 0;
                   1175: }
                   1176: 
1.1076    raeburn  1177: # --------- determine least loaded server in a user's domain which allows login
                   1178: 
                   1179: sub choose_server {
1.1259    raeburn  1180:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1181:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1182:     my %servers = &get_servers($udom);
1.1076    raeburn  1183:     my $lowest_load = 30000;
1.1259    raeburn  1184:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1185:     if ($skiploadbal) {
                   1186:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1187:         unless (defined($cached)) {
                   1188:             my $cachetime = 60*60*24;
                   1189:             my %domconfig =
                   1190:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1191:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1192:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1193:                                            $cachetime);
                   1194:             }
                   1195:         }
                   1196:     }
1.1076    raeburn  1197:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1198:         if ($skiploadbal) {
                   1199:             if (ref($balancers) eq 'HASH') {
                   1200:                 next if (exists($balancers->{$lonhost}));
                   1201:             }
1.1389    raeburn  1202:         }
1.1115    raeburn  1203:         my $loginvia;
                   1204:         if ($checkloginvia) {
                   1205:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1206:             if ($loginvia) {
                   1207:                 my ($server,$path) = split(/:/,$loginvia);
                   1208:                 ($login_host, $lowest_load) =
1.1253    raeburn  1209:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1210:                 if ($login_host eq $server) {
                   1211:                     $portal_path = $path;
1.1151    raeburn  1212:                     $isredirect = 1;
1.1116    raeburn  1213:                 }
                   1214:             } else {
                   1215:                 ($login_host, $lowest_load) =
1.1253    raeburn  1216:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1217:                 if ($login_host eq $lonhost) {
                   1218:                     $portal_path = '';
1.1151    raeburn  1219:                     $isredirect = ''; 
1.1116    raeburn  1220:                 }
                   1221:             }
                   1222:         } else {
1.1076    raeburn  1223:             ($login_host, $lowest_load) =
1.1253    raeburn  1224:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1225:         }
                   1226:     }
                   1227:     if ($login_host ne '') {
1.1116    raeburn  1228:         $hostname = &hostname($login_host);
1.1076    raeburn  1229:     }
1.1331    raeburn  1230:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1231: }
                   1232: 
1.202     matthew  1233: # --------------------------------------------- Try to change a user's password
                   1234: 
                   1235: sub changepass {
1.799     raeburn  1236:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1237:     $currentpass = &escape($currentpass);
                   1238:     $newpass     = &escape($newpass);
1.1030    raeburn  1239:     my $lonhost = $perlvar{'lonHostID'};
                   1240:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1241: 		       $server);
                   1242:     if (! $answer) {
                   1243: 	&logthis("No reply on password change request to $server ".
                   1244: 		 "by $uname in domain $udom.");
                   1245:     } elsif ($answer =~ "^ok") {
                   1246:         &logthis("$uname in $udom successfully changed their password ".
                   1247: 		 "on $server.");
                   1248:     } elsif ($answer =~ "^pwchange_failure") {
                   1249: 	&logthis("$uname in $udom was unable to change their password ".
                   1250: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1251: 		 "or pwchange");
                   1252:     } elsif ($answer =~ "^non_authorized") {
                   1253:         &logthis("$uname in $udom did not get their password correct when ".
                   1254: 		 "attempting to change it on $server.");
                   1255:     } elsif ($answer =~ "^auth_mode_error") {
                   1256:         &logthis("$uname in $udom attempted to change their password despite ".
                   1257: 		 "not being locally or internally authenticated on $server.");
                   1258:     } elsif ($answer =~ "^unknown_user") {
                   1259:         &logthis("$uname in $udom attempted to change their password ".
                   1260: 		 "on $server but were unable to because $server is not ".
                   1261: 		 "their home server.");
                   1262:     } elsif ($answer =~ "^refused") {
                   1263: 	&logthis("$server refused to change $uname in $udom password because ".
                   1264: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1265:     } elsif ($answer =~ "invalid_client") {
                   1266:         &logthis("$server refused to change $uname in $udom password because ".
                   1267:                  "it was a reset by e-mail originating from an invalid server.");
1.1408    raeburn  1268:     } elsif ($answer =~ "^prioruse") {
                   1269:        &logthis("$server refused to change $uname in $udom password because ".
                   1270:                 "the password had been used before");
1.202     matthew  1271:     }
                   1272:     return $answer;
1.1       albertel 1273: }
                   1274: 
1.169     harris41 1275: # ----------------------- Try to determine user's current authentication scheme
                   1276: 
                   1277: sub queryauthenticate {
                   1278:     my ($uname,$udom)=@_;
1.456     albertel 1279:     my $uhome=&homeserver($uname,$udom);
                   1280:     if (!$uhome) {
                   1281: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1282: 	return 'no_host';
                   1283:     }
                   1284:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1285:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1286: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1287:     }
1.456     albertel 1288:     return $answer;
1.169     harris41 1289: }
                   1290: 
1.1       albertel 1291: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1292: 
1.1       albertel 1293: sub authenticate {
1.1073    raeburn  1294:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1295:     $upass=&escape($upass);
                   1296:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1297:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1298:     my $newhome;
1.836     www      1299:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1300: # Maybe the machine was offline and only re-appeared again recently?
                   1301:         &reconlonc();
                   1302: # One more
1.952     raeburn  1303: 	$uhome=&homeserver($uname,$udom,1);
                   1304:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1305:             if (defined(&domain($udom,'primary'))) {
                   1306:                 $newhome=&domain($udom,'primary');
                   1307:             }
                   1308:             if ($newhome ne '') {
                   1309:                 $uhome = $newhome;
                   1310:             }
                   1311:         }
1.836     www      1312: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1313: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1314: 	    return 'no_host';
                   1315:         }
1.1       albertel 1316:     }
1.1073    raeburn  1317:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1318:     if ($answer eq 'authorized') {
1.952     raeburn  1319:         if ($newhome) {
                   1320:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1321:             return 'no_account_on_host'; 
                   1322:         } else {
                   1323:             &logthis("User $uname at $udom authorized by $uhome");
                   1324:             return $uhome;
                   1325:         }
1.471     albertel 1326:     }
                   1327:     if ($answer eq 'non_authorized') {
                   1328: 	&logthis("User $uname at $udom rejected by $uhome");
                   1329: 	return 'no_host'; 
1.9       www      1330:     }
1.471     albertel 1331:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1332:     return 'no_host';
                   1333: }
                   1334: 
1.1073    raeburn  1335: sub can_host_session {
1.1074    raeburn  1336:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1337:     my $canhost = 1;
1.1074    raeburn  1338:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1339:     if (ref($remotesessions) eq 'HASH') {
                   1340:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1341:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1342:                 $canhost = 0;
                   1343:             } else {
                   1344:                 $canhost = 1;
                   1345:             }
                   1346:         }
                   1347:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1348:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1349:                 $canhost = 1;
                   1350:             } else {
                   1351:                 $canhost = 0;
                   1352:             }
                   1353:         }
                   1354:         if ($canhost) {
                   1355:             if ($remotesessions->{'version'} ne '') {
                   1356:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1357:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1358:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1359:                         my $major = $1;
                   1360:                         my $minor = $2;
                   1361:                         if (($major < $reqmajor ) ||
                   1362:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1363:                             $canhost = 0;
                   1364:                         }
                   1365:                     } else {
                   1366:                         $canhost = 0;
                   1367:                     }
                   1368:                 }
                   1369:             }
                   1370:         }
                   1371:     }
                   1372:     if ($canhost) {
                   1373:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1374:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1375:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1376:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1377:                 if (($uint_dom ne '') && 
                   1378:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1379:                     $canhost = 0;
                   1380:                 } else {
                   1381:                     $canhost = 1;
                   1382:                 }
                   1383:             }
                   1384:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1385:                 if (($uint_dom ne '') && 
                   1386:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1387:                     $canhost = 1;
                   1388:                 } else {
                   1389:                     $canhost = 0;
                   1390:                 }
                   1391:             }
                   1392:         }
                   1393:     }
                   1394:     return $canhost;
                   1395: }
                   1396: 
1.1083    raeburn  1397: sub spare_can_host {
                   1398:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1399:     my $canhost=1;
1.1279    raeburn  1400:     my $try_server_hostname = &hostname($try_server);
                   1401:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1402:     my $serverhomedom = &host_domain($serverhomeID);
                   1403:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1404:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1405:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1406:             $canhost = 0;
                   1407:         }
                   1408:     }
                   1409:     if (($canhost) && ($uint_dom)) {
                   1410:         my @intdoms;
                   1411:         my $internet_names = &get_internet_names($try_server);
                   1412:         if (ref($internet_names) eq 'ARRAY') {
                   1413:             @intdoms = @{$internet_names};
                   1414:         }
                   1415:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1416:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1417:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1418:                                          $remotesessions,
                   1419:                                          $defdomdefaults{'hostedsessions'});
                   1420:         }
1.1083    raeburn  1421:     }
                   1422:     return $canhost;
                   1423: }
                   1424: 
1.1123    raeburn  1425: sub this_host_spares {
                   1426:     my ($dom) = @_;
1.1126    raeburn  1427:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1428:     my @hosts = &current_machine_ids();
                   1429:     foreach my $lonhost (@hosts) {
                   1430:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1431:             $dom_in_use = $dom;
                   1432:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1433:             last;
                   1434:         }
                   1435:     }
1.1126    raeburn  1436:     if ($dom_in_use ne '') {
                   1437:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1438:     }
                   1439:     if (ref($result) ne 'HASH') {
                   1440:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1441:         $dom_in_use = &host_domain($lonhost_in_use);
                   1442:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1443:         if (ref($result) ne 'HASH') {
                   1444:             $result = \%spareid;
                   1445:         }
                   1446:     }
                   1447:     return $result;
                   1448: }
                   1449: 
                   1450: sub spares_for_offload  {
                   1451:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1452:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1453:     if (defined($cached)) {
                   1454:         return $result;
                   1455:     } else {
1.1126    raeburn  1456:         my $cachetime = 60*60*24;
                   1457:         my %domconfig =
                   1458:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1459:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1460:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1461:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1462:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1463:                 }
                   1464:             }
                   1465:         }
                   1466:     }
1.1126    raeburn  1467:     return;
1.1123    raeburn  1468: }
                   1469: 
1.1129    raeburn  1470: sub get_lonbalancer_config {
                   1471:     my ($servers) = @_;
                   1472:     my ($currbalancer,$currtargets);
                   1473:     if (ref($servers) eq 'HASH') {
                   1474:         foreach my $server (keys(%{$servers})) {
                   1475:             my %what = (
                   1476:                          spareid => 1,
                   1477:                          perlvar => 1,
                   1478:                        );
                   1479:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1480:             if ($result eq 'ok') {
                   1481:                 if (ref($returnhash) eq 'HASH') {
                   1482:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1483:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1484:                             $currbalancer = $server;
                   1485:                             $currtargets = {};
                   1486:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1487:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1488:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1489:                                 }
                   1490:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1491:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1492:                                 }
                   1493:                             }
                   1494:                             last;
                   1495:                         }
                   1496:                     }
                   1497:                 }
                   1498:             }
                   1499:         }
                   1500:     }
                   1501:     return ($currbalancer,$currtargets);
                   1502: }
                   1503: 
                   1504: sub check_loadbalancing {
1.1331    raeburn  1505:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1506:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1507:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1508:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1509:     my @hosts = &current_machine_ids();
1.1129    raeburn  1510:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1511:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1512:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1513:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1514:     my $domneedscache;
1.1129    raeburn  1515:     my $cachetime = 60*60*24;
                   1516: 
                   1517:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1518:         $dom_in_use = $udom;
                   1519:         $homeintdom = 1;
                   1520:     } else {
                   1521:         $dom_in_use = $serverhomedom;
                   1522:     }
                   1523:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1524:     unless (defined($cached)) {
                   1525:         my %domconfig =
                   1526:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1527:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1528:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1529:         } else {
                   1530:             $domneedscache = $dom_in_use;
1.1129    raeburn  1531:         }
                   1532:     }
                   1533:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1534:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1535:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1536:         if ($is_balancer) {
                   1537:             if (ref($currrules) eq 'HASH') {
                   1538:                 if ($homeintdom) {
                   1539:                     if ($uname ne '') {
                   1540:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1541:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1542:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1543:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1544:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1545:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1546:                             }
                   1547:                         }
                   1548:                         if ($rule_in_effect eq '') {
                   1549:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1550:                             if ($userenv{'inststatus'} ne '') {
                   1551:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1552:                                 my ($othertitle,$usertypes,$types) =
                   1553:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1554:                                 if (ref($types) eq 'ARRAY') {
                   1555:                                     foreach my $type (@{$types}) {
                   1556:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1557:                                             if (exists($currrules->{$type})) {
                   1558:                                                 $rule_in_effect = $currrules->{$type};
                   1559:                                             }
                   1560:                                         }
                   1561:                                     }
                   1562:                                 }
                   1563:                             } else {
                   1564:                                 if (exists($currrules->{'default'})) {
                   1565:                                     $rule_in_effect = $currrules->{'default'};
                   1566:                                 }
                   1567:                             }
                   1568:                         }
                   1569:                     } else {
                   1570:                         if (exists($currrules->{'default'})) {
                   1571:                             $rule_in_effect = $currrules->{'default'};
                   1572:                         }
                   1573:                     }
                   1574:                 } else {
                   1575:                     if ($currrules->{'_LC_external'} ne '') {
                   1576:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1577:                     }
                   1578:                 }
                   1579:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1580:                                                        $uname,$udom);
                   1581:             }
                   1582:         }
                   1583:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1584:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1585:         unless (defined($cached)) {
                   1586:             my %domconfig =
                   1587:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1588:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1589:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1590:             } else {
                   1591:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1592:             }
                   1593:         }
                   1594:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1595:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1596:                 &check_balancer_result($result,@hosts);
                   1597:             if ($is_balancer) {
1.1129    raeburn  1598:                 if (ref($currrules) eq 'HASH') {
                   1599:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1600:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1601:                     }
                   1602:                 }
                   1603:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1604:                                                        $uname,$udom);
                   1605:             }
                   1606:         } else {
                   1607:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1608:                 $is_balancer = 1;
                   1609:                 $offloadto = &this_host_spares($dom_in_use);
                   1610:             }
1.1307    raeburn  1611:             unless (defined($cached)) {
                   1612:                 $domneedscache = $serverhomedom;
                   1613:             }
1.1129    raeburn  1614:         }
                   1615:     } else {
                   1616:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1617:             $is_balancer = 1;
                   1618:             $offloadto = &this_host_spares($dom_in_use);
                   1619:         }
1.1307    raeburn  1620:         unless (defined($cached)) {
                   1621:             $domneedscache = $serverhomedom;
                   1622:         }
                   1623:     }
                   1624:     if ($domneedscache) {
                   1625:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1626:     }
1.1176    raeburn  1627:     if ($is_balancer) {
                   1628:         my $lowest_load = 30000;
                   1629:         if (ref($offloadto) eq 'HASH') {
                   1630:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1631:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1632:                     ($otherserver,$lowest_load) =
                   1633:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1634:                 }
1.1129    raeburn  1635:             }
1.1176    raeburn  1636:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1637: 
1.1176    raeburn  1638:             if (!$found_server) {
                   1639:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1640:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1641:                         ($otherserver,$lowest_load) =
                   1642:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1643:                     }
                   1644:                 }
                   1645:             }
                   1646:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1647:             if (@{$offloadto} == 1) {
                   1648:                 $otherserver = $offloadto->[0];
                   1649:             } elsif (@{$offloadto} > 1) {
                   1650:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1651:                     ($otherserver,$lowest_load) =
                   1652:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1653:                 }
                   1654:             }
                   1655:         }
1.1331    raeburn  1656:         unless ($caller eq 'login') {
                   1657:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1658:                 $is_balancer = 0;
                   1659:                 if ($uname ne '' && $udom ne '') {
                   1660:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1661:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1662:                                  'user.loadbalcheck.time' => time});
                   1663:                     }
1.1176    raeburn  1664:                 }
1.1129    raeburn  1665:             }
                   1666:         }
1.1389    raeburn  1667:         unless ($homeintdom) {
                   1668:             undef($setcookie);
                   1669:         }
1.1129    raeburn  1670:     }
1.1391    raeburn  1671:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1672: }
                   1673: 
1.1191    raeburn  1674: sub check_balancer_result {
                   1675:     my ($result,@hosts) = @_;
1.1391    raeburn  1676:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1677:     if (ref($result) eq 'HASH') {
                   1678:         if ($result->{'lonhost'} ne '') {
                   1679:             my $currbalancer = $result->{'lonhost'};
                   1680:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1681:                 $is_balancer = 1;
                   1682:                 $currtargets = $result->{'targets'};
                   1683:                 $currrules = $result->{'rules'};
                   1684:             }
1.1391    raeburn  1685:             $dom_balancers = $currbalancer;
1.1191    raeburn  1686:         } else {
1.1391    raeburn  1687:             if (keys(%{$result})) {
                   1688:                 foreach my $key (keys(%{$result})) {
                   1689:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1690:                         (ref($result->{$key}) eq 'HASH')) {
                   1691:                         $is_balancer = 1;
                   1692:                         $currrules = $result->{$key}{'rules'};
                   1693:                         $currtargets = $result->{$key}{'targets'};
                   1694:                         $setcookie = $result->{$key}{'cookie'};
                   1695:                         last;
                   1696:                     }
1.1191    raeburn  1697:                 }
1.1391    raeburn  1698:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1699:             }
                   1700:         }
                   1701:     }
1.1391    raeburn  1702:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1703: }
                   1704: 
1.1129    raeburn  1705: sub get_loadbalancer_targets {
                   1706:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1707:     my $offloadto;
1.1175    raeburn  1708:     if ($rule_in_effect eq 'none') {
                   1709:         return [$perlvar{'lonHostID'}];
                   1710:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1711:         $offloadto = $currtargets;
                   1712:     } else {
                   1713:         if ($rule_in_effect eq 'homeserver') {
                   1714:             my $homeserver = &homeserver($uname,$udom);
                   1715:             if ($homeserver ne 'no_host') {
                   1716:                 $offloadto = [$homeserver];
                   1717:             }
                   1718:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1719:             my %domconfig =
                   1720:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1721:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1722:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1723:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1724:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1725:                     }
                   1726:                 }
                   1727:             } else {
1.1178    raeburn  1728:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1729:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1730:                 if (&hostname($remotebalancer) ne '') {
                   1731:                     $offloadto = [$remotebalancer];
                   1732:                 }
                   1733:             }
                   1734:         } elsif (&hostname($rule_in_effect) ne '') {
                   1735:             $offloadto = [$rule_in_effect];
                   1736:         }
                   1737:     }
                   1738:     return $offloadto;
                   1739: }
                   1740: 
1.1127    raeburn  1741: sub internet_dom_servers {
                   1742:     my ($dom) = @_;
                   1743:     my (%uniqservers,%servers);
                   1744:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1745:     my @machinedoms = &machine_domains($primaryserver);
                   1746:     foreach my $mdom (@machinedoms) {
                   1747:         my %currservers = %servers;
                   1748:         my %server = &get_servers($mdom);
                   1749:         %servers = (%currservers,%server);
                   1750:     }
                   1751:     my %by_hostname;
                   1752:     foreach my $id (keys(%servers)) {
                   1753:         push(@{$by_hostname{$servers{$id}}},$id);
                   1754:     }
                   1755:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1756:         if (@{$by_hostname{$hostname}} > 1) {
                   1757:             my $match = 0;
                   1758:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1759:                 if (&host_domain($id) eq $dom) {
                   1760:                     $uniqservers{$id} = $hostname;
                   1761:                     $match = 1;
                   1762:                 }
                   1763:             }
                   1764:             unless ($match) {
                   1765:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1766:             }
                   1767:         } else {
                   1768:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1769:         }
                   1770:     }
                   1771:     return %uniqservers;
                   1772: }
                   1773: 
1.1347    raeburn  1774: sub trusted_domains {
                   1775:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1776:     my ($trusted,$untrusted);
1.1347    raeburn  1777:     if (&domain($calldom) eq '') {
1.1349    raeburn  1778:         return ($trusted,$untrusted);
1.1347    raeburn  1779:     }
1.1395    raeburn  1780:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1781:         return ($trusted,$untrusted);
1.1347    raeburn  1782:     }
                   1783:     my $callprimary = &domain($calldom,'primary');
                   1784:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1785:     if ($intcalldom eq '') {
1.1349    raeburn  1786:         return ($trusted,$untrusted);
1.1347    raeburn  1787:     }
                   1788: 
                   1789:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1790:     unless (defined($cached)) {
                   1791:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1792:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1793:         $trustconfig = $domconfig{'trust'};
                   1794:     }
                   1795:     if (ref($trustconfig)) {
                   1796:         my (%possexc,%possinc,@allexc,@allinc); 
                   1797:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1798:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1799:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1800:             }
                   1801:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1802:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1803:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1804:             }
                   1805:         }
                   1806:         if (keys(%possexc)) {
                   1807:             if (keys(%possinc)) {
                   1808:                 foreach my $key (sort(keys(%possexc))) {
                   1809:                     next if ($key eq $intcalldom);
                   1810:                     unless ($possinc{$key}) {
                   1811:                         push(@allexc,$key);
                   1812:                     }
                   1813:                 }
                   1814:             } else {
                   1815:                 @allexc = sort(keys(%possexc));
                   1816:             }
                   1817:         }
                   1818:         if (keys(%possinc)) {
                   1819:             $possinc{$intcalldom} = 1;
                   1820:             @allinc = sort(keys(%possinc));
                   1821:         }
                   1822:         if ((@allexc > 0) || (@allinc > 0)) {
                   1823:             my %doms_by_intdom;
                   1824:             my %allintdoms = &all_host_intdom();
                   1825:             my %alldoms = &all_host_domain();
                   1826:             foreach my $key (%allintdoms) {
                   1827:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1828:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1829:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1830:                     }
                   1831:                 } else {
                   1832:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1833:                 }
                   1834:             }
                   1835:             foreach my $exc (@allexc) {
                   1836:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1837:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1838:                 }
                   1839:             }
                   1840:             foreach my $inc (@allinc) {
                   1841:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1842:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1843:                 }
                   1844:             }
                   1845:         }
                   1846:     }
1.1349    raeburn  1847:     return ($trusted,$untrusted);
1.1347    raeburn  1848: }
                   1849: 
                   1850: sub will_trust {
                   1851:     my ($cmdtype,$domain,$possdom) = @_;
                   1852:     return 1 if ($domain eq $possdom);
                   1853:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1854:     my $willtrust; 
                   1855:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1856:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1857:             $willtrust = 1;
                   1858:         }
                   1859:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1860:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1861:             $willtrust = 1;
                   1862:         }
                   1863:     } else {
                   1864:         $willtrust = 1;
                   1865:     }
                   1866:     return $willtrust;
                   1867: }
                   1868: 
1.1       albertel 1869: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1870: 
1.599     albertel 1871: my %homecache;
1.1       albertel 1872: sub homeserver {
1.230     stredwic 1873:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1874:     my $index="$uname:$udom";
1.426     albertel 1875: 
1.599     albertel 1876:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1877: 
                   1878:     my %servers = &get_servers($udom,'library');
                   1879:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1880:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1881: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1882: 
                   1883: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1884: 	if ($answer eq 'found') {
                   1885: 	    delete($badServerCache{$tryserver}); 
                   1886: 	    return $homecache{$index}=$tryserver;
                   1887: 	} elsif ($answer eq 'no_host') {
                   1888: 	    $badServerCache{$tryserver}=1;
                   1889: 	}
1.1       albertel 1890:     }    
                   1891:     return 'no_host';
1.70      www      1892: }
                   1893: 
1.1300    raeburn  1894: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1895: 
                   1896: sub idget {
1.1300    raeburn  1897:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1898:     my %returnhash=();
1.1300    raeburn  1899:     my @ids=(); 
                   1900:     if (ref($idsref) eq 'ARRAY') {
                   1901:         @ids = @{$idsref};
                   1902:     } else {
                   1903:         return %returnhash; 
                   1904:     }
                   1905:     if ($namespace eq '') {
                   1906:         $namespace = 'ids';
                   1907:     }
1.70      www      1908:     
1.841     albertel 1909:     my %servers = &get_servers($udom,'library');
                   1910:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1911: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1912: 	if ($namespace eq 'ids') {
                   1913: 	    $idlist=~tr/A-Z/a-z/;
                   1914: 	}
                   1915: 	my $reply;
                   1916: 	if ($namespace eq 'ids') {
                   1917: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1918: 	} else {
                   1919: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1920: 	}
1.841     albertel 1921: 	my @answer=();
                   1922: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1923: 	    @answer=split(/\&/,$reply);
                   1924: 	}                    ;
                   1925: 	my $i;
                   1926: 	for ($i=0;$i<=$#ids;$i++) {
                   1927: 	    if ($answer[$i]) {
1.1299    raeburn  1928: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1929: 	    }
1.841     albertel 1930: 	}
1.1300    raeburn  1931:     }
1.70      www      1932:     return %returnhash;
                   1933: }
                   1934: 
                   1935: # ------------------------------------- Find the IDs behind a list of usernames
                   1936: 
                   1937: sub idrget {
                   1938:     my ($udom,@unames)=@_;
                   1939:     my %returnhash=();
1.800     albertel 1940:     foreach my $uname (@unames) {
                   1941:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1942:     }
1.70      www      1943:     return %returnhash;
                   1944: }
                   1945: 
1.1300    raeburn  1946: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1947: 
                   1948: sub idput {
1.1300    raeburn  1949:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1950:     my %servers=();
1.1300    raeburn  1951:     my %ids=();
                   1952:     my %byid = ();
                   1953:     if (ref($idsref) eq 'HASH') {
                   1954:         %ids=%{$idsref};
                   1955:     }
                   1956:     if ($namespace eq '') {
                   1957:         $namespace = 'ids'; 
                   1958:     }
1.800     albertel 1959:     foreach my $uname (keys(%ids)) {
                   1960: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1961:         if ($uhom eq '') {
                   1962:             $uhom=&homeserver($uname,$udom);
                   1963:         }
1.70      www      1964:         if ($uhom ne 'no_host') {
1.800     albertel 1965:             my $esc_unam=&escape($uname);
1.1300    raeburn  1966:             if ($namespace eq 'ids') {
                   1967:                 my $id=&escape($ids{$uname});
                   1968:                 $id=~tr/A-Z/a-z/;
                   1969:                 my $esc_unam=&escape($uname);
                   1970:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1971:             } else {
1.1300    raeburn  1972:                 my @currids = split(/,/,$ids{$uname});
                   1973:                 foreach my $id (@currids) {
                   1974:                     $byid{$uhom}{$id} .= $uname.',';
                   1975:                 }
                   1976:             }
                   1977:         }
                   1978:     }
                   1979:     if ($namespace eq 'clickers') {
                   1980:         foreach my $server (keys(%byid)) {
                   1981:             if (ref($byid{$server}) eq 'HASH') {
                   1982:                 foreach my $id (keys(%{$byid{$server}})) {
                   1983:                     $byid{$server} =~ s/,$//;
                   1984:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1985:                 }
1.70      www      1986:             }
                   1987:         }
1.191     harris41 1988:     }
1.800     albertel 1989:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1990:         $servers{$server} =~ s/\&$//;
                   1991:         if ($namespace eq 'ids') {     
                   1992:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1993:         } else {
                   1994:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1995:         }
1.191     harris41 1996:     }
1.344     www      1997: }
                   1998: 
1.1300    raeburn  1999: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2000: 
                   2001: sub iddel {
1.1300    raeburn  2002:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2003:     my %result=();
1.1300    raeburn  2004:     my %ids=();
                   2005:     my %byid = ();
                   2006:     if (ref($idshashref) eq 'HASH') {
                   2007:         %ids=%{$idshashref};
                   2008:     } else {
1.1231    raeburn  2009:         return %result;
                   2010:     }
1.1300    raeburn  2011:     if ($namespace eq '') {
                   2012:         $namespace = 'ids';
                   2013:     }
1.1231    raeburn  2014:     my %servers=();
1.1300    raeburn  2015:     while (my ($id,$unamestr) = each(%ids)) {
                   2016:         if ($namespace eq 'ids') {
                   2017:             my $uhom = $uhome;
                   2018:             if ($uhom eq '') { 
                   2019:                 $uhom=&homeserver($unamestr,$udom);
                   2020:             }
                   2021:             if ($uhom ne 'no_host') {
                   2022:                 $servers{$uhom}.='&'.&escape($id);
                   2023:             }
                   2024:          } else {
                   2025:             my @curritems = split(/,/,$ids{$id});
                   2026:             foreach my $uname (@curritems) {
                   2027:                 my $uhom = $uhome;
                   2028:                 if ($uhom eq '') {
                   2029:                     $uhom=&homeserver($uname,$udom);
                   2030:                 }
                   2031:                 if ($uhom ne 'no_host') { 
                   2032:                     $byid{$uhom}{$id} .= $uname.',';
                   2033:                 }
                   2034:             }
1.1231    raeburn  2035:         }
1.1300    raeburn  2036:     }
                   2037:     if ($namespace eq 'clickers') {
                   2038:         foreach my $server (keys(%byid)) {
                   2039:             if (ref($byid{$server}) eq 'HASH') {
                   2040:                 foreach my $id (keys(%{$byid{$server}})) {
                   2041:                     $byid{$server}{$id} =~ s/,$//;
                   2042:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2043:                 }
1.1231    raeburn  2044:             }
                   2045:         }
                   2046:     }
                   2047:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2048:         $servers{$server} =~ s/\&$//;
                   2049:         if ($namespace eq 'ids') {
                   2050:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2051:         } elsif ($namespace eq 'clickers') {
                   2052:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2053:         }
1.1231    raeburn  2054:     }
                   2055:     return %result;
                   2056: }
                   2057: 
1.1300    raeburn  2058: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2059: 
                   2060: sub updateclickers {
                   2061:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2062:     my %clickers;
                   2063:     if (ref($idshashref) eq 'HASH') {
                   2064:         %clickers=%{$idshashref};
                   2065:     } else {
                   2066:         return;
                   2067:     }
                   2068:     my $items='';
                   2069:     foreach my $item (keys(%clickers)) {
                   2070:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2071:     }
                   2072:     $items=~s/\&$//;
                   2073:     my $request = "updateclickers:$udom:$action:$items";
                   2074:     if ($critical) {
                   2075:         return &critical($request,$uhome);
                   2076:     } else {
                   2077:         return &reply($request,$uhome);
                   2078:     }
                   2079: }
                   2080: 
1.1023    raeburn  2081: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2082: sub dump_dom {
1.1165    droeschl 2083:     my ($namespace, $udom, $regexp) = @_;
                   2084: 
                   2085:     $udom ||= $env{'user.domain'};
                   2086: 
                   2087:     return () unless $udom;
                   2088: 
                   2089:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2090: }
                   2091: 
1.1023    raeburn  2092: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2093: 
                   2094: sub get_dom {
1.860     raeburn  2095:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2096:     return if ($udom eq 'public');
1.806     raeburn  2097:     my $items='';
                   2098:     foreach my $item (@$storearr) {
                   2099:         $items.=&escape($item).'&';
                   2100:     }
                   2101:     $items=~s/\&$//;
1.860     raeburn  2102:     if (!$udom) {
                   2103:         $udom=$env{'user.domain'};
1.1267    raeburn  2104:         return if ($udom eq 'public');
1.860     raeburn  2105:         if (defined(&domain($udom,'primary'))) {
                   2106:             $uhome=&domain($udom,'primary');
                   2107:         } else {
1.874     albertel 2108:             undef($uhome);
1.860     raeburn  2109:         }
                   2110:     } else {
                   2111:         if (!$uhome) {
                   2112:             if (defined(&domain($udom,'primary'))) {
                   2113:                 $uhome=&domain($udom,'primary');
                   2114:             }
                   2115:         }
                   2116:     }
                   2117:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2118:         my $rep;
                   2119:         if ($namespace =~ /^enc/) {
                   2120:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2121:         } else {
                   2122:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2123:         }
1.866     raeburn  2124:         my %returnhash;
1.875     albertel 2125:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2126:             return %returnhash;
                   2127:         }
1.806     raeburn  2128:         my @pairs=split(/\&/,$rep);
                   2129:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2130:             return @pairs;
                   2131:         }
                   2132:         my $i=0;
                   2133:         foreach my $item (@$storearr) {
                   2134:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2135:             $i++;
                   2136:         }
                   2137:         return %returnhash;
                   2138:     } else {
1.880     banghart 2139:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2140:     }
                   2141: }
                   2142: 
                   2143: # -------------------------------------------- put items in domain db files 
                   2144: 
                   2145: sub put_dom {
1.860     raeburn  2146:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2147:     if (!$udom) {
                   2148:         $udom=$env{'user.domain'};
                   2149:         if (defined(&domain($udom,'primary'))) {
                   2150:             $uhome=&domain($udom,'primary');
                   2151:         } else {
1.874     albertel 2152:             undef($uhome);
1.860     raeburn  2153:         }
                   2154:     } else {
                   2155:         if (!$uhome) {
                   2156:             if (defined(&domain($udom,'primary'))) {
                   2157:                 $uhome=&domain($udom,'primary');
                   2158:             }
                   2159:         }
                   2160:     } 
                   2161:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2162:         my $items='';
                   2163:         foreach my $item (keys(%$storehash)) {
                   2164:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2165:         }
                   2166:         $items=~s/\&$//;
1.1344    raeburn  2167:         if ($namespace =~ /^enc/) {
                   2168:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2169:         } else {
                   2170:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2171:         }
1.806     raeburn  2172:     } else {
1.860     raeburn  2173:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2174:     }
                   2175: }
                   2176: 
1.1023    raeburn  2177: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2178: sub newput_dom {
1.1023    raeburn  2179:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2180:     my $result;
                   2181:     if (!$udom) {
                   2182:         $udom=$env{'user.domain'};
                   2183:     }
1.1023    raeburn  2184:     if ($udom) {
                   2185:         my $uname = &get_domainconfiguser($udom);
                   2186:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2187:     }
                   2188:     return $result;
                   2189: }
                   2190: 
1.1023    raeburn  2191: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2192: sub del_dom {
1.1023    raeburn  2193:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2194:     if (ref($storearr) eq 'ARRAY') {
                   2195:         if (!$udom) {
                   2196:             $udom=$env{'user.domain'};
                   2197:         }
1.1023    raeburn  2198:         if ($udom) {
                   2199:             my $uname = &get_domainconfiguser($udom); 
                   2200:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2201:         }
                   2202:     }
                   2203: }
                   2204: 
1.1023    raeburn  2205: # ----------------------------------construct domainconfig user for a domain 
                   2206: sub get_domainconfiguser {
                   2207:     my ($udom) = @_;
                   2208:     return $udom.'-domainconfig';
                   2209: }
                   2210: 
1.837     raeburn  2211: sub retrieve_inst_usertypes {
                   2212:     my ($udom) = @_;
                   2213:     my (%returnhash,@order);
1.989     raeburn  2214:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2215:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2216:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2217:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2218:     } else {
                   2219:         if (defined(&domain($udom,'primary'))) {
                   2220:             my $uhome=&domain($udom,'primary');
                   2221:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2222:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2223:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2224:                 return (\%returnhash,\@order);
                   2225:             }
                   2226:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2227:             my @pairs=split(/\&/,$hashitems);
                   2228:             foreach my $item (@pairs) {
                   2229:                 my ($key,$value)=split(/=/,$item,2);
                   2230:                 $key = &unescape($key);
                   2231:                 next if ($key =~ /^error: 2 /);
                   2232:                 $returnhash{$key}=&thaw_unescape($value);
                   2233:             }
                   2234:             my @esc_order = split(/\&/,$orderitems);
                   2235:             foreach my $item (@esc_order) {
                   2236:                 push(@order,&unescape($item));
                   2237:             }
                   2238:         } else {
1.1256    raeburn  2239:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2240:         }
1.1256    raeburn  2241:         return (\%returnhash,\@order);
1.837     raeburn  2242:     }
                   2243: }
                   2244: 
1.868     raeburn  2245: sub is_domainimage {
                   2246:     my ($url) = @_;
1.1306    raeburn  2247:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2248:         if (&domain($1) ne '') {
                   2249:             return '1';
                   2250:         }
                   2251:     }
                   2252:     return;
                   2253: }
                   2254: 
1.899     raeburn  2255: sub inst_directory_query {
                   2256:     my ($srch) = @_;
                   2257:     my $udom = $srch->{'srchdomain'};
                   2258:     my %results;
                   2259:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2260:     my $outcome;
1.899     raeburn  2261:     if ($homeserver ne '') {
1.1357    raeburn  2262:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2263:             if ($srch->{'srchby'} eq 'email') {
                   2264:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2265:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2266:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2267:                     (($major == 2) && ($minor < 12))) {
                   2268:                     return;
                   2269:                 }
                   2270:             }
                   2271:         }
1.904     albertel 2272: 	my $queryid=&reply("querysend:instdirsearch:".
                   2273: 			   &escape($srch->{'srchby'}).':'.
                   2274: 			   &escape($srch->{'srchterm'}).':'.
                   2275: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2276: 	my $host=&hostname($homeserver);
                   2277: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2278: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2279: 	    return;
                   2280: 	}
                   2281: 	my $response = &get_query_reply($queryid);
                   2282: 	my $maxtries = 5;
                   2283: 	my $tries = 1;
                   2284: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2285: 	    $response = &get_query_reply($queryid);
                   2286: 	    $tries ++;
                   2287: 	}
                   2288: 
                   2289:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2290:             if ($response eq 'unavailable') {
                   2291:                 $outcome = $response;
                   2292:             } else {
                   2293:                 $outcome = 'ok';
                   2294:                 my @matches = split(/\n/,$response);
                   2295:                 foreach my $match (@matches) {
                   2296:                     my ($key,$value) = split(/=/,$match);
                   2297:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2298:                 }
1.899     raeburn  2299:             }
                   2300:         }
                   2301:     }
1.909     raeburn  2302:     return ($outcome,%results);
1.899     raeburn  2303: }
                   2304: 
                   2305: sub usersearch {
                   2306:     my ($srch) = @_;
                   2307:     my $dom = $srch->{'srchdomain'};
                   2308:     my %results;
                   2309:     my %libserv = &all_library();
                   2310:     my $query = 'usersearch';
                   2311:     foreach my $tryserver (keys(%libserv)) {
                   2312:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2313:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2314:                 if ($srch->{'srchby'} eq 'email') {
                   2315:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2316:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2317:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2318:                              (($major == 2) && ($minor < 12)));
                   2319:                 }
                   2320:             }
1.899     raeburn  2321:             my $host=&hostname($tryserver);
                   2322:             my $queryid=
1.911     raeburn  2323:                 &reply("querysend:".&escape($query).':'.
                   2324:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2325:                        &escape($srch->{'srchtype'}).':'.
                   2326:                        &escape($srch->{'srchterm'}),$tryserver);
                   2327:             if ($queryid !~/^\Q$host\E\_/) {
                   2328:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2329:                 next;
1.899     raeburn  2330:             }
                   2331:             my $reply = &get_query_reply($queryid);
                   2332:             my $maxtries = 1;
                   2333:             my $tries = 1;
                   2334:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2335:                 $reply = &get_query_reply($queryid);
                   2336:                 $tries ++;
                   2337:             }
                   2338:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2339:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2340:             } else {
1.911     raeburn  2341:                 my @matches;
                   2342:                 if ($reply =~ /\n/) {
                   2343:                     @matches = split(/\n/,$reply);
                   2344:                 } else {
                   2345:                     @matches = split(/\&/,$reply);
                   2346:                 }
1.899     raeburn  2347:                 foreach my $match (@matches) {
                   2348:                     my ($uname,$udom,%userhash);
1.911     raeburn  2349:                     foreach my $entry (split(/:/,$match)) {
                   2350:                         my ($key,$value) =
                   2351:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2352:                         $userhash{$key} = $value;
                   2353:                         if ($key eq 'username') {
                   2354:                             $uname = $value;
                   2355:                         } elsif ($key eq 'domain') {
                   2356:                             $udom = $value;
1.911     raeburn  2357:                         }
1.899     raeburn  2358:                     }
                   2359:                     $results{$uname.':'.$udom} = \%userhash;
                   2360:                 }
                   2361:             }
                   2362:         }
                   2363:     }
                   2364:     return %results;
                   2365: }
                   2366: 
1.912     raeburn  2367: sub get_instuser {
                   2368:     my ($udom,$uname,$id) = @_;
                   2369:     my $homeserver = &domain($udom,'primary');
                   2370:     my ($outcome,%results);
                   2371:     if ($homeserver ne '') {
                   2372:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2373:                            &escape($id).':'.&escape($udom),$homeserver);
                   2374:         my $host=&hostname($homeserver);
                   2375:         if ($queryid !~/^\Q$host\E\_/) {
                   2376:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2377:             return;
                   2378:         }
                   2379:         my $response = &get_query_reply($queryid);
                   2380:         my $maxtries = 5;
                   2381:         my $tries = 1;
                   2382:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2383:             $response = &get_query_reply($queryid);
                   2384:             $tries ++;
                   2385:         }
                   2386:         if (!&error($response) && $response ne 'refused') {
                   2387:             if ($response eq 'unavailable') {
                   2388:                 $outcome = $response;
                   2389:             } else {
                   2390:                 $outcome = 'ok';
                   2391:                 my @matches = split(/\n/,$response);
                   2392:                 foreach my $match (@matches) {
                   2393:                     my ($key,$value) = split(/=/,$match);
                   2394:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2395:                 }
                   2396:             }
                   2397:         }
                   2398:     }
                   2399:     my %userinfo;
                   2400:     if (ref($results{$uname}) eq 'HASH') {
                   2401:         %userinfo = %{$results{$uname}};
                   2402:     } 
                   2403:     return ($outcome,%userinfo);
                   2404: }
                   2405: 
1.1290    raeburn  2406: sub get_multiple_instusers {
                   2407:     my ($udom,$users,$caller) = @_;
                   2408:     my ($outcome,$results);
                   2409:     if (ref($users) eq 'HASH') {
                   2410:         my $count = keys(%{$users}); 
                   2411:         my $requested = &freeze_escape($users);
                   2412:         my $homeserver = &domain($udom,'primary');
                   2413:         if ($homeserver ne '') {
                   2414:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2415:             my $host=&hostname($homeserver);
                   2416:             if ($queryid !~/^\Q$host\E\_/) {
                   2417:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2418:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2419:                 return ($outcome,$results);
                   2420:             }
                   2421:             my $response = &get_query_reply($queryid);
                   2422:             my $maxtries = 5;
                   2423:             if ($count > 100) {
                   2424:                 $maxtries = 1+int($count/20);
                   2425:             }
                   2426:             my $tries = 1;
                   2427:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2428:                 $response = &get_query_reply($queryid);
                   2429:                 $tries ++;
                   2430:             }
                   2431:             if ($response eq '') {
                   2432:                 $results = {};
                   2433:                 foreach my $key (keys(%{$users})) {
                   2434:                     my ($uname,$id);
                   2435:                     if ($caller eq 'id') {
                   2436:                         $id = $key;
                   2437:                     } else {
                   2438:                         $uname = $key;
                   2439:                     }
                   2440:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2441:                     $outcome = $resp;
1.1290    raeburn  2442:                     if ($resp eq 'ok') {
                   2443:                         %{$results} = (%{$results}, %info);
                   2444:                     } else {
                   2445:                         last;
                   2446:                     }
                   2447:                 }
                   2448:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2449:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2450:                     $outcome = $response;
                   2451:                 } else {
1.1291    raeburn  2452:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2453:                     if ($outcome eq 'ok') {
                   2454:                         $results = &thaw_unescape($userdata); 
                   2455:                     }
                   2456:                 }
                   2457:             }
                   2458:         }
                   2459:     }
                   2460:     return ($outcome,$results);
                   2461: }
                   2462: 
1.912     raeburn  2463: sub inst_rulecheck {
1.923     raeburn  2464:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2465:     my %returnhash;
                   2466:     if ($udom ne '') {
                   2467:         if (ref($rules) eq 'ARRAY') {
                   2468:             @{$rules} = map {&escape($_);} (@{$rules});
                   2469:             my $rulestr = join(':',@{$rules});
                   2470:             my $homeserver=&domain($udom,'primary');
                   2471:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2472:                 my $response;
                   2473:                 if ($item eq 'username') {                
                   2474:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2475:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2476:                                               $homeserver));
1.923     raeburn  2477:                 } elsif ($item eq 'id') {
                   2478:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2479:                                               ':'.&escape($id).':'.$rulestr,
                   2480:                                               $homeserver));
1.945     raeburn  2481:                 } elsif ($item eq 'selfcreate') {
                   2482:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2483:                                                &escape($udom).':'.&escape($uname).
                   2484:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2485:                 }
1.912     raeburn  2486:                 if ($response ne 'refused') {
                   2487:                     my @pairs=split(/\&/,$response);
                   2488:                     foreach my $item (@pairs) {
                   2489:                         my ($key,$value)=split(/=/,$item,2);
                   2490:                         $key = &unescape($key);
                   2491:                         next if ($key =~ /^error: 2 /);
                   2492:                         $returnhash{$key}=&thaw_unescape($value);
                   2493:                     }
                   2494:                 }
                   2495:             }
                   2496:         }
                   2497:     }
                   2498:     return %returnhash;
                   2499: }
                   2500: 
                   2501: sub inst_userrules {
1.923     raeburn  2502:     my ($udom,$check) = @_;
1.912     raeburn  2503:     my (%ruleshash,@ruleorder);
                   2504:     if ($udom ne '') {
                   2505:         my $homeserver=&domain($udom,'primary');
                   2506:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2507:             my $response;
                   2508:             if ($check eq 'id') {
                   2509:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2510:                                  $homeserver);
1.943     raeburn  2511:             } elsif ($check eq 'email') {
                   2512:                 $response=&reply('instemailrules:'.&escape($udom),
                   2513:                                  $homeserver);
1.923     raeburn  2514:             } else {
                   2515:                 $response=&reply('instuserrules:'.&escape($udom),
                   2516:                                  $homeserver);
                   2517:             }
1.912     raeburn  2518:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2519:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2520:                 ($response ne 'no_such_host')) {
                   2521:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2522:                 my @pairs=split(/\&/,$hashitems);
                   2523:                 foreach my $item (@pairs) {
                   2524:                     my ($key,$value)=split(/=/,$item,2);
                   2525:                     $key = &unescape($key);
                   2526:                     next if ($key =~ /^error: 2 /);
                   2527:                     $ruleshash{$key}=&thaw_unescape($value);
                   2528:                 }
                   2529:                 my @esc_order = split(/\&/,$orderitems);
                   2530:                 foreach my $item (@esc_order) {
                   2531:                     push(@ruleorder,&unescape($item));
                   2532:                 }
                   2533:             }
                   2534:         }
                   2535:     }
                   2536:     return (\%ruleshash,\@ruleorder);
                   2537: }
                   2538: 
1.976     raeburn  2539: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2540: 
                   2541: sub get_domain_defaults {
1.1240    raeburn  2542:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2543:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2544:     my $cachetime = 60*60*24;
1.1240    raeburn  2545:     unless ($ignore_cache) {
                   2546:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2547:         if (defined($cached)) {
                   2548:             if (ref($result) eq 'HASH') {
                   2549:                 return %{$result};
                   2550:             }
1.943     raeburn  2551:         }
                   2552:     }
                   2553:     my %domdefaults;
                   2554:     my %domconfig =
1.989     raeburn  2555:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2556:                                   'requestcourses','inststatus',
1.1183    raeburn  2557:                                   'coursedefaults','usersessions',
1.1258    raeburn  2558:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2559:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2560:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2561:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2562:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2563:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2564:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2565:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2566:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2567:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2568:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2569:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2570:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2571:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2572:     } else {
                   2573:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2574:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2575:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2576:     }
1.976     raeburn  2577:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2578:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2579:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2580:         } else {
                   2581:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2582:         }
1.1177    raeburn  2583:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2584:         foreach my $item (@usertools) {
                   2585:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2586:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2587:             }
                   2588:         }
1.1229    raeburn  2589:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2590:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2591:         }
1.976     raeburn  2592:     }
1.985     raeburn  2593:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2594:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2595:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2596:         }
                   2597:     }
1.1183    raeburn  2598:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2599:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2600:     }
1.989     raeburn  2601:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2602:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2603:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2604:         }
                   2605:     }
1.1047    raeburn  2606:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2607:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2608:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2609:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2610:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2611:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2612:         }
1.1254    raeburn  2613:         foreach my $type (@coursetypes) {
                   2614:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2615:                 unless ($type eq 'community') {
                   2616:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2617:                 }
                   2618:             }
                   2619:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2620:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2621:             }
1.1277    raeburn  2622:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2623:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2624:                     $domdefaults{$type.'postsubtimeout'} = 
                   2625:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2626:                 }
                   2627:             }
1.1230    raeburn  2628:         }
1.1286    raeburn  2629:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2630:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2631:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2632:                 if (@clonecodes) {
                   2633:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2634:                 }
                   2635:             }
                   2636:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2637:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2638:         }
1.1356    raeburn  2639:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2640:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2641:         } 
1.1047    raeburn  2642:     }
1.1073    raeburn  2643:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2644:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2645:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2646:         }
                   2647:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2648:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2649:         }
1.1279    raeburn  2650:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2651:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2652:         }
1.1073    raeburn  2653:     }
1.1254    raeburn  2654:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2655:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2656:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2657:                             'approval','limit');
                   2658:             foreach my $type (@coursetypes) {
                   2659:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2660:                     my @mgrdc = ();
                   2661:                     foreach my $item (@settings) {
                   2662:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2663:                             push(@mgrdc,$item);
                   2664:                         }
                   2665:                     }
                   2666:                     if (@mgrdc) {
                   2667:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2668:                     }
                   2669:                 }
                   2670:             }
                   2671:         }
                   2672:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2673:             foreach my $type (@coursetypes) {
                   2674:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2675:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2676:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2677:                     }
                   2678:                 }
                   2679:             }
                   2680:         }
                   2681:     }
1.1258    raeburn  2682:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2683:         $domdefaults{'catauth'} = 'std';
                   2684:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2685:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2686:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2687:         }
                   2688:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2689:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2690:         }
                   2691:     }
1.1315    raeburn  2692:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2693:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2694:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2695:         }
1.1338    raeburn  2696:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2697:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2698:         }
                   2699:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2700:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2701:         }
                   2702:     }
1.1320    raeburn  2703:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2704:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2705:         foreach my $prefix (@prefixes) {
                   2706:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2707:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2708:             }
                   2709:         }
                   2710:     }
1.1314    raeburn  2711:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2712:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2713:     }
1.1332    raeburn  2714:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2715:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2716:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2717:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2718:         }
                   2719:     }
1.1219    raeburn  2720:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2721:     return %domdefaults;
                   2722: }
                   2723: 
1.1412    raeburn  2724: sub get_dom_cats {
                   2725:     my ($dom) = @_;
                   2726:     return unless (&domain($dom));
                   2727:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2728:     unless (defined($cached)) {
                   2729:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2730:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2731:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2732:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2733:             } else {
                   2734:                 $cats = {};
                   2735:             }
                   2736:         } else {
                   2737:             $cats = {};
                   2738:         }
                   2739:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2740:     }
1.1413    raeburn  2741:     return $cats;
                   2742: }
                   2743: 
                   2744: sub get_dom_instcats {
                   2745:     my ($dom) = @_;
                   2746:     return unless (&domain($dom));
                   2747:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2748:     unless (defined($cached)) {
                   2749:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2750:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2751:         if ($totcodes > 0) {
                   2752:             my $caller = 'global';
                   2753:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2754:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2755:                 $instcats = {
                   2756:                                 codes => \%codes,
                   2757:                                 codetitles => \@codetitles,
                   2758:                                 cat_titles => \%cat_titles,
                   2759:                                 cat_order => \%cat_order,
                   2760:                             };
                   2761:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2762:             }
                   2763:         }
                   2764:     }
                   2765:     return $instcats;
                   2766: }
                   2767: 
                   2768: sub retrieve_instcodes {
                   2769:     my ($coursecodes,$dom) = @_;
                   2770:     my $totcodes;
                   2771:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2772:     foreach my $course (keys(%courses)) {
                   2773:         if (ref($courses{$course}) eq 'HASH') {
                   2774:             if ($courses{$course}{'inst_code'} ne '') {
                   2775:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2776:                 $totcodes ++;
                   2777:             }
                   2778:         }
                   2779:     }
                   2780:     return $totcodes;
1.1412    raeburn  2781: }
                   2782: 
1.1311    raeburn  2783: sub course_portal_url {
                   2784:     my ($cnum,$cdom) = @_;
                   2785:     my $chome = &homeserver($cnum,$cdom);
                   2786:     my $hostname = &hostname($chome);
                   2787:     my $protocol = $protocol{$chome};
                   2788:     $protocol = 'http' if ($protocol ne 'https');
                   2789:     my %domdefaults = &get_domain_defaults($cdom);
                   2790:     my $firsturl;
                   2791:     if ($domdefaults{'portal_def'}) {
                   2792:         $firsturl = $domdefaults{'portal_def'};
                   2793:     } else {
                   2794:         $firsturl = $protocol.'://'.$hostname;
                   2795:     }
                   2796:     return $firsturl;
                   2797: }
                   2798: 
1.1407    raeburn  2799: # --------------------------------------------- Get domain config for passwords
                   2800: 
                   2801: sub get_passwdconf {
                   2802:     my ($dom) = @_;
                   2803:     my (%passwdconf,$gotconf,$lookup);
                   2804:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2805:     if (defined($cached)) {
                   2806:         if (ref($result) eq 'HASH') {
                   2807:             %passwdconf = %{$result};
                   2808:             $gotconf = 1;
                   2809:         }
                   2810:     }
                   2811:     unless ($gotconf) {
                   2812:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2813:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2814:             %passwdconf = %{$domconfig{'passwords'}};
                   2815:         }
                   2816:         my $cachetime = 24*60*60;
                   2817:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2818:     }
                   2819:     return %passwdconf;
                   2820: }
                   2821: 
1.344     www      2822: # --------------------------------------------------- Assign a key to a student
                   2823: 
                   2824: sub assign_access_key {
1.364     www      2825: #
                   2826: # a valid key looks like uname:udom#comments
                   2827: # comments are being appended
                   2828: #
1.498     www      2829:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2830:     $kdom=
1.620     albertel 2831:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2832:     $knum=
1.620     albertel 2833:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2834:     $cdom=
1.620     albertel 2835:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2836:     $cnum=
1.620     albertel 2837:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2838:     $udom=$env{'user.name'} unless (defined($udom));
                   2839:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2840:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2841:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2842:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2843:                                                   # assigned to this person
                   2844:                                                   # - this should not happen,
1.345     www      2845:                                                   # unless something went wrong
                   2846:                                                   # the first time around
                   2847: # ready to assign
1.364     www      2848:         $logentry=$1.'; '.$logentry;
1.496     www      2849:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2850:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2851: # key now belongs to user
1.346     www      2852: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2853:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2854:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2855:                 return 'ok';
                   2856:             } else {
                   2857:                 return 
                   2858:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2859: 	    }
                   2860:         } else {
                   2861:             return 'error: Could not assign key, try again later.';
                   2862:         }
1.364     www      2863:     } elsif (!$existing{$ckey}) {
1.345     www      2864: # the key does not exist
                   2865: 	return 'error: The key does not exist';
                   2866:     } else {
                   2867: # the key is somebody else's
                   2868: 	return 'error: The key is already in use';
                   2869:     }
1.344     www      2870: }
                   2871: 
1.364     www      2872: # ------------------------------------------ put an additional comment on a key
                   2873: 
                   2874: sub comment_access_key {
                   2875: #
                   2876: # a valid key looks like uname:udom#comments
                   2877: # comments are being appended
                   2878: #
                   2879:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2880:     $cdom=
1.620     albertel 2881:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2882:     $cnum=
1.620     albertel 2883:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2884:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2885:     if ($existing{$ckey}) {
                   2886:         $existing{$ckey}.='; '.$logentry;
                   2887: # ready to assign
1.367     www      2888:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2889:                                                  $cdom,$cnum) eq 'ok') {
                   2890: 	    return 'ok';
                   2891:         } else {
                   2892: 	    return 'error: Count not store comment.';
                   2893:         }
                   2894:     } else {
                   2895: # the key does not exist
                   2896: 	return 'error: The key does not exist';
                   2897:     }
                   2898: }
                   2899: 
1.344     www      2900: # ------------------------------------------------------ Generate a set of keys
                   2901: 
                   2902: sub generate_access_keys {
1.364     www      2903:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2904:     $cdom=
1.620     albertel 2905:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2906:     $cnum=
1.620     albertel 2907:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2908:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2909:     unless (($cdom) && ($cnum)) { return 0; }
                   2910:     if ($number>10000) { return 0; }
                   2911:     sleep(2); # make sure don't get same seed twice
                   2912:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2913:     my $total=0;
                   2914:     for (my $i=1;$i<=$number;$i++) {
                   2915:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2916:                   sprintf("%lx",int(100000*rand)).'-'.
                   2917:                   sprintf("%lx",int(100000*rand));
                   2918:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2919:        $newkey=~s/0/h/g; # and also 0 and O
                   2920:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2921:        if ($existing{$newkey}) {
                   2922:            $i--;
                   2923:        } else {
1.364     www      2924: 	  if (&put('accesskeys',
                   2925:               { $newkey => '# generated '.localtime().
1.620     albertel 2926:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2927:                            '; '.$logentry },
                   2928: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2929:               $total++;
                   2930: 	  }
                   2931:        }
                   2932:     }
1.620     albertel 2933:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2934:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2935:     return $total;
                   2936: }
                   2937: 
                   2938: # ------------------------------------------------------- Validate an accesskey
                   2939: 
                   2940: sub validate_access_key {
                   2941:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2942:     $cdom=
1.620     albertel 2943:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2944:     $cnum=
1.620     albertel 2945:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2946:     $udom=$env{'user.domain'} unless (defined($udom));
                   2947:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2948:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2949:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2950: }
                   2951: 
                   2952: # ------------------------------------- Find the section of student in a course
1.652     albertel 2953: sub devalidate_getsection_cache {
                   2954:     my ($udom,$unam,$courseid)=@_;
                   2955:     my $hashid="$udom:$unam:$courseid";
                   2956:     &devalidate_cache_new('getsection',$hashid);
                   2957: }
1.298     matthew  2958: 
1.815     albertel 2959: sub courseid_to_courseurl {
                   2960:     my ($courseid) = @_;
                   2961:     #already url style courseid
                   2962:     return $courseid if ($courseid =~ m{^/});
                   2963: 
                   2964:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2965: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2966: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2967: 	return "/$cdom/$cnum";
                   2968:     }
                   2969: 
                   2970:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2971:     if (exists($courseinfo{'num'})) {
                   2972: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2973:     }
                   2974: 
                   2975:     return undef;
                   2976: }
                   2977: 
1.298     matthew  2978: sub getsection {
                   2979:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2980:     my $cachetime=1800;
1.551     albertel 2981: 
                   2982:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2983:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2984:     if (defined($cached)) { return $result; }
                   2985: 
1.298     matthew  2986:     my %Pending; 
                   2987:     my %Expired;
                   2988:     #
                   2989:     # Each role can either have not started yet (pending), be active, 
                   2990:     #    or have expired.
                   2991:     #
                   2992:     # If there is an active role, we are done.
                   2993:     #
                   2994:     # If there is more than one role which has not started yet, 
                   2995:     #     choose the one which will start sooner
                   2996:     # If there is one role which has not started yet, return it.
                   2997:     #
                   2998:     # If there is more than one expired role, choose the one which ended last.
                   2999:     # If there is a role which has expired, return it.
                   3000:     #
1.815     albertel 3001:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3002:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3003:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3004:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3005:         my $section=$1;
                   3006:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3007:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3008:         my $now=time;
1.548     albertel 3009:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3010:             $Expired{$end}=$section;
                   3011:             next;
                   3012:         }
1.548     albertel 3013:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3014:             $Pending{$start}=$section;
                   3015:             next;
                   3016:         }
1.599     albertel 3017:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3018:     }
                   3019:     #
                   3020:     # Presumedly there will be few matching roles from the above
                   3021:     # loop and the sorting time will be negligible.
                   3022:     if (scalar(keys(%Pending))) {
                   3023:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3024:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3025:     } 
                   3026:     if (scalar(keys(%Expired))) {
                   3027:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3028:         my $time = pop(@sorted);
1.599     albertel 3029:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3030:     }
1.599     albertel 3031:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3032: }
1.70      www      3033: 
1.599     albertel 3034: sub save_cache {
                   3035:     &purge_remembered();
1.722     albertel 3036:     #&Apache::loncommon::validate_page();
1.620     albertel 3037:     undef(%env);
1.780     albertel 3038:     undef($env_loaded);
1.599     albertel 3039: }
1.452     albertel 3040: 
1.599     albertel 3041: my $to_remember=-1;
                   3042: my %remembered;
                   3043: my %accessed;
                   3044: my $kicks=0;
                   3045: my $hits=0;
1.849     albertel 3046: sub make_key {
                   3047:     my ($name,$id) = @_;
1.872     albertel 3048:     if (length($id) > 65 
                   3049: 	&& length(&escape($id)) > 200) {
                   3050: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3051:     }
1.849     albertel 3052:     return &escape($name.':'.$id);
                   3053: }
                   3054: 
1.599     albertel 3055: sub devalidate_cache_new {
                   3056:     my ($name,$id,$debug) = @_;
                   3057:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3058:     my $remembered_id=$name.':'.$id;
1.849     albertel 3059:     $id=&make_key($name,$id);
1.599     albertel 3060:     $memcache->delete($id);
1.1319    damieng  3061:     delete($remembered{$remembered_id});
                   3062:     delete($accessed{$remembered_id});
1.599     albertel 3063: }
                   3064: 
                   3065: sub is_cached_new {
                   3066:     my ($name,$id,$debug) = @_;
1.1319    damieng  3067:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3068:     if (exists($remembered{$remembered_id})) {
                   3069: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3070: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3071: 	$hits++;
1.1319    damieng  3072: 	return ($remembered{$remembered_id},1);
1.599     albertel 3073:     }
1.1319    damieng  3074:     $id=&make_key($name,$id);
1.599     albertel 3075:     my $value = $memcache->get($id);
                   3076:     if (!(defined($value))) {
                   3077: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3078: 	return (undef,undef);
1.416     albertel 3079:     }
1.599     albertel 3080:     if ($value eq '__undef__') {
                   3081: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3082: 	$value=undef;
                   3083:     }
1.1319    damieng  3084:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3085:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3086:     return ($value,1);
                   3087: }
                   3088: 
                   3089: sub do_cache_new {
                   3090:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3091:     my $remembered_id=$name.':'.$id;
1.849     albertel 3092:     $id=&make_key($name,$id);
1.599     albertel 3093:     my $setvalue=$value;
                   3094:     if (!defined($setvalue)) {
                   3095: 	$setvalue='__undef__';
                   3096:     }
1.623     albertel 3097:     if (!defined($time) ) {
                   3098: 	$time=600;
                   3099:     }
1.599     albertel 3100:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3101:     my $result = $memcache->set($id,$setvalue,$time);
                   3102:     if (! $result) {
1.872     albertel 3103: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3104: 	$memcache->disconnect_all();
1.872     albertel 3105:     }
1.600     albertel 3106:     # need to make a copy of $value
1.1319    damieng  3107:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3108:     return $value;
                   3109: }
                   3110: 
                   3111: sub make_room {
1.1319    damieng  3112:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3113: 
1.1319    damieng  3114:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3115:                                     : $value;
1.599     albertel 3116:     if ($to_remember<0) { return; }
1.1319    damieng  3117:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3118:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3119:     my $to_kick;
                   3120:     my $max_time=0;
                   3121:     foreach my $other (keys(%accessed)) {
                   3122: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3123: 	    $to_kick=$other;
                   3124: 	    $max_time=&tv_interval($accessed{$other});
                   3125: 	}
                   3126:     }
                   3127:     delete($remembered{$to_kick});
                   3128:     delete($accessed{$to_kick});
                   3129:     $kicks++;
                   3130:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3131:     return;
                   3132: }
                   3133: 
1.599     albertel 3134: sub purge_remembered {
1.604     albertel 3135:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3136:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3137:     undef(%remembered);
                   3138:     undef(%accessed);
1.428     albertel 3139: }
1.70      www      3140: # ------------------------------------- Read an entry from a user's environment
                   3141: 
                   3142: sub userenvironment {
                   3143:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3144:     my $items;
                   3145:     foreach my $item (@what) {
                   3146:         $items.=&escape($item).'&';
                   3147:     }
                   3148:     $items=~s/\&$//;
1.70      www      3149:     my %returnhash=();
1.1009    raeburn  3150:     my $uhome = &homeserver($unam,$udom);
                   3151:     unless ($uhome eq 'no_host') {
                   3152:         my @answer=split(/\&/, 
                   3153:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3154:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3155:             return %returnhash;
                   3156:         }
1.1009    raeburn  3157:         my $i;
                   3158:         for ($i=0;$i<=$#what;$i++) {
                   3159: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3160:         }
1.70      www      3161:     }
                   3162:     return %returnhash;
1.1       albertel 3163: }
                   3164: 
1.617     albertel 3165: # ---------------------------------------------------------- Get a studentphoto
                   3166: sub studentphoto {
                   3167:     my ($udom,$unam,$ext) = @_;
                   3168:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3169:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3170:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3171:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3172:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3173:             } else {
                   3174:                 my ($result,$perm_reqd)=
1.707     albertel 3175: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3176:                 if ($result eq 'ok') {
                   3177:                     if (!($perm_reqd eq 'yes')) {
                   3178:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3179:                     }
                   3180:                 }
                   3181:             }
                   3182:         }
                   3183:     } else {
                   3184:         my ($result,$perm_reqd) = 
1.707     albertel 3185: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3186:         if ($result eq 'ok') {
                   3187:             if (!($perm_reqd eq 'yes')) {
                   3188:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3189:             }
                   3190:         }
                   3191:     }
                   3192:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3193: }
                   3194: 
                   3195: sub retrievestudentphoto {
                   3196:     my ($udom,$unam,$ext,$type) = @_;
                   3197:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3198:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3199:     if ($ret eq 'ok') {
                   3200:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3201:         if ($type eq 'thumbnail') {
                   3202:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3203:         }
                   3204:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3205:         return $tokenurl;
                   3206:     } else {
                   3207:         if ($type eq 'thumbnail') {
                   3208:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3209:         } else { 
                   3210:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3211:         }
1.617     albertel 3212:     }
                   3213: }
                   3214: 
1.263     www      3215: # -------------------------------------------------------------------- New chat
                   3216: 
                   3217: sub chatsend {
1.724     raeburn  3218:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3219:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3220:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3221:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3222:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3223: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3224: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3225: }
                   3226: 
                   3227: # ------------------------------------------ Find current version of a resource
                   3228: 
                   3229: sub getversion {
                   3230:     my $fname=&clutter(shift);
1.1189    raeburn  3231:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3232:     return &currentversion(&filelocation('',$fname));
                   3233: }
                   3234: 
                   3235: sub currentversion {
                   3236:     my $fname=shift;
                   3237:     my $author=$fname;
                   3238:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3239:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3240:     my $home=&homeserver($uname,$udom);
1.292     www      3241:     if ($home eq 'no_host') { 
                   3242:         return -1; 
                   3243:     }
1.1112    www      3244:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3245:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3246: 	return -1;
                   3247:     }
1.1112    www      3248:     return $answer;
1.263     www      3249: }
                   3250: 
1.1111    www      3251: #
                   3252: # Return special version number of resource if set by override, empty otherwise
                   3253: #
                   3254: sub usedversion {
                   3255:     my $fname=shift;
                   3256:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3257:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3258:     if ($urlversion) { return $urlversion; }
                   3259:     return '';
                   3260: }
                   3261: 
1.1       albertel 3262: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3263: 
1.1       albertel 3264: sub subscribe {
                   3265:     my $fname=shift;
1.761     raeburn  3266:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3267:     $fname=~s/[\n\r]//g;
1.1       albertel 3268:     my $author=$fname;
                   3269:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3270:     my ($udom,$uname)=split(/\//,$author);
                   3271:     my $home=homeserver($uname,$udom);
1.335     albertel 3272:     if ($home eq 'no_host') {
                   3273:         return 'not_found';
1.1       albertel 3274:     }
                   3275:     my $answer=reply("sub:$fname",$home);
1.64      www      3276:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3277: 	$answer.=' by '.$home;
                   3278:     }
1.1       albertel 3279:     return $answer;
                   3280: }
                   3281:     
1.8       www      3282: # -------------------------------------------------------------- Replicate file
                   3283: 
                   3284: sub repcopy {
                   3285:     my $filename=shift;
1.23      www      3286:     $filename=~s/\/+/\//g;
1.1142    raeburn  3287:     my $londocroot = $perlvar{'lonDocRoot'};
                   3288:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3289:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3290:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3291: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3292: 	return &repcopy_userfile($filename);
                   3293:     }
1.532     albertel 3294:     $filename=~s/[\n\r]//g;
1.8       www      3295:     my $transname="$filename.in.transfer";
1.828     www      3296: # FIXME: this should flock
1.607     raeburn  3297:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3298:     my $remoteurl=subscribe($filename);
1.64      www      3299:     if ($remoteurl =~ /^con_lost by/) {
                   3300: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3301:            return 'unavailable';
1.8       www      3302:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3303: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3304: 	   return 'not_found';
1.64      www      3305:     } elsif ($remoteurl =~ /^rejected by/) {
                   3306: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3307:            return 'forbidden';
1.20      www      3308:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3309:            return 'ok';
1.8       www      3310:     } else {
1.290     www      3311:         my $author=$filename;
                   3312:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3313:         my ($udom,$uname)=split(/\//,$author);
                   3314:         my $home=homeserver($uname,$udom);
                   3315:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3316:            my @parts=split(/\//,$filename);
                   3317:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3318:            if ($path ne "$londocroot/res") {
1.8       www      3319:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3320: 	       return 'bad_request';
1.8       www      3321:            }
                   3322:            my $count;
                   3323:            for ($count=5;$count<$#parts;$count++) {
                   3324:                $path.="/$parts[$count]";
                   3325:                if ((-e $path)!=1) {
                   3326: 		   mkdir($path,0777);
                   3327:                }
                   3328:            }
                   3329:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3330:            my $response;
                   3331:            if ($remoteurl =~ m{/raw/}) {
                   3332:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3333:            } else {
                   3334:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3335:            }
1.8       www      3336:            if ($response->is_error()) {
                   3337: 	       unlink($transname);
                   3338:                my $message=$response->status_line;
1.672     albertel 3339:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3340:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3341:                return 'unavailable';
1.8       www      3342:            } else {
1.16      www      3343: 	       if ($remoteurl!~/\.meta$/) {
                   3344:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3345:                   my $mresponse;
                   3346:                   if ($remoteurl =~ m{/raw/}) {
                   3347:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3348:                   } else {
                   3349:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3350:                   }
1.16      www      3351:                   if ($mresponse->is_error()) {
                   3352: 		      unlink($filename.'.meta');
                   3353:                       &logthis(
1.672     albertel 3354:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3355:                   }
                   3356: 	       }
1.8       www      3357:                rename($transname,$filename);
1.607     raeburn  3358:                return 'ok';
1.8       www      3359:            }
1.290     www      3360:        }
1.8       www      3361:     }
1.330     www      3362: }
                   3363: 
                   3364: # ------------------------------------------------ Get server side include body
                   3365: sub ssi_body {
1.381     albertel 3366:     my ($filelink,%form)=@_;
1.606     matthew  3367:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3368:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3369:     }
1.953     www      3370:     my $output='';
                   3371:     my $response;
1.980     raeburn  3372:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3373:        ($output,$response)=&externalssi($filelink);
1.953     www      3374:     } else {
1.1004    droeschl 3375:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3376:        $filelink .= 'inhibitmenu=yes';
1.953     www      3377:        ($output,$response)=&ssi($filelink,%form);
                   3378:     }
1.778     albertel 3379:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3380:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3381:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3382:     if (wantarray) {
                   3383:         return ($output, $response);
                   3384:     } else {
                   3385:         return $output;
                   3386:     }
1.8       www      3387: }
                   3388: 
1.15      www      3389: # --------------------------------------------------------- Server Side Include
                   3390: 
1.782     albertel 3391: sub absolute_url {
                   3392:     my ($host_name) = @_;
                   3393:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3394:     if ($host_name eq '') {
                   3395: 	$host_name = $ENV{'SERVER_NAME'};
                   3396:     }
                   3397:     return $protocol.$host_name;
                   3398: }
                   3399: 
1.942     foxr     3400: #
                   3401: #   Server side include.
                   3402: # Parameters:
                   3403: #  fn     Possibly encrypted resource name/id.
                   3404: #  form   Hash that describes how the rendering should be done
                   3405: #         and other things.
1.944     foxr     3406: # Returns:
1.950     raeburn  3407: #   Scalar context: The content of the response.
                   3408: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3409: #     
1.15      www      3410: sub ssi {
                   3411: 
1.944     foxr     3412:     my ($fn,%form)=@_;
1.23      www      3413:     my $request;
1.711     albertel 3414: 
                   3415:     $form{'no_update_last_known'}=1;
1.895     albertel 3416:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3417:     if (%form) {
1.782     albertel 3418:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3419:       $request->content(join('&',map { 
                   3420:             my $name = escape($_);
                   3421:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3422:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3423:             : &escape($form{$_}) );    
                   3424:         } keys(%form)));
1.23      www      3425:     } else {
1.782     albertel 3426:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3427:     }
                   3428: 
1.15      www      3429:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3430:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3431:     my $islocal;
                   3432:     if (($env{'request.course.id'}) &&
                   3433:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3434:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3435:         ($form{'grade_symb'} ne '') &&
                   3436:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3437:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3438:         $islocal = 1;
                   3439:     }
1.1384    raeburn  3440:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3441:                                                 '','','',$islocal);
1.1182    foxr     3442: 
1.944     foxr     3443:     if (wantarray) {
1.1345    raeburn  3444: 	return ($response->content, $response);
1.944     foxr     3445:     } else {
1.1345    raeburn  3446: 	return $response->content;
1.942     foxr     3447:     }
1.324     www      3448: }
                   3449: 
                   3450: sub externalssi {
                   3451:     my ($url)=@_;
                   3452:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3453:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3454:     if (wantarray) {
                   3455:         return ($response->content, $response);
                   3456:     } else {
                   3457:         return $response->content;
                   3458:     }
1.15      www      3459: }
1.254     www      3460: 
1.1354    raeburn  3461: 
                   3462: # If the local copy of a replicated resource is outdated, trigger a  
                   3463: # connection from the homeserver to flush the delayed queue. If no update 
                   3464: # happens, remove local copies of outdated resource (and corresponding
                   3465: # metadata file).
                   3466: 
1.1352    raeburn  3467: sub remove_stale_resfile {
                   3468:     my ($url) = @_;
1.1354    raeburn  3469:     my $removed;
1.1352    raeburn  3470:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3471:         my $audom = $1;
                   3472:         my $auname = $2;
1.1353    raeburn  3473:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3474:             my $homeserver = &homeserver($auname,$audom);
                   3475:             unless (($homeserver eq 'no_host') ||
                   3476:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3477:                 my $fname = &filelocation('',$url);
                   3478:                 if (-e $fname) {
                   3479:                     my $hostname = &hostname($homeserver);
                   3480:                     if ($hostname) {
1.1397    raeburn  3481:                         my $protocol = $protocol{$homeserver};
                   3482:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3483:                         my $uri = &declutter($url);
                   3484:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3485:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3486:                         if ($response->is_success()) {
                   3487:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3488:                             my $locmodtime = (stat($fname))[9];
                   3489:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3490:                                 my $stale;
                   3491:                                 my $answer = &reply('pong',$homeserver);
                   3492:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3493:                                     sleep(0.2);
                   3494:                                     $locmodtime = (stat($fname))[9];
                   3495:                                     if ($locmodtime < $remmodtime) {
                   3496:                                         my $posstransfer = $fname.'.in.transfer';
                   3497:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3498:                                             $removed = 1;
                   3499:                                         } else {
                   3500:                                             $stale = 1;
                   3501:                                         }
                   3502:                                     } else {
                   3503:                                         $removed = 1;
                   3504:                                     }
                   3505:                                 } else {
                   3506:                                     $stale = 1;
                   3507:                                 }
                   3508:                                 if ($stale) {
                   3509:                                     unlink($fname);
                   3510:                                     if ($uri!~/\.meta$/) {
                   3511:                                         unlink($fname.'.meta');
                   3512:                                     }
                   3513:                                     &reply("unsub:$fname",$homeserver);
                   3514:                                     $removed = 1;
1.1352    raeburn  3515:                                 }
                   3516:                             }
                   3517:                         }
                   3518:                     }
                   3519:                 }
                   3520:             }
                   3521:         }
                   3522:     }
1.1354    raeburn  3523:     return $removed;
1.1352    raeburn  3524: }
                   3525: 
1.492     albertel 3526: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3527: 
                   3528: sub allowuploaded {
                   3529:     my ($srcurl,$url)=@_;
                   3530:     $url=&clutter(&declutter($url));
                   3531:     my $dir=$url;
                   3532:     $dir=~s/\/[^\/]+$//;
                   3533:     my %httpref=();
                   3534:     my $httpurl=&hreflocation('',$url);
                   3535:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3536:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3537: }
1.477     raeburn  3538: 
1.1193    raeburn  3539: #
                   3540: # Determine if the current user should be able to edit a particular resource,
                   3541: # when viewing in course context.
                   3542: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3543: #     Functions.
                   3544: # (b) When displaying folder contents in course editor, used to determine if
                   3545: #     "Edit" link will be displayed alongside resource.
                   3546: #
1.1196    raeburn  3547: #  input: six args -- filename (decluttered), course number, course domain,
                   3548: #                   url, symb (if registered) and group (if this is a group
                   3549: #                   item -- e.g., bulletin board, group page etc.).
                   3550: #  output: array of five scalars -- 
1.1193    raeburn  3551: #          $cfile -- url for file editing if editable on current server
                   3552: #          $home -- homeserver of resource (i.e., for author if published,
                   3553: #                                           or course if uploaded.).
                   3554: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3555: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3556: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3557: #
                   3558: 
                   3559: sub can_edit_resource {
1.1194    raeburn  3560:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3561:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3562: #
                   3563: # For aboutme pages user can only edit his/her own.
                   3564: #
1.1199    raeburn  3565:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3566:         my ($sdom,$sname) = ($1,$2);
                   3567:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3568:             $home = $env{'user.home'};
                   3569:             $cfile = $resurl;
                   3570:             if ($env{'form.forceedit'}) {
                   3571:                 $forceview = 1;
                   3572:             } else {
                   3573:                 $forceedit = 1;
                   3574:             }
                   3575:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3576:         } else {
                   3577:             return;
                   3578:         }
                   3579:     }
                   3580: 
                   3581:     if ($env{'request.course.id'}) {
                   3582:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3583:         if ($group ne '') {
                   3584: # if this is a group homepage or group bulletin board, check group privs
                   3585:             my $allowed = 0;
1.1197    raeburn  3586:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3587:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3588:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3589:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3590:                     $allowed = 1;
                   3591:                 }
1.1197    raeburn  3592:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3593:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3594:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3595:                     $allowed = 1;
                   3596:                 }
                   3597:             }
                   3598:             if ($allowed) {
                   3599:                 $home=&homeserver($cnum,$cdom);
                   3600:                 if ($env{'form.forceedit'}) {
                   3601:                     $forceview = 1;
                   3602:                 } else {
                   3603:                     $forceedit = 1;
                   3604:                 }
                   3605:                 $cfile = $resurl;
                   3606:             } else {
                   3607:                 return;
                   3608:             }
                   3609:         } else {
1.1208    raeburn  3610:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3611:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3612:                     return;
                   3613:                 }
                   3614:             } elsif (!$crsedit) {
1.1194    raeburn  3615: #
                   3616: # No edit allowed where CC has switched to student role.
                   3617: #
                   3618:                 return;
                   3619:             }
                   3620:         }
                   3621:     }
                   3622: 
1.1193    raeburn  3623:     if ($file ne '') {
                   3624:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3625:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3626:                 $uploaded = 1;
                   3627:                 $incourse = 1;
1.1193    raeburn  3628:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3629:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3630:                     if ($env{'form.forceedit'}) {
                   3631:                         $forceview = 1;
                   3632:                     } else {
                   3633:                         $forceedit = 1;
                   3634:                     }
1.1194    raeburn  3635:                 }
                   3636:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3637:                 $incourse = 1;
                   3638:                 if ($env{'form.forceedit'}) {
                   3639:                     $forceview = 1;
                   3640:                 } else {
                   3641:                     $forceedit = 1;
                   3642:                 }
                   3643:                 $cfile = $resurl;
                   3644:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3645:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3646:                     $incourse = 1;
                   3647:                     if ($env{'form.forceedit'}) {
                   3648:                         $forceview = 1;
                   3649:                     } else {
                   3650:                         $forceedit = 1;
                   3651:                     }
                   3652:                     $cfile = $resurl;
1.1199    raeburn  3653:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3654:                     $incourse = 1;
                   3655:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3656:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3657:                     $incourse = 1;
1.1199    raeburn  3658:                     if ($env{'form.forceedit'}) {
                   3659:                         $forceview = 1;
                   3660:                     } else {
                   3661:                         $forceedit = 1;
                   3662:                     }
                   3663:                     $cfile = $resurl;
1.1343    raeburn  3664:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3665:                     $incourse = 1;
                   3666:                     if ($env{'form.forceedit'}) {
                   3667:                         $forceview = 1;
                   3668:                     } else {
                   3669:                         $forceedit = 1;
                   3670:                     }
                   3671:                     $cfile = $resurl;
1.1208    raeburn  3672:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3673:                     $incourse = 1;
                   3674:                     if ($env{'form.forceedit'}) {
                   3675:                         $forceview = 1;
                   3676:                     } else {
                   3677:                         $forceedit = 1;
                   3678:                     }
                   3679:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3680:                 }
                   3681:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3682:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3683:                 if (&is_on_map($template)) { 
                   3684:                     $incourse = 1;
                   3685:                     $forceview = 1;
                   3686:                     $cfile = $template;
1.1193    raeburn  3687:                 }
1.1199    raeburn  3688:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3689:                     $incourse = 1;
                   3690:                     if ($env{'form.forceedit'}) {
                   3691:                         $forceview = 1;
                   3692:                     } else {
                   3693:                         $forceedit = 1;
                   3694:                     }
                   3695:                     $cfile = $resurl;
1.1343    raeburn  3696:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3697:                 $incourse = 1;
                   3698:                 if ($env{'form.forceedit'}) {
                   3699:                     $forceview = 1;
                   3700:                 } else {
                   3701:                     $forceedit = 1;
                   3702:                 }
                   3703:                 $cfile = $resurl;
1.1199    raeburn  3704:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3705:                 $incourse = 1;
                   3706:                 $forceview = 1;
                   3707:                 if ($symb) {
                   3708:                     my ($map,$id,$res)=&decode_symb($symb);
                   3709:                     $env{'request.symb'} = $symb;
                   3710:                     $cfile = &clutter($res);
                   3711:                 } else {
                   3712:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3713:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3714:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3715:                         $cfile = '/adm/wrapper'.$escfile;
                   3716:                     } else {
                   3717:                         $escfile =~ s{^http://}{};
                   3718:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3719:                     }
1.1199    raeburn  3720:                 }
1.1234    raeburn  3721:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3722:                 if ($env{'form.forceedit'}) {
                   3723:                     $forceview = 1;
                   3724:                 } else {
                   3725:                     $forceedit = 1;
                   3726:                 }
                   3727:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3728:             }
                   3729:         }
1.1194    raeburn  3730:         if ($uploaded || $incourse) {
                   3731:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3732:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3733:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3734:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3735:             # Check that the user has permission to edit this resource
                   3736:             my $setpriv = 1;
                   3737:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3738:             if (defined($cfudom)) {
                   3739:                 $home=&homeserver($cfuname,$cfudom);
                   3740:                 $cfile=$file;
                   3741:             }
                   3742:         }
1.1194    raeburn  3743:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3744:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3745:             my @ids=&current_machine_ids();
                   3746:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3747:                 $switchserver=1;
                   3748:             }
                   3749:         }
                   3750:     }
1.1194    raeburn  3751:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3752: }
                   3753: 
                   3754: sub is_course_upload {
                   3755:     my ($file,$cnum,$cdom) = @_;
                   3756:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3757:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3758:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3759:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3760:         return 1;
                   3761:     }
                   3762:     return;
                   3763: }
                   3764: 
1.1194    raeburn  3765: sub in_course {
1.1195    raeburn  3766:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3767:     if ($hideprivileged) {
                   3768:         my $skipuser;
1.1219    raeburn  3769:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3770:         my @possdoms = ($cdom);  
                   3771:         if ($coursehash{'checkforpriv'}) { 
                   3772:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3773:         }
                   3774:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3775:             $skipuser = 1;
                   3776:             if ($coursehash{'nothideprivileged'}) {
                   3777:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3778:                     my $user;
                   3779:                     if ($item =~ /:/) {
                   3780:                         $user = $item;
                   3781:                     } else {
                   3782:                         $user = join(':',split(/[\@]/,$item));
                   3783:                     }
                   3784:                     if ($user eq $uname.':'.$udom) {
                   3785:                         undef($skipuser);
                   3786:                         last;
                   3787:                     }
                   3788:                 }
                   3789:             }
                   3790:             if ($skipuser) {
                   3791:                 return 0;
                   3792:             }
                   3793:         }
                   3794:     }
1.1194    raeburn  3795:     $type ||= 'any';
                   3796:     if (!defined($cdom) || !defined($cnum)) {
                   3797:         my $cid  = $env{'request.course.id'};
                   3798:         $cdom = $env{'course.'.$cid.'.domain'};
                   3799:         $cnum = $env{'course.'.$cid.'.num'};
                   3800:     }
                   3801:     my $typesref;
1.1195    raeburn  3802:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3803:         $typesref = ['active','previous','future'];
                   3804:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3805:         $typesref = [$type];
                   3806:     }
                   3807:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3808:                               $typesref,undef,[$cdom]);
                   3809:     my ($tmp) = keys(%roles);
                   3810:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3811:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3812:     if (@course_roles > 0) {
                   3813:         return 1;
                   3814:     }
                   3815:     return 0;
                   3816: }
                   3817: 
1.478     albertel 3818: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3819: # input: action, courseID, current domain, intended
1.637     raeburn  3820: #        path to file, source of file, instruction to parse file for objects,
                   3821: #        ref to hash for embedded objects,
                   3822: #        ref to hash for codebase of java objects.
1.1095    raeburn  3823: #        reference to scalar to accommodate mime type determined
                   3824: #          from File::MMagic if $parser = parse.
1.637     raeburn  3825: #
1.485     raeburn  3826: # output: url to file (if action was uploaddoc), 
                   3827: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3828: #
1.478     albertel 3829: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3830: # course.
1.477     raeburn  3831: #
1.478     albertel 3832: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3833: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3834: #          course's home server.
1.477     raeburn  3835: #
1.478     albertel 3836: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3837: #          be copied from $source (current location) to 
                   3838: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3839: #         and will then be copied to
                   3840: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3841: #         course's home server.
1.485     raeburn  3842: #
1.481     raeburn  3843: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3844: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3845: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3846: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3847: #         in course's home server.
1.637     raeburn  3848: #
1.477     raeburn  3849: 
                   3850: sub process_coursefile {
1.1095    raeburn  3851:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3852:         $mimetype)=@_;
1.477     raeburn  3853:     my $fetchresult;
1.638     albertel 3854:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3855:     if ($action eq 'propagate') {
1.638     albertel 3856:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3857: 			     $home);
1.481     raeburn  3858:     } else {
1.477     raeburn  3859:         my $fpath = '';
                   3860:         my $fname = $file;
1.478     albertel 3861:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3862:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3863:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3864:         if ($action eq 'copy') {
                   3865:             if ($source eq '') {
                   3866:                 $fetchresult = 'no source file';
                   3867:                 return $fetchresult;
                   3868:             } else {
                   3869:                 my $destination = $filepath.'/'.$fname;
                   3870:                 rename($source,$destination);
                   3871:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3872:                                  $home);
1.481     raeburn  3873:             }
                   3874:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3875:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3876:             print $fh $env{'form.'.$source};
1.481     raeburn  3877:             close($fh);
1.637     raeburn  3878:             if ($parser eq 'parse') {
1.1024    raeburn  3879:                 my $mm = new File::MMagic;
1.1095    raeburn  3880:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3881:                 if ($type eq 'text/html') {
1.1024    raeburn  3882:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3883:                     unless ($parse_result eq 'ok') {
                   3884:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3885:                     }
1.637     raeburn  3886:                 }
1.1095    raeburn  3887:                 if (ref($mimetype)) {
                   3888:                     $$mimetype = $type;
                   3889:                 } 
1.637     raeburn  3890:             }
1.477     raeburn  3891:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3892:                                  $home);
1.481     raeburn  3893:             if ($fetchresult eq 'ok') {
                   3894:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3895:             } else {
                   3896:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3897:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3898:                 return '/adm/notfound.html';
                   3899:             }
1.477     raeburn  3900:         }
                   3901:     }
1.485     raeburn  3902:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3903:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3904:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3905:     }
                   3906:     return $fetchresult;
                   3907: }
                   3908: 
1.637     raeburn  3909: sub build_filepath {
                   3910:     my ($fpath) = @_;
                   3911:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3912:     unless ($fpath eq '') {
                   3913:         my @parts=split('/',$fpath);
                   3914:         foreach my $part (@parts) {
                   3915:             $filepath.= '/'.$part;
                   3916:             if ((-e $filepath)!=1) {
                   3917:                 mkdir($filepath,0777);
                   3918:             }
                   3919:         }
                   3920:     }
                   3921:     return $filepath;
                   3922: }
                   3923: 
                   3924: sub store_edited_file {
1.638     albertel 3925:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3926:     my $file = $primary_url;
                   3927:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3928:     my $fpath = '';
                   3929:     my $fname = $file;
                   3930:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3931:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3932:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3933:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3934:     print $fh $content;
                   3935:     close($fh);
1.638     albertel 3936:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3937:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3938: 			  $home);
1.637     raeburn  3939:     if ($$fetchresult eq 'ok') {
                   3940:         return '/uploaded/'.$fpath.'/'.$fname;
                   3941:     } else {
1.638     albertel 3942:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3943: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3944:         return '/adm/notfound.html';
                   3945:     }
                   3946: }
                   3947: 
1.531     albertel 3948: sub clean_filename {
1.831     albertel 3949:     my ($fname,$args)=@_;
1.315     www      3950: # Replace Windows backslashes by forward slashes
1.257     www      3951:     $fname=~s/\\/\//g;
1.831     albertel 3952:     if (!$args->{'keep_path'}) {
                   3953:         # Get rid of everything but the actual filename
                   3954: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3955:     }
1.315     www      3956: # Replace spaces by underscores
                   3957:     $fname=~s/\s+/\_/g;
1.1406    raeburn  3958: # Transliterate non-ascii text to ascii
                   3959:     my $lang = &Apache::lonlocal::current_language();
                   3960:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3961: # Replace all other weird characters by nothing
1.831     albertel 3962:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3963: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3964: # numbers
                   3965:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3966:     return $fname;
                   3967: }
1.1406    raeburn  3968: 
1.1051    raeburn  3969: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3970: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3971: # image with the same aspect ratio as the original, but with dimensions which do 
                   3972: # not exceed $resizewidth and $resizeheight.
                   3973:  
1.984     neumanie 3974: sub resizeImage {
1.1051    raeburn  3975:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3976:     my $ima = Image::Magick->new;
                   3977:     my $resized;
                   3978:     if (-e $img_path) {
                   3979:         $ima->Read($img_path);
                   3980:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3981:             my $width = $ima->Get('width');
                   3982:             my $height = $ima->Get('height');
                   3983:             if ($width > $resizewidth) {
                   3984: 	        my $factor = $width/$resizewidth;
                   3985:                 my $newheight = $height/$factor;
                   3986:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3987:                 $resized = 1;
                   3988:             }
                   3989:         }
                   3990:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3991:             my $width = $ima->Get('width');
                   3992:             my $height = $ima->Get('height');
                   3993:             if ($height > $resizeheight) {
                   3994:                 my $factor = $height/$resizeheight;
                   3995:                 my $newwidth = $width/$factor;
                   3996:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3997:                 $resized = 1;
                   3998:             }
                   3999:         }
                   4000:         if ($resized) {
                   4001:             $ima->Write($img_path);
                   4002:         }
                   4003:     }
                   4004:     return;
1.977     amueller 4005: }
                   4006: 
1.608     albertel 4007: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4008: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4009: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4010: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4011: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4012: #                   if 'coursedoc': upload to the current course
                   4013: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4014: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4015: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4016: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4017: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4018: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4019: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4020: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4021: #        $allfiles - reference to hash for embedded objects
                   4022: #        $codebase - reference to hash for codebase of java objects
                   4023: #        $desuname - username for permanent storage of uploaded file
                   4024: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4025: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4026: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4027: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4028: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4029: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4030: #                    from File::MMagic.
1.858     raeburn  4031: # 
1.686     albertel 4032: # output: url of file in userspace, or error: <message> 
                   4033: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4034: 
1.531     albertel 4035: sub userfileupload {
1.1090    raeburn  4036:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4037:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4038:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4039:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4040:     $fname=&clean_filename($fname);
1.1090    raeburn  4041:     # See if there is anything left
1.257     www      4042:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4043:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4044:     if ($fname =~ /^\./) {
                   4045:         my ($s,$usec) = &gettimeofday();
                   4046:         while (length($usec) < 6) {
                   4047:             $usec = '0'.$usec;
                   4048:         }
                   4049:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4050:     }
1.1090    raeburn  4051:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4052:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4053:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4054:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4055:         my $now = time;
1.1090    raeburn  4056:         my $filepath;
1.1095    raeburn  4057:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4058:              $filepath = 'tmp/helprequests/'.$now;
                   4059:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4060:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4061:                          '_'.$env{'user.domain'}.'/pending';
                   4062:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4063:             my ($docuname,$docudom);
1.1350    raeburn  4064:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4065:                 $docudom = $destudom;
                   4066:             } else {
                   4067:                 $docudom = $env{'user.domain'};
                   4068:             }
1.1350    raeburn  4069:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4070:                 $docuname = $destuname;
                   4071:             } else {
                   4072:                 $docuname = $env{'user.name'};
                   4073:             }
                   4074:             if (exists($env{'form.group'})) {
                   4075:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4076:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4077:             }
                   4078:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4079:             if ($context eq 'canceloverwrite') {
                   4080:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4081:                 if (-e  $tempfile) {
                   4082:                     my @info = stat($tempfile);
                   4083:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4084:                         unlink($tempfile);
                   4085:                     }
                   4086:                 }
                   4087:                 return;
1.523     raeburn  4088:             }
                   4089:         }
1.1090    raeburn  4090:         # Create the directory if not present
1.741     raeburn  4091:         my @parts=split(/\//,$filepath);
                   4092:         my $fullpath = $perlvar{'lonDaemons'};
                   4093:         for (my $i=0;$i<@parts;$i++) {
                   4094:             $fullpath .= '/'.$parts[$i];
                   4095:             if ((-e $fullpath)!=1) {
                   4096:                 mkdir($fullpath,0777);
                   4097:             }
                   4098:         }
1.1359    raeburn  4099:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4100:         print $fh $env{'form.'.$formname};
                   4101:         close($fh);
1.1090    raeburn  4102:         if ($context eq 'existingfile') {
                   4103:             my @info = stat($fullpath.'/'.$fname);
                   4104:             return ($fullpath.'/'.$fname,$info[9]);
                   4105:         } else {
                   4106:             return $fullpath.'/'.$fname;
                   4107:         }
1.523     raeburn  4108:     }
1.995     raeburn  4109:     if ($subdir eq 'scantron') {
                   4110:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4111:     } else {
1.995     raeburn  4112:         $fname="$subdir/$fname";
                   4113:     }
1.1090    raeburn  4114:     if ($context eq 'coursedoc') {
1.638     albertel 4115: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4116: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4117:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4118:             return &finishuserfileupload($docuname,$docudom,
                   4119: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4120: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4121:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4122:         } else {
1.1218    raeburn  4123:             if ($env{'form.folder'}) {
                   4124:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4125:             }
1.638     albertel 4126:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4127: 				       $fname,$formname,$parser,
1.1095    raeburn  4128: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4129:         }
1.719     banghart 4130:     } elsif (defined($destuname)) {
                   4131:         my $docuname=$destuname;
                   4132:         my $docudom=$destudom;
1.860     raeburn  4133: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4134: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4135:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4136:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4137:     } else {
1.638     albertel 4138:         my $docuname=$env{'user.name'};
                   4139:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4140:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4141:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4142:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4143:         }
1.860     raeburn  4144: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4145: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4146:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4147:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4148:     }
1.271     www      4149: }
                   4150: 
                   4151: sub finishuserfileupload {
1.860     raeburn  4152:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4153:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4154:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4155:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4156:   
1.860     raeburn  4157:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4158:     $file=$fname;
                   4159:     if ($fname=~m|/|) {
                   4160:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4161: 	$path.=$fnamepath.'/';
                   4162:     }
1.259     www      4163:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4164:     my $count;
                   4165:     for ($count=4;$count<=$#parts;$count++) {
                   4166:         $filepath.="/$parts[$count]";
                   4167:         if ((-e $filepath)!=1) {
                   4168: 	    mkdir($filepath,0777);
                   4169:         }
                   4170:     }
1.984     neumanie 4171: 
1.258     www      4172: # Save the file
                   4173:     {
1.1359    raeburn  4174: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4175: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4176: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4177: 	    return '/adm/notfound.html';
                   4178: 	}
1.1090    raeburn  4179:         if ($context eq 'overwrite') {
1.1117    foxr     4180:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4181:             my $target = $filepath.'/'.$file;
                   4182:             if (-e $source) {
                   4183:                 my @info = stat($source);
                   4184:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4185:                     unless (&File::Copy::move($source,$target)) {
                   4186:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4187:                         return "Moving from $source failed";
                   4188:                     }
                   4189:                 } else {
                   4190:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4191:                 }
                   4192:             } else {
                   4193:                 return "Temporary file: $source missing";
                   4194:             }
                   4195:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4196: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4197: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4198: 	    return '/adm/notfound.html';
                   4199: 	}
1.570     albertel 4200: 	close(FH);
1.1051    raeburn  4201:         if ($resizewidth && $resizeheight) {
                   4202:             my $mm = new File::MMagic;
                   4203:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4204:             if ($mime_type =~ m{^image/}) {
                   4205: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4206:             }  
1.977     amueller 4207: 	}
1.258     www      4208:     }
1.1152    raeburn  4209:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4210:         if (ref($mimetype)) {
                   4211:             if ($$mimetype eq '') {
                   4212:                 my $mm = new File::MMagic;
                   4213:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4214:                 $$mimetype = $type;
                   4215:             }
                   4216:         }
                   4217:     }
1.1401    raeburn  4218:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4219:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4220:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4221:                                                        $allfiles,$codebase);
                   4222:             unless ($parse_result eq 'ok') {
                   4223:                 &logthis('Failed to parse '.$filepath.$file.
                   4224: 	   	         ' for embedded media: '.$parse_result); 
                   4225:             }
1.637     raeburn  4226:         }
1.1401    raeburn  4227:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4228:         my $format = $env{'form.scantron_format'};
                   4229:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4230:     }
1.860     raeburn  4231:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4232:         my $input = $filepath.'/'.$file;
                   4233:         my $output = $filepath.'/'.'tn-'.$file;
                   4234:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4235:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4236:         system({$args[0]} @args);
1.860     raeburn  4237:         if (-e $filepath.'/'.'tn-'.$file) {
                   4238:             $fetchthumb  = 1; 
                   4239:         }
                   4240:     }
1.858     raeburn  4241:  
1.259     www      4242: # Notify homeserver to grep it
                   4243: #
1.984     neumanie 4244:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4245:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4246:     if ($fetchresult eq 'ok') {
1.860     raeburn  4247:         if ($fetchthumb) {
                   4248:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4249:             if ($thumbresult ne 'ok') {
                   4250:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4251:                          $docuhome.': '.$thumbresult);
                   4252:             }
                   4253:         }
1.259     www      4254: #
1.258     www      4255: # Return the URL to it
1.494     albertel 4256:         return '/uploaded/'.$path.$file;
1.263     www      4257:     } else {
1.494     albertel 4258:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4259: 		 ': '.$fetchresult);
1.263     www      4260:         return '/adm/notfound.html';
1.858     raeburn  4261:     }
1.493     albertel 4262: }
                   4263: 
1.637     raeburn  4264: sub extract_embedded_items {
1.961     raeburn  4265:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4266:     my @state = ();
1.1164    raeburn  4267:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4268:     my %javafiles = (
                   4269:                       codebase => '',
                   4270:                       code => '',
                   4271:                       archive => ''
                   4272:                     );
                   4273:     my %mediafiles = (
                   4274:                       src => '',
                   4275:                       movie => '',
                   4276:                      );
1.648     raeburn  4277:     my $p;
                   4278:     if ($content) {
                   4279:         $p = HTML::LCParser->new($content);
                   4280:     } else {
1.961     raeburn  4281:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4282:     }
1.641     albertel 4283:     while (my $t=$p->get_token()) {
1.640     albertel 4284: 	if ($t->[0] eq 'S') {
                   4285: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4286: 	    push(@state, $tagname);
1.648     raeburn  4287:             if (lc($tagname) eq 'allow') {
                   4288:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4289:             }
1.640     albertel 4290: 	    if (lc($tagname) eq 'img') {
                   4291: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4292: 	    }
1.886     albertel 4293: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4294:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4295:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4296:                 }
1.886     albertel 4297: 	    }
1.645     raeburn  4298:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4299:                 my $src;
1.645     raeburn  4300:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4301:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4302:                 } else {
1.1164    raeburn  4303:                     if ($attr->{'src'} ne '') {
                   4304:                         $src = $attr->{'src'};
                   4305:                         &add_filetype($allfiles,$src,'src');
                   4306:                     }
                   4307:                 }
                   4308:                 my $text = $p->get_trimmed_text();
                   4309:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4310:                     my @swfargs = split(/,/,$1);
                   4311:                     foreach my $item (@swfargs) {
                   4312:                         $item =~ s/["']//g;
                   4313:                         $item =~ s/^\s+//;
                   4314:                         $item =~ s/\s+$//;
                   4315:                     }
                   4316:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4317:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4318:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4319:                         } else {
                   4320:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4321:                         }
                   4322:                     }
1.645     raeburn  4323:                 }
                   4324:             }
                   4325:             if (lc($tagname) eq 'link') {
                   4326:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4327:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4328:                 }
                   4329:             }
1.640     albertel 4330: 	    if (lc($tagname) eq 'object' ||
                   4331: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4332: 		foreach my $item (keys(%javafiles)) {
                   4333: 		    $javafiles{$item} = '';
                   4334: 		}
1.1164    raeburn  4335:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4336:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4337:                 }
1.640     albertel 4338: 	    }
                   4339: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4340: 		my $name = lc($attr->{'name'});
                   4341: 		foreach my $item (keys(%javafiles)) {
                   4342: 		    if ($name eq $item) {
                   4343: 			$javafiles{$item} = $attr->{'value'};
                   4344: 			last;
                   4345: 		    }
                   4346: 		}
1.1164    raeburn  4347:                 my $pathfrom;
1.640     albertel 4348: 		foreach my $item (keys(%mediafiles)) {
                   4349: 		    if ($name eq $item) {
1.1164    raeburn  4350:                         $pathfrom = $attr->{'value'};
                   4351:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4352: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4353: 			last;
                   4354: 		    }
                   4355: 		}
1.1164    raeburn  4356:                 if ($name eq 'flashvars') {
                   4357:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4358:                 }
                   4359:                 if ($pathfrom ne '') {
                   4360:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4361:                                          $pathfrom);
                   4362:                 }
1.640     albertel 4363: 	    }
                   4364: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4365: 		foreach my $item (keys(%javafiles)) {
                   4366: 		    if ($attr->{$item}) {
                   4367: 			$javafiles{$item} = $attr->{$item};
                   4368: 			last;
                   4369: 		    }
                   4370: 		}
                   4371: 		foreach my $item (keys(%mediafiles)) {
                   4372: 		    if ($attr->{$item}) {
                   4373: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4374: 			last;
                   4375: 		    }
                   4376: 		}
1.1164    raeburn  4377:                 if (lc($tagname) eq 'embed') {
                   4378:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4379:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4380:                                              $attr->{'src'});
                   4381:                     }
                   4382:                 }
1.640     albertel 4383: 	    }
1.1243    raeburn  4384:             if (lc($tagname) eq 'iframe') {
                   4385:                 my $src = $attr->{'src'} ;
                   4386:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4387:                     &add_filetype($allfiles,$src,'src');
                   4388:                 } elsif ($src =~ m{^/}) {
                   4389:                     if ($env{'request.course.id'}) {
                   4390:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4391:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4392:                         my $url = &hreflocation('',$fullpath);
                   4393:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4394:                             my $relpath = $1;
                   4395:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4396:                                 &add_filetype($allfiles,$1,'src');
                   4397:                             }
                   4398:                         }
                   4399:                     }
                   4400:                 }
                   4401:             }
1.1164    raeburn  4402:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4403:                 pop(@state);
1.1164    raeburn  4404:             }
1.640     albertel 4405: 	} elsif ($t->[0] eq 'E') {
                   4406: 	    my ($tagname) = ($t->[1]);
                   4407: 	    if ($javafiles{'codebase'} ne '') {
                   4408: 		$javafiles{'codebase'} .= '/';
                   4409: 	    }  
                   4410: 	    if (lc($tagname) eq 'applet' ||
                   4411: 		lc($tagname) eq 'object' ||
                   4412: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4413: 		) {
                   4414: 		foreach my $item (keys(%javafiles)) {
                   4415: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4416: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4417: 			&add_filetype($allfiles,$file,$item);
                   4418: 		    }
                   4419: 		}
                   4420: 	    } 
                   4421: 	    pop @state;
                   4422: 	}
                   4423:     }
1.1164    raeburn  4424:     foreach my $id (sort(keys(%flashvars))) {
                   4425:         if ($shockwave{$id} ne '') {
                   4426:             my @pairs = split(/\&/,$flashvars{$id});
                   4427:             foreach my $pair (@pairs) {
                   4428:                 my ($key,$value) = split(/\=/,$pair);
                   4429:                 if ($key eq 'thumb') {
                   4430:                     &add_filetype($allfiles,$value,$key);
                   4431:                 } elsif ($key eq 'content') {
                   4432:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4433:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4434:                     if ($ext ne '') {
                   4435:                         &add_filetype($allfiles,$path.$value,$ext);
                   4436:                     }
                   4437:                 }
                   4438:             }
                   4439:         }
                   4440:     }
1.637     raeburn  4441:     return 'ok';
                   4442: }
                   4443: 
1.639     albertel 4444: sub add_filetype {
                   4445:     my ($allfiles,$file,$type)=@_;
                   4446:     if (exists($allfiles->{$file})) {
                   4447: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4448: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4449: 	}
                   4450:     } else {
                   4451: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4452:     }
                   4453: }
                   4454: 
1.1164    raeburn  4455: sub embedded_dependency {
                   4456:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4457:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4458:         if (($identifier ne '') &&
                   4459:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4460:             ($pathfrom ne '')) {
                   4461:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4462:             foreach my $dep (@{$related->{$identifier}}) {
                   4463:                 &add_filetype($allfiles,$path.$dep,'object');
                   4464:             }
                   4465:         }
                   4466:     }
                   4467:     return;
                   4468: }
                   4469: 
1.1401    raeburn  4470: sub bubblesheet_converter {
                   4471:     my ($cdom,$fullpath,$config,$format) = @_;
                   4472:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4473:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4474:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4475:         my (%csvcols,%csvoptions);
                   4476:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4477:             %csvcols = %{$config->{'fields'}};
                   4478:         }
                   4479:         if (ref($config->{'options'}) eq 'HASH') {
                   4480:             %csvoptions = %{$config->{'options'}};
                   4481:         }
1.1401    raeburn  4482:         my %csvbynum = reverse(%csvcols);
                   4483:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4484:         if (keys(%scantronconf)) {
                   4485:             my %bynum = (
                   4486:                           $scantronconf{CODEstart} => 'CODEstart',
                   4487:                           $scantronconf{IDstart}   => 'IDstart',
                   4488:                           $scantronconf{PaperID}   => 'PaperID',
                   4489:                           $scantronconf{FirstName} => 'FirstName',
                   4490:                           $scantronconf{LastName}  => 'LastName',
                   4491:                           $scantronconf{Qstart}    => 'Qstart',
                   4492:                         );
                   4493:             my @ordered;
                   4494:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4495:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4496:             }
                   4497:             my %mapstart = (
                   4498:                               CODEstart => 'CODE',
                   4499:                               IDstart   => 'ID',
                   4500:                               PaperID   => 'PaperID',
                   4501:                               FirstName => 'FirstName',
                   4502:                               LastName  => 'LastName',
                   4503:                               Qstart    => 'FirstQuestion',
                   4504:                            );
                   4505:             my %maplength = (
                   4506:                               CODEstart => 'CODElength',
                   4507:                               IDstart   => 'IDlength',
                   4508:                               PaperID   => 'PaperIDlength',
                   4509:                               FirstName => 'FirstNamelength',
                   4510:                               LastName  => 'LastNamelength',
                   4511:             );
                   4512:             if (open(my $fh,'<',$fullpath)) {
                   4513:                 my $output;
1.1403    raeburn  4514:                 my %lettdig = &letter_to_digits();
                   4515:                 my %diglett = reverse(%lettdig);
                   4516:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4517:                 my $num = 0;
1.1401    raeburn  4518:                 while (my $line=<$fh>) {
1.1404    raeburn  4519:                     $num ++;
                   4520:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4521:                     $line =~ s{[\r\n]+$}{};
                   4522:                     my %found;
                   4523:                     my @values = split(/,/,$line);
                   4524:                     my ($qstart,$record);
                   4525:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4526:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4527:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4528:                             if ($values[$i] eq '') {
                   4529:                                 $values[$i] = $scantronconf{'Qoff'};
                   4530:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4531:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4532:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4533:                                 }
                   4534:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4535:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4536:                                     $values[$i] = $diglett{$values[$i]};
                   4537:                                 }
                   4538:                             } else {
                   4539:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4540:                                     my $digit;
                   4541:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4542:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4543:                                         if ($values[$i] eq 'J') {
                   4544:                                             $digit += $numletts;
                   4545:                                         }
                   4546:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4547:                                         $digit = $values[$i]-1;
                   4548:                                         if ($values[$i] eq '0') {
                   4549:                                             $digit += $numletts;
                   4550:                                         }
                   4551:                                     }
                   4552:                                     my $qval='';
                   4553:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4554:                                         if ($j == $digit) {
                   4555:                                             $qval .= $scantronconf{'Qon'};
                   4556:                                         } else {
                   4557:                                             $qval .= $scantronconf{'Qoff'};
                   4558:                                         }
                   4559:                                     }
                   4560:                                     $values[$i] = $qval;
                   4561:                                 }
                   4562:                             }
                   4563:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4564:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4565:                             }
                   4566:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4567:                             if ($numblank > 0) {
                   4568:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4569:                             }
1.1401    raeburn  4570:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4571:                                 $qstart = $i;
1.1403    raeburn  4572:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4573:                             } else {
1.1403    raeburn  4574:                                 $found{'FirstQuestion'} .= $values[$i];
                   4575:                             }
                   4576:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4577:                             if ($csvoptions{'rem'}) {
                   4578:                                 $values[$i] =~ s/^\s+//;
                   4579:                             }
                   4580:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4581:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4582:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4583:                                 }
                   4584:                             }
                   4585:                             $found{$csvbynum{$i}} = $values[$i];
                   4586:                         }
                   4587:                     }
                   4588:                     foreach my $item (@ordered) {
                   4589:                         my $currlength = 1+length($record);
                   4590:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4591:                         if ($numspaces > 0) {
                   4592:                             $record .= (' ' x $numspaces);
                   4593:                         }
                   4594:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4595:                             unless ($item eq 'Qstart') {
                   4596:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4597:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4598:                                 }
                   4599:                             }
                   4600:                             $record .= $found{$mapstart{$item}};
                   4601:                         }
                   4602:                     }
                   4603:                     $output .= "$record\n";
                   4604:                 }
                   4605:                 close($fh);
                   4606:                 if ($output) {
                   4607:                     if (open(my $fh,'>',$fullpath)) {
                   4608:                         print $fh $output;
                   4609:                         close($fh);
                   4610:                     }
                   4611:                 }
                   4612:             }
                   4613:         }
                   4614:         return;
                   4615:     }
                   4616: }
                   4617: 
1.1403    raeburn  4618: sub letter_to_digits {
                   4619:     my %lettdig = (
                   4620:                     A => 1,
                   4621:                     B => 2,
                   4622:                     C => 3,
                   4623:                     D => 4,
                   4624:                     E => 5,
                   4625:                     F => 6,
                   4626:                     G => 7,
                   4627:                     H => 8,
                   4628:                     I => 9,
                   4629:                     J => 0,
                   4630:                   );
                   4631:     return %lettdig;
                   4632: }
                   4633: 
1.1401    raeburn  4634: sub get_scantron_config {
                   4635:     my ($which,$cdom) = @_;
                   4636:     my @lines = &get_scantronformat_file($cdom);
                   4637:     my %config;
                   4638:     #FIXME probably should move to XML it has already gotten a bit much now
                   4639:     foreach my $line (@lines) {
                   4640:         my ($name,$descrip)=split(/:/,$line);
                   4641:         if ($name ne $which ) { next; }
                   4642:         chomp($line);
                   4643:         my @config=split(/:/,$line);
                   4644:         $config{'name'}=$config[0];
                   4645:         $config{'description'}=$config[1];
                   4646:         $config{'CODElocation'}=$config[2];
                   4647:         $config{'CODEstart'}=$config[3];
                   4648:         $config{'CODElength'}=$config[4];
                   4649:         $config{'IDstart'}=$config[5];
                   4650:         $config{'IDlength'}=$config[6];
                   4651:         $config{'Qstart'}=$config[7];
                   4652:         $config{'Qlength'}=$config[8];
                   4653:         $config{'Qoff'}=$config[9];
                   4654:         $config{'Qon'}=$config[10];
                   4655:         $config{'PaperID'}=$config[11];
                   4656:         $config{'PaperIDlength'}=$config[12];
                   4657:         $config{'FirstName'}=$config[13];
                   4658:         $config{'FirstNamelength'}=$config[14];
                   4659:         $config{'LastName'}=$config[15];
                   4660:         $config{'LastNamelength'}=$config[16];
                   4661:         $config{'BubblesPerRow'}=$config[17];
                   4662:         last;
                   4663:     }
                   4664:     return %config;
                   4665: }
                   4666: 
                   4667: sub get_scantronformat_file {
                   4668:     my ($cdom) = @_;
                   4669:     if ($cdom eq '') {
                   4670:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4671:     }
                   4672:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4673:     my $gottab = 0;
                   4674:     my @lines;
                   4675:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4676:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4677:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4678:             if ($formatfile ne '-1') {
                   4679:                 @lines = split("\n",$formatfile,-1);
                   4680:                 $gottab = 1;
                   4681:             }
                   4682:         }
                   4683:     }
                   4684:     if (!$gottab) {
                   4685:         my $confname = $cdom.'-domainconfig';
                   4686:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4687:         my $formatfile = &getfile($default);
                   4688:         if ($formatfile ne '-1') {
                   4689:             @lines = split("\n",$formatfile,-1);
                   4690:             $gottab = 1;
                   4691:         }
                   4692:     }
                   4693:     if (!$gottab) {
                   4694:         my @domains = &current_machine_domains();
                   4695:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4696:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4697:                 @lines = <$fh>;
                   4698:                 close($fh);
1.1403    raeburn  4699:             }
1.1401    raeburn  4700:         } else {
                   4701:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4702:                 @lines = <$fh>;
                   4703:                 close($fh);
                   4704:             }
                   4705:         }
                   4706:     }
                   4707:     return @lines;
                   4708: }
                   4709: 
1.493     albertel 4710: sub removeuploadedurl {
1.984     neumanie 4711:     my ($url)=@_;	
                   4712:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4713:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4714: }
                   4715: 
                   4716: sub removeuserfile {
                   4717:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4718:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4719:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4720:     if ($result eq 'ok') {	
1.798     raeburn  4721:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4722:             my $metafile = $fname.'.meta';
                   4723:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4724: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4725:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4726:             my $sqlresult = 
1.823     albertel 4727:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4728:                                         'portfolio_metadata',$group,
                   4729:                                         'delete');
1.798     raeburn  4730:         }
                   4731:     }
                   4732:     return $result;
1.257     www      4733: }
1.15      www      4734: 
1.530     albertel 4735: sub mkdiruserfile {
                   4736:     my ($docuname,$docudom,$dir)=@_;
                   4737:     my $home=&homeserver($docuname,$docudom);
                   4738:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4739: }
                   4740: 
1.531     albertel 4741: sub renameuserfile {
                   4742:     my ($docuname,$docudom,$old,$new)=@_;
                   4743:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4744:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4745:                         &escape("$old").':'.&escape("$new"),$home);
                   4746:     if ($result eq 'ok') {
                   4747:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4748:             my $oldmeta = $old.'.meta';
                   4749:             my $newmeta = $new.'.meta';
                   4750:             my $metaresult = 
                   4751:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4752: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4753:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4754:             my $sqlresult = 
1.823     albertel 4755:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4756:                                         'portfolio_metadata',$group,
                   4757:                                         'delete');
1.798     raeburn  4758:         }
                   4759:     }
                   4760:     return $result;
1.531     albertel 4761: }
                   4762: 
1.14      www      4763: # ------------------------------------------------------------------------- Log
                   4764: 
                   4765: sub log {
                   4766:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4767:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4768: }
                   4769: 
                   4770: # ------------------------------------------------------------------ Course Log
1.352     www      4771: #
                   4772: # This routine flushes several buffers of non-mission-critical nature
                   4773: #
1.157     www      4774: 
                   4775: sub flushcourselogs {
1.352     www      4776:     &logthis('Flushing log buffers');
                   4777: #
                   4778: # course logs
                   4779: # This is a log of all transactions in a course, which can be used
                   4780: # for data mining purposes
                   4781: #
                   4782: # It also collects the courseid database, which lists last transaction
                   4783: # times and course titles for all courseids
                   4784: #
                   4785:     my %courseidbuffer=();
1.921     raeburn  4786:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4787:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4788: 		          &escape($courselogs{$crsid}),
                   4789: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4790: 	    delete $courselogs{$crsid};
                   4791:         } else {
                   4792:             &logthis('Failed to flush log buffer for '.$crsid);
                   4793:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4794:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4795:                         " exceeded maximum size, deleting.</font>");
                   4796:                delete $courselogs{$crsid};
                   4797:             }
1.352     www      4798:         }
1.920     raeburn  4799:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4800:             'description' => $coursedescrbuf{$crsid},
                   4801:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4802:             'type'        => $coursetypebuf{$crsid},
                   4803:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4804:         };
1.191     harris41 4805:     }
1.352     www      4806: #
                   4807: # Write course id database (reverse lookup) to homeserver of courses 
                   4808: # Is used in pickcourse
                   4809: #
1.840     albertel 4810:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4811:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4812:                                     $courseidbuffer{$crs_home},
                   4813:                                     $crs_home,'timeonly');
1.352     www      4814:     }
                   4815: #
                   4816: # File accesses
                   4817: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4818: #
1.449     matthew  4819:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4820:         if ($entry =~ /___count$/) {
                   4821:             my ($dom,$name);
1.807     albertel 4822:             ($dom,$name,undef)=
1.811     albertel 4823: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4824:             if (! defined($dom) || $dom eq '' || 
                   4825:                 ! defined($name) || $name eq '') {
1.620     albertel 4826:                 my $cid = $env{'request.course.id'};
                   4827:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4828:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4829:             }
1.450     matthew  4830:             my $value = $accesshash{$entry};
                   4831:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4832:             my %temphash=($url => $value);
1.449     matthew  4833:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4834:             if ($result eq 'ok') {
                   4835:                 delete $accesshash{$entry};
                   4836:             }
                   4837:         } else {
1.811     albertel 4838:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4839:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4840:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4841:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4842:                 delete $accesshash{$entry};
                   4843:             }
1.185     www      4844:         }
1.191     harris41 4845:     }
1.352     www      4846: #
                   4847: # Roles
                   4848: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4849: #
1.800     albertel 4850:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4851:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4852: 	    split(/\:/,$entry);
                   4853:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4854:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4855:                 $rudom,$runame) eq 'ok') {
                   4856: 	    delete $userrolehash{$entry};
                   4857:         }
                   4858:     }
1.662     raeburn  4859: #
1.1334    raeburn  4860: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4861: #
                   4862:     my %domrolebuffer = ();
1.1000    raeburn  4863:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4864:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4865:         if ($domrolebuffer{$rudom}) {
                   4866:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4867:                       '='.&escape($domainrolehash{$entry});
                   4868:         } else {
                   4869:             $domrolebuffer{$rudom}.=&escape($entry).
                   4870:                       '='.&escape($domainrolehash{$entry});
                   4871:         }
                   4872:         delete $domainrolehash{$entry};
                   4873:     }
                   4874:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4875: 	my %servers;
                   4876: 	if (defined(&domain($dom,'primary'))) {
                   4877: 	    my $primary=&domain($dom,'primary');
                   4878: 	    my $hostname=&hostname($primary);
                   4879: 	    $servers{$primary} = $hostname;
                   4880: 	} else { 
                   4881: 	    %servers = &get_servers($dom,'library');
                   4882: 	}
1.841     albertel 4883: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4884: 	    if (&reply('domroleput:'.$dom.':'.
                   4885: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4886: 		last;
                   4887: 	    } else {  
1.841     albertel 4888: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4889: 	    }
1.662     raeburn  4890:         }
                   4891:     }
1.186     www      4892:     $dumpcount++;
1.157     www      4893: }
                   4894: 
                   4895: sub courselog {
                   4896:     my $what=shift;
1.158     www      4897:     $what=time.':'.$what;
1.620     albertel 4898:     unless ($env{'request.course.id'}) { return ''; }
                   4899:     $coursedombuf{$env{'request.course.id'}}=
                   4900:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4901:     $coursenumbuf{$env{'request.course.id'}}=
                   4902:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4903:     $coursehombuf{$env{'request.course.id'}}=
                   4904:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4905:     $coursedescrbuf{$env{'request.course.id'}}=
                   4906:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4907:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4908:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4909:     $courseownerbuf{$env{'request.course.id'}}=
                   4910:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4911:     $coursetypebuf{$env{'request.course.id'}}=
                   4912:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4913:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4914: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4915:     } else {
1.620     albertel 4916: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4917:     }
1.620     albertel 4918:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4919: 	&flushcourselogs();
                   4920:     }
1.158     www      4921: }
                   4922: 
                   4923: sub courseacclog {
                   4924:     my $fnsymb=shift;
1.620     albertel 4925:     unless ($env{'request.course.id'}) { return ''; }
                   4926:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4927:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4928:         $what.=':POST';
1.583     matthew  4929:         # FIXME: Probably ought to escape things....
1.800     albertel 4930: 	foreach my $key (keys(%env)) {
                   4931:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4932:                 my $formitem = $1;
                   4933:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4934:                     $what.=':'.$formitem.'='.$env{$key};
                   4935:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4936:                     $what.=':'.$formitem.'='.$env{$key};
                   4937:                 }
1.158     www      4938:             }
1.191     harris41 4939:         }
1.583     matthew  4940:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4941:         # FIXME: We should not be depending on a form parameter that someone
                   4942:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4943:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4944:             $what.= ':POST';
                   4945:             # FIXME: Probably ought to escape things....
                   4946:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4947:                                  'crsdiscuss') {
1.620     albertel 4948:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4949:             }
                   4950:         }
1.158     www      4951:     }
                   4952:     &courselog($what);
1.149     www      4953: }
                   4954: 
1.185     www      4955: sub countacc {
                   4956:     my $url=&declutter(shift);
1.458     matthew  4957:     return if (! defined($url) || $url eq '');
1.620     albertel 4958:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4959: #
                   4960: # Mark that this url was used in this course
                   4961: #
1.620     albertel 4962:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4963: #
                   4964: # Increase the access count for this resource in this child process
                   4965: #
1.281     www      4966:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4967:     $accesshash{$key}++;
1.185     www      4968: }
1.349     www      4969: 
1.361     www      4970: sub linklog {
                   4971:     my ($from,$to)=@_;
                   4972:     $from=&declutter($from);
                   4973:     $to=&declutter($to);
                   4974:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4975:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4976: }
1.1160    www      4977: 
                   4978: sub statslog {
                   4979:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4980:     if ($users<2) { return; }
                   4981:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4982:             'course'       => $env{'request.course.id'},
                   4983:             'sections'     => '"all"',
                   4984:             'num_students' => $users,
                   4985:             'part'         => $part,
                   4986:             'symb'         => $symb,
                   4987:             'mean_tries'   => $av_attempts,
                   4988:             'deg_of_diff'  => $degdiff});
                   4989:     foreach my $key (keys(%dynstore)) {
                   4990:         $accesshash{$key}=$dynstore{$key};
                   4991:     }
                   4992: }
1.361     www      4993:   
1.349     www      4994: sub userrolelog {
                   4995:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4996:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4997:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4998:        $userrolehash
                   4999:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5000:                     =$tend.':'.$tstart;
1.662     raeburn  5001:     }
1.1169    droeschl 5002:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5003:        $userrolehash
                   5004:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5005:                     =$tend.':'.$tstart;
                   5006:     }
1.1334    raeburn  5007:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5008:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5009:        $domainrolehash
                   5010:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5011:                     = $tend.':'.$tstart;
                   5012:     }
1.351     www      5013: }
                   5014: 
1.957     raeburn  5015: sub courserolelog {
                   5016:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5017:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5018:         my $cdom = $1;
                   5019:         my $cnum = $2;
                   5020:         my $sec = $3;
                   5021:         my $namespace = 'rolelog';
                   5022:         my %storehash = (
                   5023:                            role    => $trole,
                   5024:                            start   => $tstart,
                   5025:                            end     => $tend,
                   5026:                            selfenroll => $selfenroll,
                   5027:                            context    => $context,
                   5028:                         );
                   5029:         if ($trole eq 'gr') {
                   5030:             $namespace = 'groupslog';
                   5031:             $storehash{'group'} = $sec;
                   5032:         } else {
                   5033:             $storehash{'section'} = $sec;
                   5034:         }
1.1188    raeburn  5035:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5036:                    $domain,$cnum,$cdom);
1.1184    raeburn  5037:         if (($trole ne 'st') || ($sec ne '')) {
                   5038:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5039:         }
                   5040:     }
                   5041:     return;
                   5042: }
                   5043: 
1.1184    raeburn  5044: sub domainrolelog {
                   5045:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5046:     if ($area =~ m{^/($match_domain)/$}) {
                   5047:         my $cdom = $1;
                   5048:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5049:         my $namespace = 'rolelog';
                   5050:         my %storehash = (
                   5051:                            role    => $trole,
                   5052:                            start   => $tstart,
                   5053:                            end     => $tend,
                   5054:                            context => $context,
                   5055:                         );
1.1188    raeburn  5056:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5057:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5058:     }
                   5059:     return;
                   5060: 
                   5061: }
                   5062: 
                   5063: sub coauthorrolelog {
                   5064:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5065:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5066:         my $audom = $1;
                   5067:         my $auname = $2;
                   5068:         my $namespace = 'rolelog';
                   5069:         my %storehash = (
                   5070:                            role    => $trole,
                   5071:                            start   => $tstart,
                   5072:                            end     => $tend,
                   5073:                            context => $context,
                   5074:                         );
1.1188    raeburn  5075:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5076:                    $domain,$auname,$audom);
1.1184    raeburn  5077:     }
                   5078:     return;
                   5079: }
                   5080: 
1.351     www      5081: sub get_course_adv_roles {
1.948     raeburn  5082:     my ($cid,$codes) = @_;
1.620     albertel 5083:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5084:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5085:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5086:     my %nothide=();
1.800     albertel 5087:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5088:         if ($user !~ /:/) {
                   5089: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5090:         } else {
                   5091:             $nothide{$user}=1;
                   5092:         }
1.470     www      5093:     }
1.1219    raeburn  5094:     my @possdoms = ($coursehash{'domain'});
                   5095:     if ($coursehash{'checkforpriv'}) {
                   5096:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5097:     }
1.351     www      5098:     my %returnhash=();
                   5099:     my %dumphash=
                   5100:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5101:     my $now=time;
1.997     raeburn  5102:     my %privileged;
1.1000    raeburn  5103:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5104: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5105:         if (($tstart) && ($tstart<0)) { next; }
                   5106:         if (($tend) && ($tend<$now)) { next; }
                   5107:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5108:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5109: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5110:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5111:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5112: 	if ($role eq 'cr') { next; }
1.948     raeburn  5113:         if ($codes) {
                   5114:             if ($section) { $role .= ':'.$section; }
                   5115:             if ($returnhash{$role}) {
                   5116:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5117:             } else {
                   5118:                 $returnhash{$role}=$username.':'.$domain;
                   5119:             }
1.351     www      5120:         } else {
1.988     raeburn  5121:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5122:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5123:             if ($returnhash{$key}) {
                   5124: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5125:             } else {
                   5126:                 $returnhash{$key}=$username.':'.$domain;
                   5127:             }
1.351     www      5128:         }
1.948     raeburn  5129:     }
1.400     www      5130:     return %returnhash;
                   5131: }
                   5132: 
                   5133: sub get_my_roles {
1.937     raeburn  5134:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5135:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5136:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5137:     my (%dumphash,%nothide);
1.1086    raeburn  5138:     if ($context eq 'userroles') {
1.1166    raeburn  5139:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5140:     } else {
1.1219    raeburn  5141:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5142:         if ($hidepriv) {
                   5143:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5144:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5145:                 if ($user !~ /:/) {
                   5146:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5147:                 } else {
                   5148:                     $nothide{$user} = 1;
                   5149:                 }
                   5150:             }
                   5151:         }
1.858     raeburn  5152:     }
1.400     www      5153:     my %returnhash=();
                   5154:     my $now=time;
1.999     raeburn  5155:     my %privileged;
1.800     albertel 5156:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5157:         my ($role,$tend,$tstart);
                   5158:         if ($context eq 'userroles') {
1.1149    raeburn  5159:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5160: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5161:         } else {
                   5162:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5163:         }
1.400     www      5164:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5165:         my $status = 'active';
1.939     raeburn  5166:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5167:             $status = 'previous';
                   5168:         } 
                   5169:         if (($tstart) && ($now<$tstart)) {
                   5170:             $status = 'future';
                   5171:         }
                   5172:         if (ref($types) eq 'ARRAY') {
                   5173:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5174:                 next;
                   5175:             } 
                   5176:         } else {
                   5177:             if ($status ne 'active') {
                   5178:                 next;
                   5179:             }
                   5180:         }
1.867     raeburn  5181:         my ($rolecode,$username,$domain,$section,$area);
                   5182:         if ($context eq 'userroles') {
1.1186    raeburn  5183:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5184:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5185:         } else {
                   5186:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5187:         }
1.832     raeburn  5188:         if (ref($roledoms) eq 'ARRAY') {
                   5189:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5190:                 next;
                   5191:             }
                   5192:         }
                   5193:         if (ref($roles) eq 'ARRAY') {
                   5194:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5195:                 if ($role =~ /^cr\//) {
                   5196:                     if (!grep(/^cr$/,@{$roles})) {
                   5197:                         next;
                   5198:                     }
1.1104    raeburn  5199:                 } elsif ($role =~ /^gr\//) {
                   5200:                     if (!grep(/^gr$/,@{$roles})) {
                   5201:                         next;
                   5202:                     }
1.922     raeburn  5203:                 } else {
                   5204:                     next;
                   5205:                 }
1.832     raeburn  5206:             }
1.867     raeburn  5207:         }
1.937     raeburn  5208:         if ($hidepriv) {
1.1219    raeburn  5209:             my @privroles = ('dc','su');
1.999     raeburn  5210:             if ($context eq 'userroles') {
1.1219    raeburn  5211:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5212:             } else {
1.1219    raeburn  5213:                 my $possdoms = [$domain];
                   5214:                 if (ref($roledoms) eq 'ARRAY') {
                   5215:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5216:                 }
1.1219    raeburn  5217:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5218:                     if (!$nothide{$username.':'.$domain}) {
                   5219:                         next;
                   5220:                     }
                   5221:                 }
1.937     raeburn  5222:             }
                   5223:         }
1.933     raeburn  5224:         if ($withsec) {
                   5225:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5226:                 $tstart.':'.$tend;
                   5227:         } else {
                   5228:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5229:         }
1.832     raeburn  5230:     }
1.373     www      5231:     return %returnhash;
1.399     www      5232: }
                   5233: 
1.1333    raeburn  5234: sub get_all_adhocroles {
                   5235:     my ($dom) = @_;
                   5236:     my @roles_by_num = ();
                   5237:     my %domdefaults = &get_domain_defaults($dom);
                   5238:     my (%description,%access_in_dom,%access_info);
                   5239:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5240:         my $count = 0;
                   5241:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5242:         my %ordered;
                   5243:         foreach my $role (sort(keys(%domcurrent))) {
                   5244:             my ($order,$desc,$access_in_dom);
                   5245:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5246:                 $order = $domcurrent{$role}{'order'};
                   5247:                 $desc = $domcurrent{$role}{'desc'};
                   5248:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5249:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5250:             }
                   5251:             if ($order eq '') {
                   5252:                 $order = $count;
                   5253:             }
                   5254:             $ordered{$order} = $role;
                   5255:             if ($desc ne '') {
                   5256:                 $description{$role} = $desc;
                   5257:             } else {
                   5258:                 $description{$role}= $role;
                   5259:             }
                   5260:             $count++;
                   5261:         }
                   5262:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5263:             push(@roles_by_num,$ordered{$item});
                   5264:         }
                   5265:     }
                   5266:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5267: }
                   5268: 
1.1332    raeburn  5269: sub get_my_adhocroles {
1.1333    raeburn  5270:     my ($cid,$checkreg) = @_;
                   5271:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5272:     if ($env{'request.course.id'} eq $cid) {
                   5273:         $cdom = $env{'course.'.$cid.'.domain'};
                   5274:         $cnum = $env{'course.'.$cid.'.num'};
                   5275:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5276:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5277:         $cdom = $1;
                   5278:         $cnum = $2;
                   5279:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5280:                                      $cdom,$cnum);
                   5281:     }
                   5282:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5283:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5284:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5285:         if ($rosterhash{$user} ne '') {
                   5286:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5287:             return ([],{}) if ($type eq 'auto');
                   5288:         }
                   5289:     }
                   5290:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5291:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5292:             my $then=$env{'user.login.time'};
                   5293:             my $update=$env{'user.update.time'};
1.1335    raeburn  5294:             if (!$update) {
                   5295:                 $update = $then;
                   5296:             }
                   5297:             my @liveroles;
1.1334    raeburn  5298:             foreach my $role ('dh','da') {
                   5299:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5300:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5301:                     my $limit = $update;
                   5302:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5303:                         $limit = $then;
                   5304:                     }
1.1335    raeburn  5305:                     my $activerole = 1;
                   5306:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5307:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5308:                     if ($activerole) {
                   5309:                         push(@liveroles,$role);
                   5310:                     }
1.1334    raeburn  5311:                 }
1.1332    raeburn  5312:             }
1.1335    raeburn  5313:             if (@liveroles) {
1.1332    raeburn  5314:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5315:                     my ($accessref,$accessinfo,%access_in_dom);
                   5316:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5317:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5318:                         if (@{$roles_by_num}) {
1.1332    raeburn  5319:                             my %settings;
                   5320:                             if ($env{'request.course.id'} eq $cid) {
                   5321:                                 foreach my $envkey (keys(%env)) {
                   5322:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5323:                                         $settings{$1} = $env{$envkey};
                   5324:                                     }
                   5325:                                 }
                   5326:                             } else {
                   5327:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5328:                             }
                   5329:                             my %setincrs;
                   5330:                             if ($settings{'internal.adhocaccess'}) {
                   5331:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5332:                             }
                   5333:                             my @statuses;
                   5334:                             if ($env{'environment.inststatus'}) {
                   5335:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5336:                             }
                   5337:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5338:                             if (ref($accessref) eq 'HASH') {
                   5339:                                 %access_in_dom = %{$accessref};
                   5340:                             }
                   5341:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5342:                                 my ($curraccess,@okstatus,@personnel);
                   5343:                                 if ($setincrs{$role}) {
                   5344:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5345:                                     if ($curraccess eq 'status') {
                   5346:                                         @okstatus = split(/\&/,$rest);
                   5347:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5348:                                         @personnel = split(/\&/,$rest);
                   5349:                                     }
                   5350:                                 } else {
                   5351:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5352:                                     if (ref($accessinfo) eq 'HASH') {
                   5353:                                         if ($curraccess eq 'status') {
                   5354:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5355:                                                 @okstatus = @{$accessinfo->{$role}};
                   5356:                                             }
                   5357:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5358:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5359:                                                 @personnel = @{$accessinfo->{$role}};
                   5360:                                             }
1.1332    raeburn  5361:                                         }
                   5362:                                     }
                   5363:                                 }
                   5364:                                 if ($curraccess eq 'none') {
                   5365:                                     next;
                   5366:                                 } elsif ($curraccess eq 'all') {
                   5367:                                     push(@possroles,$role);
1.1336    raeburn  5368:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5369:                                     if (grep(/^dh$/,@liveroles)) {
                   5370:                                         push(@possroles,$role);
                   5371:                                     } else {
                   5372:                                         next;
                   5373:                                     }
1.1336    raeburn  5374:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5375:                                     if (grep(/^da$/,@liveroles)) {
                   5376:                                         push(@possroles,$role);
                   5377:                                     } else {
                   5378:                                         next;
                   5379:                                     }
1.1332    raeburn  5380:                                 } elsif ($curraccess eq 'status') {
                   5381:                                     if (@okstatus) {
                   5382:                                         if (!@statuses) {
                   5383:                                             if (grep(/^default$/,@okstatus)) {
                   5384:                                                 push(@possroles,$role);
                   5385:                                             }
                   5386:                                         } else {
                   5387:                                             foreach my $status (@okstatus) {
                   5388:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5389:                                                     push(@possroles,$role);
                   5390:                                                     last;
                   5391:                                                 }
                   5392:                                             }
                   5393:                                         }
                   5394:                                     }
                   5395:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5396:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5397:                                         if ($curraccess eq 'exc') {
                   5398:                                             push(@possroles,$role);
                   5399:                                         }
                   5400:                                     } elsif ($curraccess eq 'inc') {
                   5401:                                         push(@possroles,$role);
                   5402:                                     }
                   5403:                                 }
                   5404:                             }
                   5405:                         }
                   5406:                     }
                   5407:                 }
                   5408:             }
                   5409:         }
                   5410:     }
1.1333    raeburn  5411:     unless (ref($description) eq 'HASH') {
                   5412:         if (ref($roles_by_num) eq 'ARRAY') {
                   5413:             my %desc;
                   5414:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5415:             $description = \%desc;
                   5416:         } else {
                   5417:             $description = {};
                   5418:         }
                   5419:     }
                   5420:     return (\@possroles,$description);
1.1332    raeburn  5421: }
                   5422: 
1.399     www      5423: # ----------------------------------------------------- Frontpage Announcements
                   5424: #
                   5425: #
                   5426: 
                   5427: sub postannounce {
                   5428:     my ($server,$text)=@_;
1.844     albertel 5429:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5430:     unless ($text=~/\w/) { $text=''; }
                   5431:     return &reply('setannounce:'.&escape($text),$server);
                   5432: }
                   5433: 
                   5434: sub getannounce {
1.448     albertel 5435: 
1.1359    raeburn  5436:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5437: 	my $announcement='';
1.800     albertel 5438: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5439: 	close($fh);
1.399     www      5440: 	if ($announcement=~/\w/) { 
                   5441: 	    return 
                   5442:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5443:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5444: 	} else {
                   5445: 	    return '';
                   5446: 	}
                   5447:     } else {
                   5448: 	return '';
                   5449:     }
1.351     www      5450: }
1.353     www      5451: 
                   5452: # ---------------------------------------------------------- Course ID routines
                   5453: # Deal with domain's nohist_courseid.db files
                   5454: #
                   5455: 
                   5456: sub courseidput {
1.921     raeburn  5457:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5458:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5459:     my $outcome;
                   5460:     if ($caller eq 'timeonly') {
                   5461:         my $cids = '';
                   5462:         foreach my $item (keys(%$storehash)) {
                   5463:             $cids.=&escape($item).'&';
                   5464:         }
                   5465:         $cids=~s/\&$//;
                   5466:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5467:                           $coursehome);       
                   5468:     } else {
                   5469:         my $items = '';
                   5470:         foreach my $item (keys(%$storehash)) {
                   5471:             $items.= &escape($item).'='.
                   5472:                      &freeze_escape($$storehash{$item}).'&';
                   5473:         }
                   5474:         $items=~s/\&$//;
                   5475:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5476:                           $coursehome);
1.918     raeburn  5477:     }
                   5478:     if ($outcome eq 'unknown_cmd') {
                   5479:         my $what;
                   5480:         foreach my $cid (keys(%$storehash)) {
                   5481:             $what .= &escape($cid).'=';
1.921     raeburn  5482:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5483:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5484:             }
                   5485:             $what =~ s/\:$/&/;
                   5486:         }
                   5487:         $what =~ s/\&$//;  
                   5488:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5489:     } else {
                   5490:         return $outcome;
                   5491:     }
1.353     www      5492: }
                   5493: 
                   5494: sub courseiddump {
1.921     raeburn  5495:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5496:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5497:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5498:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5499:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5500:     my $as_hash = 1;
                   5501:     my %returnhash;
                   5502:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5503:     my %libserv = &all_library();
                   5504:     foreach my $tryserver (keys(%libserv)) {
                   5505:         if ( (  $hostidflag == 1 
                   5506: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5507: 	     || (!defined($hostidflag)) ) {
                   5508: 
1.918     raeburn  5509: 	    if (($domfilter eq '') ||
                   5510: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5511:                 my $rep;
                   5512:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5513:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5514:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5515:                                 &escape($descfilter), &escape($instcodefilter), 
                   5516:                                 &escape($ownerfilter), &escape($coursefilter),
                   5517:                                 &escape($typefilter), &escape($regexp_ok), 
                   5518:                                 $as_hash, &escape($selfenrollonly), 
                   5519:                                 &escape($catfilter), $showhidden, $caller, 
                   5520:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5521:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5522:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5523:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5524:                 } else {
                   5525:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5526:                              $sincefilter.':'.&escape($descfilter).':'.
                   5527:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5528:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5529:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5530:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5531:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5532:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5533:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5534:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5535:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5536:                 }
                   5537:                      
1.918     raeburn  5538:                 my @pairs=split(/\&/,$rep);
                   5539:                 foreach my $item (@pairs) {
                   5540:                     my ($key,$value)=split(/\=/,$item,2);
                   5541:                     $key = &unescape($key);
                   5542:                     next if ($key =~ /^error: 2 /);
                   5543:                     my $result = &thaw_unescape($value);
                   5544:                     if (ref($result) eq 'HASH') {
                   5545:                         $returnhash{$key}=$result;
                   5546:                     } else {
1.921     raeburn  5547:                         my @responses = split(/:/,$value);
                   5548:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5549:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5550:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5551:                         }
1.1008    raeburn  5552:                     }
1.353     www      5553:                 }
                   5554:             }
                   5555:         }
                   5556:     }
                   5557:     return %returnhash;
                   5558: }
                   5559: 
1.1055    raeburn  5560: sub courselastaccess {
                   5561:     my ($cdom,$cnum,$hostidref) = @_;
                   5562:     my %returnhash;
                   5563:     if ($cdom && $cnum) {
                   5564:         my $chome = &homeserver($cnum,$cdom);
                   5565:         if ($chome ne 'no_host') {
                   5566:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5567:             &extract_lastaccess(\%returnhash,$rep);
                   5568:         }
                   5569:     } else {
                   5570:         if (!$cdom) { $cdom=''; }
                   5571:         my %libserv = &all_library();
                   5572:         foreach my $tryserver (keys(%libserv)) {
                   5573:             if (ref($hostidref) eq 'ARRAY') {
                   5574:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5575:             } 
                   5576:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5577:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5578:                 &extract_lastaccess(\%returnhash,$rep);
                   5579:             }
                   5580:         }
                   5581:     }
                   5582:     return %returnhash;
                   5583: }
                   5584: 
                   5585: sub extract_lastaccess {
                   5586:     my ($returnhash,$rep) = @_;
                   5587:     if (ref($returnhash) eq 'HASH') {
                   5588:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5589:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5590:                  $rep eq '') {
                   5591:             my @pairs=split(/\&/,$rep);
                   5592:             foreach my $item (@pairs) {
                   5593:                 my ($key,$value)=split(/\=/,$item,2);
                   5594:                 $key = &unescape($key);
                   5595:                 next if ($key =~ /^error: 2 /);
                   5596:                 $returnhash->{$key} = &thaw_unescape($value);
                   5597:             }
                   5598:         }
                   5599:     }
                   5600:     return;
                   5601: }
                   5602: 
1.658     raeburn  5603: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5604: 
                   5605: sub dcmailput {
1.685     raeburn  5606:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5607:     my $status = &Apache::lonnet::critical(
1.740     www      5608:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5609:        &escape($message),$server);
1.662     raeburn  5610:     return $status;
                   5611: }
                   5612: 
1.658     raeburn  5613: sub dcmaildump {
                   5614:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5615:     my %returnhash=();
1.846     albertel 5616: 
                   5617:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5618:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5619:                                                          &escape($enddate).':';
                   5620: 	my @esc_senders=map { &escape($_)} @$senders;
                   5621: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5622: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5623:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5624:             if (($key) && ($value)) {
                   5625:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5626:             }
                   5627:         }
                   5628:     }
                   5629:     return %returnhash;
                   5630: }
1.662     raeburn  5631: # ---------------------------------------------------------- Domain roles
                   5632: 
                   5633: sub get_domain_roles {
                   5634:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5635:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5636:         $startdate = '.';
                   5637:     }
1.1018    raeburn  5638:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5639:         $enddate = '.';
                   5640:     }
1.922     raeburn  5641:     my $rolelist;
                   5642:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5643:         $rolelist = join('&',@{$roles});
1.922     raeburn  5644:     }
1.662     raeburn  5645:     my %personnel = ();
1.841     albertel 5646: 
                   5647:     my %servers = &get_servers($dom,'library');
                   5648:     foreach my $tryserver (keys(%servers)) {
                   5649: 	%{$personnel{$tryserver}}=();
                   5650: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5651: 					    &escape($startdate).':'.
                   5652: 					    &escape($enddate).':'.
                   5653: 					    &escape($rolelist), $tryserver))) {
                   5654: 	    my ($key,$value) = split(/\=/,$line,2);
                   5655: 	    if (($key) && ($value)) {
                   5656: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5657: 	    }
                   5658: 	}
1.662     raeburn  5659:     }
                   5660:     return %personnel;
                   5661: }
1.658     raeburn  5662: 
1.1332    raeburn  5663: sub get_active_domroles {
                   5664:     my ($dom,$roles) = @_;
                   5665:     return () unless (ref($roles) eq 'ARRAY');
                   5666:     my $now = time;
                   5667:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5668:     my %domroles;
                   5669:     foreach my $server (keys(%dompersonnel)) {
                   5670:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5671:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5672:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5673:         }
                   5674:     }
                   5675:     return %domroles;
                   5676: }
                   5677: 
1.1057    www      5678: # ----------------------------------------------------------- Interval timing 
1.149     www      5679: 
1.1153    www      5680: {
                   5681: # Caches needed for speedup of navmaps
                   5682: # We don't want to cache this for very long at all (5 seconds at most)
                   5683: # 
                   5684: # The user for whom we cache
                   5685: my $cachedkey='';
                   5686: # The cached times for this user
                   5687: my %cachedtimes=();
                   5688: # When this was last done
1.1282    raeburn  5689: my $cachedtime='';
1.1153    www      5690: 
                   5691: sub load_all_first_access {
1.1308    raeburn  5692:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5693:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5694:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5695:         (!$ignorecache)) {
1.1154    raeburn  5696:         return;
                   5697:     }
                   5698:     $cachedtime=time;
                   5699:     $cachedkey=$uname.':'.$udom;
                   5700:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5701: }
                   5702: 
1.504     albertel 5703: sub get_first_access {
1.1308    raeburn  5704:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5705:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5706:     if ($argsymb) { $symb=$argsymb; }
                   5707:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5708:     if ($argmap) { $map = $argmap; }
1.926     albertel 5709:     if ($type eq 'course') {
                   5710: 	$res='course';
                   5711:     } elsif ($type eq 'map') {
1.588     albertel 5712: 	$res=&symbread($map);
                   5713:     } else {
                   5714: 	$res=$symb;
                   5715:     }
1.1308    raeburn  5716:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5717:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5718: }
                   5719: 
                   5720: sub set_first_access {
1.1162    raeburn  5721:     my ($type,$interval)=@_;
1.790     albertel 5722:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5723:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5724:     if ($type eq 'course') {
                   5725: 	$res='course';
                   5726:     } elsif ($type eq 'map') {
1.588     albertel 5727: 	$res=&symbread($map);
                   5728:     } else {
                   5729: 	$res=$symb;
                   5730:     }
1.1153    www      5731:     $cachedkey='';
1.1162    raeburn  5732:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5733:     if ($firstaccess) {
                   5734:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5735:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5736:                  "in $courseid");
1.1386    raeburn  5737:         return 'already_set';
                   5738:     } else {
1.1162    raeburn  5739:         my $start = time;
                   5740: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5741:                           $udom,$uname);
                   5742:         if ($putres eq 'ok') {
                   5743:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5744:                  $udom,$uname); 
                   5745:             &appenv(
                   5746:                      {
                   5747:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5748:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5749:                      }
                   5750:                   );
1.1365    raeburn  5751:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5752:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5753:             }
1.1386    raeburn  5754:         } elsif ($putres ne 'refused') {
                   5755:             &logthis("Result: $putres when attempting to set first access time ".
                   5756:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5757:         }
                   5758:         return $putres;
1.505     albertel 5759:     }
                   5760:     return 'already_set';
1.504     albertel 5761: }
1.1153    www      5762: }
1.1282    raeburn  5763: 
1.110     www      5764: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5765: 
                   5766: sub expirespread {
                   5767:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5768:     my $cid=$env{'request.course.id'}; 
1.110     www      5769:     if ($cid) {
                   5770:        my $now=time;
                   5771:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5772:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5773:                             $env{'course.'.$cid.'.num'}.
1.110     www      5774: 	        	    ':nohist_expirationdates:'.
                   5775:                             &escape($key).'='.$now,
1.620     albertel 5776:                             $env{'course.'.$cid.'.home'})
1.110     www      5777:     }
                   5778:     return 'ok';
1.14      www      5779: }
                   5780: 
1.109     www      5781: # ----------------------------------------------------- Devalidate Spreadsheets
                   5782: 
                   5783: sub devalidate {
1.325     www      5784:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5785:     my $cid=$env{'request.course.id'}; 
1.109     www      5786:     if ($cid) {
1.391     matthew  5787:         # delete the stored spreadsheets for
                   5788:         # - the student level sheet of this user in course's homespace
                   5789:         # - the assessment level sheet for this resource 
                   5790:         #   for this user in user's homespace
1.553     albertel 5791: 	# - current conditional state info
1.325     www      5792: 	my $key=$uname.':'.$udom.':';
1.109     www      5793:         my $status=
1.299     matthew  5794: 	    &del('nohist_calculatedsheets',
1.391     matthew  5795: 		 [$key.'studentcalc:'],
1.620     albertel 5796: 		 $env{'course.'.$cid.'.domain'},
                   5797: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5798: 		.' '.
                   5799: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5800: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5801:         unless ($status eq 'ok ok') {
                   5802:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5803:                     $uname.' at '.$udom.' for '.
1.109     www      5804: 		    $symb.': '.$status);
1.133     albertel 5805:         }
1.553     albertel 5806: 	&delenv('user.state.'.$cid);
1.109     www      5807:     }
                   5808: }
                   5809: 
1.265     albertel 5810: sub get_scalar {
                   5811:     my ($string,$end) = @_;
                   5812:     my $value;
                   5813:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5814: 	$value = $1;
                   5815:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5816: 	$value = $1;
                   5817:     }
                   5818:     return &unescape($value);
                   5819: }
                   5820: 
                   5821: sub array2str {
                   5822:   my (@array) = @_;
                   5823:   my $result=&arrayref2str(\@array);
                   5824:   $result=~s/^__ARRAY_REF__//;
                   5825:   $result=~s/__END_ARRAY_REF__$//;
                   5826:   return $result;
                   5827: }
                   5828: 
1.204     albertel 5829: sub arrayref2str {
                   5830:   my ($arrayref) = @_;
1.265     albertel 5831:   my $result='__ARRAY_REF__';
1.204     albertel 5832:   foreach my $elem (@$arrayref) {
1.265     albertel 5833:     if(ref($elem) eq 'ARRAY') {
                   5834:       $result.=&arrayref2str($elem).'&';
                   5835:     } elsif(ref($elem) eq 'HASH') {
                   5836:       $result.=&hashref2str($elem).'&';
                   5837:     } elsif(ref($elem)) {
                   5838:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5839:     } else {
                   5840:       $result.=&escape($elem).'&';
                   5841:     }
                   5842:   }
                   5843:   $result=~s/\&$//;
1.265     albertel 5844:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5845:   return $result;
                   5846: }
                   5847: 
1.168     albertel 5848: sub hash2str {
1.204     albertel 5849:   my (%hash) = @_;
                   5850:   my $result=&hashref2str(\%hash);
1.265     albertel 5851:   $result=~s/^__HASH_REF__//;
                   5852:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5853:   return $result;
                   5854: }
                   5855: 
                   5856: sub hashref2str {
                   5857:   my ($hashref)=@_;
1.265     albertel 5858:   my $result='__HASH_REF__';
1.800     albertel 5859:   foreach my $key (sort(keys(%$hashref))) {
                   5860:     if (ref($key) eq 'ARRAY') {
                   5861:       $result.=&arrayref2str($key).'=';
                   5862:     } elsif (ref($key) eq 'HASH') {
                   5863:       $result.=&hashref2str($key).'=';
                   5864:     } elsif (ref($key)) {
1.265     albertel 5865:       $result.='=';
1.800     albertel 5866:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5867:     } else {
1.1132    raeburn  5868: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5869:     }
                   5870: 
1.800     albertel 5871:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5872:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5873:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5874:       $result.=&hashref2str($hashref->{$key}).'&';
                   5875:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5876:        $result.='&';
1.800     albertel 5877:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5878:     } else {
1.800     albertel 5879:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5880:     }
                   5881:   }
1.168     albertel 5882:   $result=~s/\&$//;
1.265     albertel 5883:   $result .= '__END_HASH_REF__';
1.168     albertel 5884:   return $result;
                   5885: }
                   5886: 
                   5887: sub str2hash {
1.265     albertel 5888:     my ($string)=@_;
                   5889:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5890:     return %$hash;
                   5891: }
                   5892: 
                   5893: sub str2hashref {
1.168     albertel 5894:   my ($string) = @_;
1.265     albertel 5895: 
                   5896:   my %hash;
                   5897: 
                   5898:   if($string !~ /^__HASH_REF__/) {
                   5899:       if (! ($string eq '' || !defined($string))) {
                   5900: 	  $hash{'error'}='Not hash reference';
                   5901:       }
                   5902:       return (\%hash, $string);
                   5903:   }
                   5904: 
                   5905:   $string =~ s/^__HASH_REF__//;
                   5906: 
                   5907:   while($string !~ /^__END_HASH_REF__/) {
                   5908:       #key
                   5909:       my $key='';
                   5910:       if($string =~ /^__HASH_REF__/) {
                   5911:           ($key, $string)=&str2hashref($string);
                   5912:           if(defined($key->{'error'})) {
                   5913:               $hash{'error'}='Bad data';
                   5914:               return (\%hash, $string);
                   5915:           }
                   5916:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5917:           ($key, $string)=&str2arrayref($string);
                   5918:           if($key->[0] eq 'Array reference error') {
                   5919:               $hash{'error'}='Bad data';
                   5920:               return (\%hash, $string);
                   5921:           }
                   5922:       } else {
                   5923:           $string =~ s/^(.*?)=//;
1.267     albertel 5924: 	  $key=&unescape($1);
1.265     albertel 5925:       }
                   5926:       $string =~ s/^=//;
                   5927: 
                   5928:       #value
                   5929:       my $value='';
                   5930:       if($string =~ /^__HASH_REF__/) {
                   5931:           ($value, $string)=&str2hashref($string);
                   5932:           if(defined($value->{'error'})) {
                   5933:               $hash{'error'}='Bad data';
                   5934:               return (\%hash, $string);
                   5935:           }
                   5936:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5937:           ($value, $string)=&str2arrayref($string);
                   5938:           if($value->[0] eq 'Array reference error') {
                   5939:               $hash{'error'}='Bad data';
                   5940:               return (\%hash, $string);
                   5941:           }
                   5942:       } else {
                   5943: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5944:       }
                   5945:       $string =~ s/^&//;
                   5946: 
                   5947:       $hash{$key}=$value;
1.204     albertel 5948:   }
1.265     albertel 5949: 
                   5950:   $string =~ s/^__END_HASH_REF__//;
                   5951: 
                   5952:   return (\%hash, $string);
1.204     albertel 5953: }
                   5954: 
                   5955: sub str2array {
1.265     albertel 5956:     my ($string)=@_;
                   5957:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5958:     return @$array;
                   5959: }
                   5960: 
                   5961: sub str2arrayref {
1.204     albertel 5962:   my ($string) = @_;
1.265     albertel 5963:   my @array;
                   5964: 
                   5965:   if($string !~ /^__ARRAY_REF__/) {
                   5966:       if (! ($string eq '' || !defined($string))) {
                   5967: 	  $array[0]='Array reference error';
                   5968:       }
                   5969:       return (\@array, $string);
                   5970:   }
                   5971: 
                   5972:   $string =~ s/^__ARRAY_REF__//;
                   5973: 
                   5974:   while($string !~ /^__END_ARRAY_REF__/) {
                   5975:       my $value='';
                   5976:       if($string =~ /^__HASH_REF__/) {
                   5977:           ($value, $string)=&str2hashref($string);
                   5978:           if(defined($value->{'error'})) {
                   5979:               $array[0] ='Array reference error';
                   5980:               return (\@array, $string);
                   5981:           }
                   5982:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5983:           ($value, $string)=&str2arrayref($string);
                   5984:           if($value->[0] eq 'Array reference error') {
                   5985:               $array[0] ='Array reference error';
                   5986:               return (\@array, $string);
                   5987:           }
                   5988:       } else {
                   5989: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5990:       }
                   5991:       $string =~ s/^&//;
                   5992: 
                   5993:       push(@array, $value);
1.191     harris41 5994:   }
1.265     albertel 5995: 
                   5996:   $string =~ s/^__END_ARRAY_REF__//;
                   5997: 
                   5998:   return (\@array, $string);
1.168     albertel 5999: }
                   6000: 
1.167     albertel 6001: # -------------------------------------------------------------------Temp Store
                   6002: 
1.168     albertel 6003: sub tmpreset {
                   6004:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6005:   if (!$symb) {
                   6006:     $symb=&symbread();
1.620     albertel 6007:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6008:   }
                   6009:   $symb=escape($symb);
                   6010: 
1.620     albertel 6011:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6012:   $namespace=~s/\//\_/g;
                   6013:   $namespace=~s/\W//g;
                   6014: 
1.620     albertel 6015:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6016:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6017:   if ($domain eq 'public' && $stuname eq 'public') {
                   6018:       $stuname=$ENV{'REMOTE_ADDR'};
                   6019:   }
1.1117    foxr     6020:   my $path=LONCAPA::tempdir();
1.168     albertel 6021:   my %hash;
                   6022:   if (tie(%hash,'GDBM_File',
                   6023: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6024: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6025:     foreach my $key (keys(%hash)) {
1.180     albertel 6026:       if ($key=~ /:$symb/) {
1.168     albertel 6027: 	delete($hash{$key});
                   6028:       }
                   6029:     }
                   6030:   }
                   6031: }
                   6032: 
1.167     albertel 6033: sub tmpstore {
1.168     albertel 6034:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6035: 
                   6036:   if (!$symb) {
                   6037:     $symb=&symbread();
1.620     albertel 6038:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6039:   }
                   6040:   $symb=escape($symb);
                   6041: 
                   6042:   if (!$namespace) {
                   6043:     # I don't think we would ever want to store this for a course.
                   6044:     # it seems this will only be used if we don't have a course.
1.620     albertel 6045:     #$namespace=$env{'request.course.id'};
1.168     albertel 6046:     #if (!$namespace) {
1.620     albertel 6047:       $namespace=$env{'request.state'};
1.168     albertel 6048:     #}
                   6049:   }
                   6050:   $namespace=~s/\//\_/g;
                   6051:   $namespace=~s/\W//g;
1.620     albertel 6052:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6053:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6054:   if ($domain eq 'public' && $stuname eq 'public') {
                   6055:       $stuname=$ENV{'REMOTE_ADDR'};
                   6056:   }
1.168     albertel 6057:   my $now=time;
                   6058:   my %hash;
1.1117    foxr     6059:   my $path=LONCAPA::tempdir();
1.168     albertel 6060:   if (tie(%hash,'GDBM_File',
                   6061: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6062: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6063:     $hash{"version:$symb"}++;
                   6064:     my $version=$hash{"version:$symb"};
                   6065:     my $allkeys=''; 
                   6066:     foreach my $key (keys(%$storehash)) {
                   6067:       $allkeys.=$key.':';
1.591     albertel 6068:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6069:     }
                   6070:     $hash{"$version:$symb:timestamp"}=$now;
                   6071:     $allkeys.='timestamp';
                   6072:     $hash{"$version:keys:$symb"}=$allkeys;
                   6073:     if (untie(%hash)) {
                   6074:       return 'ok';
                   6075:     } else {
                   6076:       return "error:$!";
                   6077:     }
                   6078:   } else {
                   6079:     return "error:$!";
                   6080:   }
                   6081: }
1.167     albertel 6082: 
1.168     albertel 6083: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6084: 
1.168     albertel 6085: sub tmprestore {
                   6086:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6087: 
1.168     albertel 6088:   if (!$symb) {
                   6089:     $symb=&symbread();
1.620     albertel 6090:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6091:   }
                   6092:   $symb=escape($symb);
                   6093: 
1.620     albertel 6094:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6095: 
1.620     albertel 6096:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6097:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6098:   if ($domain eq 'public' && $stuname eq 'public') {
                   6099:       $stuname=$ENV{'REMOTE_ADDR'};
                   6100:   }
1.168     albertel 6101:   my %returnhash;
                   6102:   $namespace=~s/\//\_/g;
                   6103:   $namespace=~s/\W//g;
                   6104:   my %hash;
1.1117    foxr     6105:   my $path=LONCAPA::tempdir();
1.168     albertel 6106:   if (tie(%hash,'GDBM_File',
                   6107: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6108: 	  &GDBM_READER(),0640)) {
1.168     albertel 6109:     my $version=$hash{"version:$symb"};
                   6110:     $returnhash{'version'}=$version;
                   6111:     my $scope;
                   6112:     for ($scope=1;$scope<=$version;$scope++) {
                   6113:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6114:       my @keys=split(/:/,$vkeys);
                   6115:       my $key;
                   6116:       $returnhash{"$scope:keys"}=$vkeys;
                   6117:       foreach $key (@keys) {
1.591     albertel 6118: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6119: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6120:       }
                   6121:     }
1.168     albertel 6122:     if (!(untie(%hash))) {
                   6123:       return "error:$!";
                   6124:     }
                   6125:   } else {
                   6126:     return "error:$!";
                   6127:   }
                   6128:   return %returnhash;
1.167     albertel 6129: }
                   6130: 
1.9       www      6131: # ----------------------------------------------------------------------- Store
                   6132: 
                   6133: sub store {
1.1269    raeburn  6134:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6135:     my $home='';
                   6136: 
1.168     albertel 6137:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6138: 
1.213     www      6139:     $symb=&symbclean($symb);
1.122     albertel 6140:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6141: 
1.620     albertel 6142:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6143:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6144: 
                   6145:     &devalidate($symb,$stuname,$domain);
1.109     www      6146: 
                   6147:     $symb=escape($symb);
1.187     www      6148:     if (!$namespace) { 
1.620     albertel 6149:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6150:           return ''; 
                   6151:        } 
                   6152:     }
1.620     albertel 6153:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6154: 
                   6155:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6156:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6157: 
1.12      www      6158:     my $namevalue='';
1.800     albertel 6159:     foreach my $key (keys(%$storehash)) {
                   6160:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6161:     }
1.12      www      6162:     $namevalue=~s/\&$//;
1.187     www      6163:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6164:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6165: }
                   6166: 
1.47      www      6167: # -------------------------------------------------------------- Critical Store
                   6168: 
                   6169: sub cstore {
1.1269    raeburn  6170:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6171:     my $home='';
                   6172: 
1.168     albertel 6173:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6174: 
1.213     www      6175:     $symb=&symbclean($symb);
1.122     albertel 6176:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6177: 
1.620     albertel 6178:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6179:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6180: 
                   6181:     &devalidate($symb,$stuname,$domain);
1.109     www      6182: 
                   6183:     $symb=escape($symb);
1.187     www      6184:     if (!$namespace) { 
1.620     albertel 6185:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6186:           return ''; 
                   6187:        } 
                   6188:     }
1.620     albertel 6189:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6190: 
                   6191:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6192:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6193: 
1.47      www      6194:     my $namevalue='';
1.800     albertel 6195:     foreach my $key (keys(%$storehash)) {
                   6196:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6197:     }
1.47      www      6198:     $namevalue=~s/\&$//;
1.187     www      6199:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6200:     return critical
1.1269    raeburn  6201:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6202: }
                   6203: 
1.9       www      6204: # --------------------------------------------------------------------- Restore
                   6205: 
                   6206: sub restore {
1.124     www      6207:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6208:     my $home='';
                   6209: 
1.168     albertel 6210:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6211: 
1.122     albertel 6212:     if (!$symb) {
1.1224    raeburn  6213:         return if ($namespace eq 'courserequests');
                   6214:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6215:     } else {
1.1224    raeburn  6216:         unless ($namespace eq 'courserequests') {
                   6217:             $symb=&escape(&symbclean($symb));
                   6218:         }
1.122     albertel 6219:     }
1.188     www      6220:     if (!$namespace) { 
1.620     albertel 6221:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6222:           return ''; 
                   6223:        } 
                   6224:     }
1.620     albertel 6225:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6226:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6227:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6228:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6229: 
1.12      www      6230:     my %returnhash=();
1.800     albertel 6231:     foreach my $line (split(/\&/,$answer)) {
                   6232: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6233:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6234:     }
1.75      www      6235:     my $version;
                   6236:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6237:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6238:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6239:        }
1.75      www      6240:     }
1.13      www      6241:     return %returnhash;
1.34      www      6242: }
                   6243: 
                   6244: # ---------------------------------------------------------- Course Description
1.1118    foxr     6245: #
                   6246: #  
1.34      www      6247: 
                   6248: sub coursedescription {
1.731     albertel 6249:     my ($courseid,$args)=@_;
1.34      www      6250:     $courseid=~s/^\///;
1.49      www      6251:     $courseid=~s/\_/\//g;
1.34      www      6252:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6253:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6254:     my $normalid=$cdomain.'_'.$cnum;
                   6255:     # need to always cache even if we get errors otherwise we keep 
                   6256:     # trying and trying and trying to get the course description.
                   6257:     my %envhash=();
                   6258:     my %returnhash=();
1.731     albertel 6259:     
                   6260:     my $expiretime=600;
                   6261:     if ($env{'request.course.id'} eq $normalid) {
                   6262: 	$expiretime=120;
                   6263:     }
                   6264: 
                   6265:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6266:     if (!$args->{'freshen_cache'}
                   6267: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6268: 	foreach my $key (keys(%env)) {
                   6269: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6270: 	    my ($setting) = $1;
                   6271: 	    $returnhash{$setting} = $env{$key};
                   6272: 	}
                   6273: 	return %returnhash;
                   6274:     }
                   6275: 
1.1118    foxr     6276:     # get the data again
                   6277: 
1.731     albertel 6278:     if (!$args->{'one_time'}) {
                   6279: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6280:     }
1.811     albertel 6281: 
1.34      www      6282:     if ($chome ne 'no_host') {
1.302     albertel 6283:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6284:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6285: 	   my $username = $env{'user.name'}; # Defult username
                   6286: 	   if(defined $args->{'user'}) {
                   6287: 	       $username = $args->{'user'};
                   6288: 	   }
1.129     albertel 6289:            $returnhash{'home'}= $chome;
                   6290: 	   $returnhash{'domain'} = $cdomain;
                   6291: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6292:            if (!defined($returnhash{'type'})) {
                   6293:                $returnhash{'type'} = 'Course';
                   6294:            }
1.130     albertel 6295:            while (my ($name,$value) = each %returnhash) {
1.53      www      6296:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6297:            }
1.270     www      6298:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6299:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6300: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6301:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6302:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6303:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6304:        }
                   6305:     }
1.731     albertel 6306:     if (!$args->{'one_time'}) {
1.949     raeburn  6307: 	&appenv(\%envhash);
1.731     albertel 6308:     }
1.302     albertel 6309:     return %returnhash;
1.461     www      6310: }
                   6311: 
1.1080    raeburn  6312: sub update_released_required {
                   6313:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6314:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6315:         $cid = $env{'request.course.id'};
                   6316:         $cdom = $env{'course.'.$cid.'.domain'};
                   6317:         $cnum = $env{'course.'.$cid.'.num'};
                   6318:         $chome = $env{'course.'.$cid.'.home'};
                   6319:     }
                   6320:     if ($needsrelease) {
                   6321:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6322:         my $needsupdate;
                   6323:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6324:             $needsupdate = 1;
                   6325:         } else {
                   6326:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6327:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6328:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6329:                 $needsupdate = 1;
                   6330:             }
                   6331:         }
                   6332:         if ($needsupdate) {
                   6333:             my %needshash = (
                   6334:                              'internal.releaserequired' => $needsrelease,
                   6335:                             );
                   6336:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6337:             if ($putresult eq 'ok') {
                   6338:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6339:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6340:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6341:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6342:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6343:                 }
                   6344:             }
                   6345:         }
                   6346:     }
                   6347:     return;
                   6348: }
                   6349: 
1.461     www      6350: # -------------------------------------------------See if a user is privileged
                   6351: 
                   6352: sub privileged {
1.1219    raeburn  6353:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6354:     my $now = time;
1.1219    raeburn  6355:     my $roles;
                   6356:     if (ref($possroles) eq 'ARRAY') {
                   6357:         $roles = $possroles; 
                   6358:     } else {
                   6359:         $roles = ['dc','su'];
                   6360:     }
                   6361:     if (ref($possdomains) eq 'ARRAY') {
                   6362:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6363:         foreach my $dom (@{$possdomains}) {
                   6364:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6365:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6366:                 foreach my $role (@{$roles}) {
                   6367:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6368:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6369:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6370:                             return 1 unless (($end && $end < $now) ||
                   6371:                                              ($start && $start > $now));
                   6372:                         }
                   6373:                     }
                   6374:                 }
                   6375:             }
                   6376:         }
                   6377:     } else {
                   6378:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6379:         my $now = time;
1.1170    droeschl 6380: 
1.1275    musolffc 6381:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6382:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6383:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6384:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6385:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6386:             }
1.1219    raeburn  6387:         }
                   6388:     }
                   6389:     return 0;
                   6390: }
1.1170    droeschl 6391: 
1.1219    raeburn  6392: sub privileged_by_domain {
                   6393:     my ($domains,$roles) = @_;
                   6394:     my %privileged = ();
                   6395:     my $cachetime = 60*60*24;
                   6396:     my $now = time;
                   6397:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6398:         return %privileged;
                   6399:     }
                   6400:     foreach my $dom (@{$domains}) {
                   6401:         next if (ref($privileged{$dom}) eq 'HASH');
                   6402:         my $needroles;
                   6403:         foreach my $role (@{$roles}) {
                   6404:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6405:             if (defined($cached)) {
                   6406:                 if (ref($result) eq 'HASH') {
                   6407:                     $privileged{$dom}{$role} = $result;
                   6408:                 }
                   6409:             } else {
                   6410:                 $needroles = 1;
                   6411:             }
                   6412:         }
                   6413:         if ($needroles) {
                   6414:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6415:             $privileged{$dom} = {};
                   6416:             foreach my $server (keys(%dompersonnel)) {
                   6417:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6418:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6419:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6420:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6421:                         next if ($end && $end < $now);
                   6422:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6423:                             $dompersonnel{$server}{$item};
                   6424:                     }
                   6425:                 }
                   6426:             }
                   6427:             if (ref($privileged{$dom}) eq 'HASH') {
                   6428:                 foreach my $role (@{$roles}) {
                   6429:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6430:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6431:                     } else {
                   6432:                         my %hash = ();
                   6433:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6434:                     }
                   6435:                 }
                   6436:             }
                   6437:         }
                   6438:     }
                   6439:     return %privileged;
1.9       www      6440: }
1.1       albertel 6441: 
1.103     harris41 6442: # -------------------------------------------------------- Get user privileges
1.11      www      6443: 
                   6444: sub rolesinit {
1.1169    droeschl 6445:     my ($domain, $username) = @_;
                   6446:     my %userroles = ('user.login.time' => time);
                   6447:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6448: 
                   6449:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6450:     # also, blocking can be triggered by an activating timer
                   6451:     # it's saved in the user's %env.
                   6452:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6453:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6454:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6455:         %timerintchk, %timerintenv);
                   6456: 
1.1162    raeburn  6457:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6458:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6459:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6460:     }
1.1169    droeschl 6461: 
1.1162    raeburn  6462:     foreach my $key (keys(%timerinterval)) {
                   6463:         my ($cid,$rest) = split(/\0/,$key);
                   6464:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6465:     }
1.1169    droeschl 6466: 
1.11      www      6467:     my %allroles=();
1.1162    raeburn  6468:     my %allgroups=();
1.11      www      6469: 
1.1274    raeburn  6470:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6471:         my $role = $rolesdump{$area};
                   6472:         $area =~ s/\_\w\w$//;
                   6473: 
                   6474:         my ($trole, $tend, $tstart, $group_privs);
                   6475: 
                   6476:         if ($role =~ /^cr/) {
                   6477:         # Custom role, defined by a user 
                   6478:         # e.g., user.role.cr/msu/smith/mynewrole
                   6479:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6480:                 $trole = $1;
                   6481:                 ($tend, $tstart) = split('_', $2);
                   6482:             } else {
                   6483:                 $trole = $role;
                   6484:             }
                   6485:         } elsif ($role =~ m|^gr/|) {
                   6486:         # Role of member in a group, defined within a course/community
                   6487:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6488:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6489:             next if $tstart eq '-1';
                   6490:             ($trole, $group_privs) = split(/\//, $trole);
                   6491:             $group_privs = &unescape($group_privs);
                   6492:         } else {
                   6493:         # Just a normal role, defined in roles.tab
                   6494:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6495:         }
                   6496: 
                   6497:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6498:                  $username);
                   6499:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6500: 
                   6501:         # role expired or not available yet?
                   6502:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6503:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6504: 
                   6505:         next if $area eq '' or $trole eq '';
                   6506: 
                   6507:         my $spec = "$trole.$area";
                   6508:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6509: 
                   6510:         if ($trole =~ /^cr\//) {
                   6511:         # Custom role, defined by a user
                   6512:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6513:         } elsif ($trole eq 'gr') {
                   6514:         # Role of a member in a group, defined within a course/community
                   6515:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6516:             next;
                   6517:         } else {
                   6518:         # Normal role, defined in roles.tab
                   6519:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6520:         }
                   6521: 
                   6522:         my $cid = $tdomain.'_'.$trest;
                   6523:         unless ($firstaccchk{$cid}) {
                   6524:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6525:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6526:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6527:                         $coursetimerstarts{$cid}{$item}; 
                   6528:                 }
                   6529:             }
                   6530:             $firstaccchk{$cid} = 1;
                   6531:         }
                   6532:         unless ($timerintchk{$cid}) {
                   6533:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6534:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6535:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6536:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6537:                 }
1.12      www      6538:             }
1.1169    droeschl 6539:             $timerintchk{$cid} = 1;
1.191     harris41 6540:         }
1.11      www      6541:     }
1.1169    droeschl 6542: 
1.1341    raeburn  6543:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6544:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6545:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6546:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6547: 
1.1162    raeburn  6548:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6549: }
                   6550: 
1.567     raeburn  6551: sub set_arearole {
1.1215    raeburn  6552:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6553:     unless ($nolog) {
1.567     raeburn  6554: # log the associated role with the area
1.1215    raeburn  6555:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6556:     }
1.743     albertel 6557:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6558: }
                   6559: 
                   6560: sub custom_roleprivs {
                   6561:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6562:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6563:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6564:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6565:         my ($rdummy,$roledef)=
                   6566:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6567:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6568:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6569:             if (defined($syspriv)) {
1.1043    raeburn  6570:                 if ($trest =~ /^$match_community$/) {
                   6571:                     $syspriv =~ s/bre\&S//; 
                   6572:                 }
1.567     raeburn  6573:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6574:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6575:             }
                   6576:             if ($tdomain ne '') {
                   6577:                 if (defined($dompriv)) {
                   6578:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6579:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6580:                 }
                   6581:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6582:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6583:                         my $rolename = $1;
                   6584:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6585:                     }
1.567     raeburn  6586:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6587:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6588:                 }
                   6589:             }
                   6590:         }
                   6591:     }
                   6592: }
                   6593: 
1.1332    raeburn  6594: sub course_adhocrole_privs {
                   6595:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6596:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6597:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6598:         my (%currprivs,%storeprivs);
                   6599:         foreach my $item (split(/:/,$coursepriv)) {
                   6600:             my ($priv,$restrict) = split(/\&/,$item);
                   6601:             $currprivs{$priv} = $restrict;
                   6602:         }
                   6603:         my (%possadd,%possremove,%full);
                   6604:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6605:             my ($priv,$restrict)=split(/\&/,$item);
                   6606:             $full{$priv} = $restrict;
                   6607:         }
                   6608:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6609:              next if ($item eq '');
                   6610:              my ($rule,$rest) = split(/=/,$item);
                   6611:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6612:              foreach my $priv (split(/:/,$rest)) {
                   6613:                  if ($priv ne '') {
                   6614:                      if ($rule eq 'off') {
                   6615:                          $possremove{$priv} = 1;
                   6616:                      } else {
                   6617:                          $possadd{$priv} = 1;
                   6618:                      }
                   6619:                  }
                   6620:              }
                   6621:          }
                   6622:          foreach my $priv (sort(keys(%full))) {
                   6623:              if (exists($currprivs{$priv})) {
                   6624:                  unless (exists($possremove{$priv})) {
                   6625:                      $storeprivs{$priv} = $currprivs{$priv};
                   6626:                  }
                   6627:              } elsif (exists($possadd{$priv})) {
                   6628:                  $storeprivs{$priv} = $full{$priv};
                   6629:              }
                   6630:          }
                   6631:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6632:      }
                   6633:      return $coursepriv;
                   6634: }
                   6635: 
1.678     raeburn  6636: sub group_roleprivs {
                   6637:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6638:     my $access = 1;
                   6639:     my $now = time;
                   6640:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6641:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6642:     if ($access) {
1.811     albertel 6643:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6644:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6645:     }
                   6646: }
1.567     raeburn  6647: 
                   6648: sub standard_roleprivs {
                   6649:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6650:     if (defined($pr{$trole.':s'})) {
                   6651:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6652:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6653:     }
                   6654:     if ($tdomain ne '') {
                   6655:         if (defined($pr{$trole.':d'})) {
                   6656:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6657:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6658:         }
                   6659:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6660:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6661:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6662:         }
                   6663:     }
                   6664: }
                   6665: 
                   6666: sub set_userprivs {
1.1064    raeburn  6667:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6668:     my $author=0;
                   6669:     my $adv=0;
1.1341    raeburn  6670:     my $rar=0;
1.678     raeburn  6671:     my %grouproles = ();
                   6672:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6673:         my @groupkeys; 
1.1000    raeburn  6674:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6675:             push(@groupkeys,$role);
                   6676:         }
                   6677:         if (ref($groups_roles) eq 'HASH') {
                   6678:             foreach my $key (keys(%{$groups_roles})) {
                   6679:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6680:                     push(@groupkeys,$key);
                   6681:                 }
                   6682:             }
                   6683:         }
                   6684:         if (@groupkeys > 0) {
                   6685:             foreach my $role (@groupkeys) {
                   6686:                 my ($trole,$area,$sec,$extendedarea);
                   6687:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6688:                     $trole = $1;
                   6689:                     $area = $2;
                   6690:                     $sec = $3;
                   6691:                     $extendedarea = $area.$sec;
                   6692:                     if (exists($$allgroups{$area})) {
                   6693:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6694:                             my $spec = $trole.'.'.$extendedarea;
                   6695:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6696:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6697:                         }
1.678     raeburn  6698:                     }
                   6699:                 }
                   6700:             }
                   6701:         }
                   6702:     }
1.800     albertel 6703:     foreach my $group (keys(%grouproles)) {
                   6704:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6705:     }
1.800     albertel 6706:     foreach my $role (keys(%{$allroles})) {
                   6707:         my %thesepriv;
1.941     raeburn  6708:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6709:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6710:             if ($item ne '') {
                   6711:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6712:                 if ($restrictions eq '') {
                   6713:                     $thesepriv{$privilege}='F';
                   6714:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6715:                     $thesepriv{$privilege}.=$restrictions;
                   6716:                 }
                   6717:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6718:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6719:             }
                   6720:         }
                   6721:         my $thesestr='';
1.1104    raeburn  6722:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6723: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6724: 	}
                   6725:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6726:     }
1.1341    raeburn  6727:     return ($author,$adv,$rar);
1.567     raeburn  6728: }
                   6729: 
1.994     raeburn  6730: sub role_status {
1.1104    raeburn  6731:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6732:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6733:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6734:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6735:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6736:             $$where = '/'.$two;
1.994     raeburn  6737:             $$trolecode=$$role.'.'.$$where;
                   6738:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6739:             $$tstatus='is';
1.1104    raeburn  6740:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6741:                 $$tstatus='future';
1.1034    raeburn  6742:                 if ($$tstart<$now) {
                   6743:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6744:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6745:                             my (%allroles,%allgroups,$group_privs,
                   6746:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6747:                             my %userroles = (
                   6748:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6749:                             );
1.1064    raeburn  6750:                             @rolecodes = ('cm'); 
1.1002    raeburn  6751:                             my $spec=$$role.'.'.$$where;
                   6752:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6753:                             if ($$role =~ /^cr\//) {
                   6754:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6755:                                 push(@rolecodes,'cr');
1.1002    raeburn  6756:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6757:                                 push(@rolecodes,$$role);
1.1002    raeburn  6758:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6759:                                                     $env{'user.name'});
1.1064    raeburn  6760:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6761:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6762:                                 $group_privs = &unescape($group_privs);
                   6763:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6764:                                 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  6765:                                 &get_groups_roles($tdomain,$trest,
                   6766:                                                   \%course_roles,\@rolecodes,
                   6767:                                                   \%groups_roles);
1.1002    raeburn  6768:                             } else {
1.1064    raeburn  6769:                                 push(@rolecodes,$$role);
1.1002    raeburn  6770:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6771:                             }
1.1341    raeburn  6772:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6773:                                                                    \%groups_roles);
1.1064    raeburn  6774:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6775:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6776:                         }
                   6777:                     }
1.1034    raeburn  6778:                     $$tstatus = 'is';
1.1002    raeburn  6779:                 }
1.994     raeburn  6780:             }
                   6781:             if ($$tend) {
1.1104    raeburn  6782:                 if ($$tend<$update) {
1.994     raeburn  6783:                     $$tstatus='expired';
                   6784:                 } elsif ($$tend<$now) {
                   6785:                     $$tstatus='will_not';
                   6786:                 }
                   6787:             }
                   6788:         }
                   6789:     }
                   6790: }
                   6791: 
1.1104    raeburn  6792: sub get_groups_roles {
                   6793:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6794:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6795:                   (ref($rolecodes) eq 'ARRAY') && 
                   6796:                   (ref($groups_roles) eq 'HASH')); 
                   6797:     if (keys(%{$cdom_courseroles}) > 0) {
                   6798:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6799:         if ($cdom ne '' && $cnum ne '') {
                   6800:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6801:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6802:                     my $crsrole = $1;
                   6803:                     my $crssec = $2;
                   6804:                     if ($crsrole =~ /^cr/) {
                   6805:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6806:                             push(@{$rolecodes},'cr');
                   6807:                         }
                   6808:                     } else {
                   6809:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6810:                             push(@{$rolecodes},$crsrole);
                   6811:                         }
                   6812:                     }
                   6813:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6814:                     if ($crssec ne '') {
                   6815:                         $rolekey .= "/$crssec";
                   6816:                     }
                   6817:                     $rolekey .= './';
                   6818:                     $groups_roles->{$rolekey} = $rolecodes;
                   6819:                 }
                   6820:             }
                   6821:         }
                   6822:     }
                   6823:     return;
                   6824: }
                   6825: 
                   6826: sub delete_env_groupprivs {
                   6827:     my ($where,$courseroles,$possroles) = @_;
                   6828:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6829:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6830:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6831:         %{$courseroles->{$udom}} =
                   6832:             &get_my_roles('','','userroles',['active'],
                   6833:                           $possroles,[$udom],1);
                   6834:     }
                   6835:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6836:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6837:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6838:             my $area = '/'.$cdom.'/'.$cnum;
                   6839:             my $privkey = "user.priv.$crsrole.$area";
                   6840:             if ($crssec ne '') {
                   6841:                 $privkey .= '/'.$crssec;
                   6842:             }
                   6843:             $privkey .= ".$area/$group";
                   6844:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6845:         }
                   6846:     }
                   6847:     return;
                   6848: }
                   6849: 
1.994     raeburn  6850: sub check_adhoc_privs {
1.1329    raeburn  6851:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6852:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6853:     if ($sec) {
                   6854:         $cckey .= '/'.$sec;
                   6855:     } 
1.1185    raeburn  6856:     my $setprivs;
1.994     raeburn  6857:     if ($env{$cckey}) {
                   6858:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6859:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6860:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6861:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6862:             $setprivs = 1;
1.994     raeburn  6863:         }
                   6864:     } else {
1.1330    raeburn  6865:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6866:         $setprivs = 1;
1.994     raeburn  6867:     }
1.1185    raeburn  6868:     return $setprivs;
1.994     raeburn  6869: }
                   6870: 
                   6871: sub set_adhoc_privileges {
1.1326    raeburn  6872: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6873:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6874:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6875:     if ($sec ne '') {
                   6876:         $area .= '/'.$sec;
                   6877:     }
1.994     raeburn  6878:     my $spec = $role.'.'.$area;
                   6879:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6880:                                   $env{'user.name'},1);
1.1326    raeburn  6881:     my %rolehash = ();
1.1332    raeburn  6882:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6883:         my $rolename = $1;
1.1326    raeburn  6884:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6885:         my %domdef = &get_domain_defaults($dcdom);
                   6886:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6887:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6888:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6889:             }
                   6890:         }
1.1326    raeburn  6891:     } else {
                   6892:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6893:     }
1.1341    raeburn  6894:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6895:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6896:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  6897:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6898:             ($caller eq 'tiny')) {
1.1088    raeburn  6899:         &appenv( {'request.role'        => $spec,
                   6900:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6901:                   'request.course.sec'  => $sec,
1.1088    raeburn  6902:                  }
                   6903:                );
                   6904:         my $tadv=0;
                   6905:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6906:         &appenv({'request.role.adv'    => $tadv});
                   6907:     }
1.994     raeburn  6908: }
                   6909: 
1.12      www      6910: # --------------------------------------------------------------- get interface
                   6911: 
                   6912: sub get {
1.131     albertel 6913:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6914:    my $items='';
1.800     albertel 6915:    foreach my $item (@$storearr) {
                   6916:        $items.=&escape($item).'&';
1.191     harris41 6917:    }
1.12      www      6918:    $items=~s/\&$//;
1.620     albertel 6919:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6920:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6921:    my $uhome=&homeserver($uname,$udomain);
                   6922: 
1.133     albertel 6923:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6924:    my @pairs=split(/\&/,$rep);
1.273     albertel 6925:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6926:      return @pairs;
                   6927:    }
1.15      www      6928:    my %returnhash=();
1.42      www      6929:    my $i=0;
1.800     albertel 6930:    foreach my $item (@$storearr) {
                   6931:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6932:       $i++;
1.191     harris41 6933:    }
1.15      www      6934:    return %returnhash;
1.27      www      6935: }
                   6936: 
                   6937: # --------------------------------------------------------------- del interface
                   6938: 
                   6939: sub del {
1.133     albertel 6940:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6941:    my $items='';
1.800     albertel 6942:    foreach my $item (@$storearr) {
                   6943:        $items.=&escape($item).'&';
1.191     harris41 6944:    }
1.984     neumanie 6945: 
1.27      www      6946:    $items=~s/\&$//;
1.620     albertel 6947:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6948:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6949:    my $uhome=&homeserver($uname,$udomain);
                   6950:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6951: }
                   6952: 
                   6953: # -------------------------------------------------------------- dump interface
                   6954: 
1.1180    droeschl 6955: sub unserialize {
                   6956:     my ($rep, $escapedkeys) = @_;
                   6957: 
                   6958:     return {} if $rep =~ /^error/;
                   6959: 
                   6960:     my %returnhash=();
1.1252    raeburn  6961: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6962: 	    my ($key, $value) = split(/=/, $item, 2);
                   6963: 	    $key = unescape($key) unless $escapedkeys;
                   6964: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6965: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6966: 	}
                   6967:     #return %returnhash;
                   6968:     return \%returnhash;
                   6969: }        
                   6970: 
                   6971: # see Lond::dump_with_regexp
                   6972: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6973: sub dump {
1.1180    droeschl 6974:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6975:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6976:     if (!$uname) { $uname=$env{'user.name'}; }
                   6977:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6978: 
1.1266    raeburn  6979:     if ($regexp) {
                   6980:         $regexp=&escape($regexp);
                   6981:     } else {
                   6982:         $regexp='.';
                   6983:     }
1.1180    droeschl 6984:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6985:         # user is hosted on this machine
1.1266    raeburn  6986:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6987:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6988:         return %{unserialize($reply, $escapedkeys)};
                   6989:     }
1.1166    raeburn  6990:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6991:     my @pairs=split(/\&/,$rep);
                   6992:     my %returnhash=();
1.1098    foxr     6993:     if (!($rep =~ /^error/ )) {
                   6994: 	foreach my $item (@pairs) {
                   6995: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6996:         $key = unescape($key) unless $escapedkeys;
                   6997:         #$key = &unescape($key);
1.1098    foxr     6998: 	    next if ($key =~ /^error: 2 /);
                   6999: 	    $returnhash{$key}=&thaw_unescape($value);
                   7000: 	}
1.755     albertel 7001:     }
                   7002:     return %returnhash;
1.407     www      7003: }
                   7004: 
1.1098    foxr     7005: 
1.717     albertel 7006: # --------------------------------------------------------- dumpstore interface
                   7007: 
                   7008: sub dumpstore {
                   7009:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7010:    # same as dump but keys must be escaped. They may contain colon separated
                   7011:    # lists of values that may themself contain colons (e.g. symbs).
                   7012:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7013: }
                   7014: 
1.407     www      7015: # -------------------------------------------------------------- keys interface
                   7016: 
                   7017: sub getkeys {
                   7018:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7019:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7020:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7021:    my $uhome=&homeserver($uname,$udomain);
                   7022:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7023:    my @keyarray=();
1.800     albertel 7024:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7025:       next if ($key =~ /^error: 2 /);
1.800     albertel 7026:       push(@keyarray,&unescape($key));
1.407     www      7027:    }
                   7028:    return @keyarray;
1.318     matthew  7029: }
                   7030: 
1.319     matthew  7031: # --------------------------------------------------------------- currentdump
                   7032: sub currentdump {
1.328     matthew  7033:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7034:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7035:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7036:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7037:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7038:    my $rep;
                   7039: 
                   7040:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7041:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7042:                    $courseid)));
                   7043:    } else {
                   7044:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7045:    }
                   7046: 
1.318     matthew  7047:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7048:    #
1.318     matthew  7049:    my %returnhash=();
1.319     matthew  7050:    #
1.1343    raeburn  7051:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7052:        # an old lond will not know currentdump
                   7053:        # Do a dump and make it look like a currentdump
1.822     albertel 7054:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7055:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7056:        my %hash = @tmp;
                   7057:        @tmp=();
1.424     matthew  7058:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7059:    } else {
                   7060:        my @pairs=split(/\&/,$rep);
1.800     albertel 7061:        foreach my $pair (@pairs) {
                   7062:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7063:            my ($symb,$param) = split(/:/,$key);
                   7064:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7065:                                                         &thaw_unescape($value);
1.319     matthew  7066:        }
1.191     harris41 7067:    }
1.12      www      7068:    return %returnhash;
1.424     matthew  7069: }
                   7070: 
                   7071: sub convert_dump_to_currentdump{
                   7072:     my %hash = %{shift()};
                   7073:     my %returnhash;
                   7074:     # Code ripped from lond, essentially.  The only difference
                   7075:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7076:     # we might run in to problems with parameter names =~ /^v\./
                   7077:     while (my ($key,$value) = each(%hash)) {
                   7078:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7079: 	$symb  = &unescape($symb);
                   7080: 	$param = &unescape($param);
1.424     matthew  7081:         next if ($v eq 'version' || $symb eq 'keys');
                   7082:         next if (exists($returnhash{$symb}) &&
                   7083:                  exists($returnhash{$symb}->{$param}) &&
                   7084:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7085:         $returnhash{$symb}->{$param}=$value;
                   7086:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7087:     }
                   7088:     #
                   7089:     # Remove all of the keys in the hashes which keep track of
                   7090:     # the version of the parameter.
                   7091:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7092:         # use a foreach because we are going to delete from the hash.
                   7093:         foreach my $key (keys(%$param_hash)) {
                   7094:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7095:         }
                   7096:     }
                   7097:     return \%returnhash;
1.12      www      7098: }
                   7099: 
1.627     albertel 7100: # ------------------------------------------------------ critical inc interface
                   7101: 
                   7102: sub cinc {
                   7103:     return &inc(@_,'critical');
                   7104: }
                   7105: 
1.449     matthew  7106: # --------------------------------------------------------------- inc interface
                   7107: 
                   7108: sub inc {
1.627     albertel 7109:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7110:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7111:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7112:     my $uhome=&homeserver($uname,$udomain);
                   7113:     my $items='';
                   7114:     if (! ref($store)) {
                   7115:         # got a single value, so use that instead
                   7116:         $items = &escape($store).'=&';
                   7117:     } elsif (ref($store) eq 'SCALAR') {
                   7118:         $items = &escape($$store).'=&';        
                   7119:     } elsif (ref($store) eq 'ARRAY') {
                   7120:         $items = join('=&',map {&escape($_);} @{$store});
                   7121:     } elsif (ref($store) eq 'HASH') {
                   7122:         while (my($key,$value) = each(%{$store})) {
                   7123:             $items.= &escape($key).'='.&escape($value).'&';
                   7124:         }
                   7125:     }
                   7126:     $items=~s/\&$//;
1.627     albertel 7127:     if ($critical) {
                   7128: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7129:     } else {
                   7130: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7131:     }
1.449     matthew  7132: }
                   7133: 
1.12      www      7134: # --------------------------------------------------------------- put interface
                   7135: 
                   7136: sub put {
1.134     albertel 7137:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7138:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7139:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7140:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7141:    my $items='';
1.800     albertel 7142:    foreach my $item (keys(%$storehash)) {
                   7143:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7144:    }
1.12      www      7145:    $items=~s/\&$//;
1.134     albertel 7146:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7147: }
                   7148: 
1.631     albertel 7149: # ------------------------------------------------------------ newput interface
                   7150: 
                   7151: sub newput {
                   7152:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7154:    if (!$uname) { $uname=$env{'user.name'}; }
                   7155:    my $uhome=&homeserver($uname,$udomain);
                   7156:    my $items='';
                   7157:    foreach my $key (keys(%$storehash)) {
                   7158:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7159:    }
                   7160:    $items=~s/\&$//;
                   7161:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7162: }
                   7163: 
                   7164: # ---------------------------------------------------------  putstore interface
                   7165: 
1.524     raeburn  7166: sub putstore {
1.1269    raeburn  7167:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7168:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7169:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7170:    my $uhome=&homeserver($uname,$udomain);
                   7171:    my $items='';
1.715     albertel 7172:    foreach my $key (keys(%$storehash)) {
                   7173:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7174:    }
1.715     albertel 7175:    $items=~s/\&$//;
1.716     albertel 7176:    my $esc_symb=&escape($symb);
                   7177:    my $esc_v=&escape($version);
1.715     albertel 7178:    my $reply =
1.716     albertel 7179:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7180: 	      $uhome);
1.1269    raeburn  7181:    if (($tolog) && ($reply eq 'ok')) {
                   7182:        my $namevalue='';
                   7183:        foreach my $key (keys(%{$storehash})) {
                   7184:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7185:        }
                   7186:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7187:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7188:                      '&version='.$esc_v.
                   7189:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7190:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7191:    }
1.715     albertel 7192:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7193:        # gfall back to way things use to be done
1.715     albertel 7194:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7195: 			    $uname);
1.524     raeburn  7196:    }
1.715     albertel 7197:    return $reply;
                   7198: }
                   7199: 
                   7200: sub old_putstore {
1.716     albertel 7201:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7202:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7203:     if (!$uname) { $uname=$env{'user.name'}; }
                   7204:     my $uhome=&homeserver($uname,$udomain);
                   7205:     my %newstorehash;
1.800     albertel 7206:     foreach my $item (keys(%$storehash)) {
                   7207: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7208: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7209:     }
                   7210:     my $items='';
                   7211:     my %allitems = ();
1.800     albertel 7212:     foreach my $item (keys(%newstorehash)) {
                   7213: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7214: 	    my $key = $1.':keys:'.$2;
                   7215: 	    $allitems{$key} .= $3.':';
                   7216: 	}
1.800     albertel 7217: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7218:     }
1.800     albertel 7219:     foreach my $item (keys(%allitems)) {
                   7220: 	$allitems{$item} =~ s/\:$//;
                   7221: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7222:     }
                   7223:     $items=~s/\&$//;
                   7224:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7225: }
                   7226: 
1.47      www      7227: # ------------------------------------------------------ critical put interface
                   7228: 
                   7229: sub cput {
1.134     albertel 7230:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7231:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7232:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7233:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7234:    my $items='';
1.800     albertel 7235:    foreach my $item (keys(%$storehash)) {
                   7236:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7237:    }
1.47      www      7238:    $items=~s/\&$//;
1.134     albertel 7239:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7240: }
                   7241: 
                   7242: # -------------------------------------------------------------- eget interface
                   7243: 
                   7244: sub eget {
1.133     albertel 7245:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7246:    my $items='';
1.800     albertel 7247:    foreach my $item (@$storearr) {
                   7248:        $items.=&escape($item).'&';
1.191     harris41 7249:    }
1.12      www      7250:    $items=~s/\&$//;
1.620     albertel 7251:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7252:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7253:    my $uhome=&homeserver($uname,$udomain);
                   7254:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7255:    my @pairs=split(/\&/,$rep);
                   7256:    my %returnhash=();
1.42      www      7257:    my $i=0;
1.800     albertel 7258:    foreach my $item (@$storearr) {
                   7259:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7260:       $i++;
1.191     harris41 7261:    }
1.12      www      7262:    return %returnhash;
                   7263: }
                   7264: 
1.667     albertel 7265: # ------------------------------------------------------------ tmpput interface
                   7266: sub tmpput {
1.802     raeburn  7267:     my ($storehash,$server,$context)=@_;
1.667     albertel 7268:     my $items='';
1.800     albertel 7269:     foreach my $item (keys(%$storehash)) {
                   7270: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7271:     }
                   7272:     $items=~s/\&$//;
1.802     raeburn  7273:     if (defined($context)) {
                   7274:         $items .= ':'.&escape($context);
                   7275:     }
1.667     albertel 7276:     return &reply("tmpput:$items",$server);
                   7277: }
                   7278: 
                   7279: # ------------------------------------------------------------ tmpget interface
                   7280: sub tmpget {
1.688     albertel 7281:     my ($token,$server)=@_;
                   7282:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7283:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7284:     my %returnhash;
1.1328    raeburn  7285:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7286:         return %returnhash;
                   7287:     }
1.667     albertel 7288:     foreach my $item (split(/\&/,$rep)) {
                   7289: 	my ($key,$value)=split(/=/,$item);
                   7290: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7291:     }
                   7292:     return %returnhash;
                   7293: }
                   7294: 
1.1113    raeburn  7295: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7296: sub tmpdel {
                   7297:     my ($token,$server)=@_;
                   7298:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7299:     return &reply("tmpdel:$token",$server);
                   7300: }
                   7301: 
1.1198    raeburn  7302: # ------------------------------------------------------------ get_timebased_id 
                   7303: 
                   7304: sub get_timebased_id {
                   7305:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7306:         $maxtries) = @_;
                   7307:     my ($newid,$error,$dellock);
                   7308:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7309:         return ('','ok','invalid call to get suffix');
                   7310:     }
                   7311: 
                   7312: # set defaults for any optional args for which values were not supplied
                   7313:     if ($who eq '') {
                   7314:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7315:     }
                   7316:     if (!$locktries) {
                   7317:         $locktries = 3;
                   7318:     }
                   7319:     if (!$maxtries) {
                   7320:         $maxtries = 10;
                   7321:     }
                   7322:     
                   7323:     if (($cdom eq '') || ($cnum eq '')) {
                   7324:         if ($env{'request.course.id'}) {
                   7325:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7326:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7327:         }
                   7328:         if (($cdom eq '') || ($cnum eq '')) {
                   7329:             return ('','ok','call to get suffix not in course context');
                   7330:         }
                   7331:     }
                   7332: 
                   7333: # construct locking item
                   7334:     my $lockhash = {
                   7335:                       $prefix."\0".'locked_'.$keyid => $who,
                   7336:                    };
                   7337:     my $tries = 0;
                   7338: 
                   7339: # attempt to get lock on nohist_$namespace file
                   7340:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7341:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7342:         $tries ++;
                   7343:         sleep 1;
                   7344:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7345:     }
                   7346: 
                   7347: # attempt to get unique identifier, based on current timestamp
                   7348:     if ($gotlock eq 'ok') {
                   7349:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7350:         my $id = time;
                   7351:         $newid = $id;
1.1268    raeburn  7352:         if ($idtype eq 'addcode') {
                   7353:             $newid .= &sixnum_code();
                   7354:         }
1.1198    raeburn  7355:         my $idtries = 0;
                   7356:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7357:             if ($idtype eq 'concat') {
                   7358:                 $newid = $id.$idtries;
1.1268    raeburn  7359:             } elsif ($idtype eq 'addcode') {
                   7360:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7361:             } else {
                   7362:                 $newid ++;
                   7363:             }
                   7364:             $idtries ++;
                   7365:         }
                   7366:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7367:             my %new_item =  (
                   7368:                               $prefix."\0".$newid => $who,
                   7369:                             );
                   7370:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7371:                                                  $cdom,$cnum);
                   7372:             if ($putresult ne 'ok') {
                   7373:                 undef($newid);
                   7374:                 $error = 'error saving new item: '.$putresult;
                   7375:             }
                   7376:         } else {
1.1268    raeburn  7377:              undef($newid);
1.1198    raeburn  7378:              $error = ('error: no unique suffix available for the new item ');
                   7379:         }
                   7380: #  remove lock
                   7381:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7382:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7383:     } else {
                   7384:         $error = "error: could not obtain lockfile\n";
                   7385:         $dellock = 'ok';
1.1276    raeburn  7386:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7387:             $dellock = 'nolock';
                   7388:         }
1.1198    raeburn  7389:     }
                   7390:     return ($newid,$dellock,$error);
                   7391: }
                   7392: 
1.1268    raeburn  7393: sub sixnum_code {
                   7394:     my $code;
                   7395:     for (0..6) {
                   7396:         $code .= int( rand(9) );
                   7397:     }
                   7398:     return $code;
                   7399: }
                   7400: 
1.765     albertel 7401: # -------------------------------------------------- portfolio access checking
                   7402: 
                   7403: sub portfolio_access {
1.1270    raeburn  7404:     my ($requrl,$clientip) = @_;
1.765     albertel 7405:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7406:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7407:     if ($result) {
                   7408:         my %setters;
                   7409:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7410:             my ($startblock,$endblock) =
                   7411:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7412:             if ($startblock && $endblock) {
                   7413:                 return 'B';
                   7414:             }
                   7415:         } else {
                   7416:             my ($startblock,$endblock) =
                   7417:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7418:             if ($startblock && $endblock) {
                   7419:                 return 'B';
                   7420:             }
                   7421:         }
                   7422:     }
1.765     albertel 7423:     if ($result eq 'ok') {
1.766     albertel 7424:        return 'F';
1.765     albertel 7425:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7426:        return 'A';
1.765     albertel 7427:     }
1.766     albertel 7428:     return '';
1.765     albertel 7429: }
                   7430: 
                   7431: sub get_portfolio_access {
1.1270    raeburn  7432:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7433: 
                   7434:     if (!ref($access_hash)) {
                   7435: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7436: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7437: 						   $file_name);
                   7438: 	$access_hash = $access_controls{$file_name};
                   7439:     }
                   7440: 
1.1270    raeburn  7441:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7442:     my $now = time;
                   7443:     if (ref($access_hash) eq 'HASH') {
                   7444:         foreach my $key (keys(%{$access_hash})) {
                   7445:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7446:             if ($start > $now) {
                   7447:                 next;
                   7448:             }
                   7449:             if ($end && $end<$now) {
                   7450:                 next;
                   7451:             }
                   7452:             if ($scope eq 'public') {
                   7453:                 $public = $key;
                   7454:                 last;
                   7455:             } elsif ($scope eq 'guest') {
                   7456:                 $guest = $key;
                   7457:             } elsif ($scope eq 'domains') {
                   7458:                 push(@domains,$key);
                   7459:             } elsif ($scope eq 'users') {
                   7460:                 push(@users,$key);
                   7461:             } elsif ($scope eq 'course') {
                   7462:                 push(@courses,$key);
                   7463:             } elsif ($scope eq 'group') {
                   7464:                 push(@groups,$key);
1.1270    raeburn  7465:             } elsif ($scope eq 'ip') {
                   7466:                 push(@ips,$key);
1.765     albertel 7467:             }
                   7468:         }
                   7469:         if ($public) {
                   7470:             return 'ok';
1.1270    raeburn  7471:         } elsif (@ips > 0) {
                   7472:             my $allowed;
                   7473:             foreach my $ipkey (@ips) {
                   7474:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7475:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7476:                         $allowed = 1;
                   7477:                         last; 
                   7478:                     }
                   7479:                 }
                   7480:             }
                   7481:             if ($allowed) {
                   7482:                 return 'ok';
                   7483:             }
1.765     albertel 7484:         }
                   7485:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7486:             if ($guest) {
                   7487:                 return $guest;
                   7488:             }
                   7489:         } else {
                   7490:             if (@domains > 0) {
                   7491:                 foreach my $domkey (@domains) {
                   7492:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7493:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7494:                             return 'ok';
                   7495:                         }
                   7496:                     }
                   7497:                 }
                   7498:             }
                   7499:             if (@users > 0) {
                   7500:                 foreach my $userkey (@users) {
1.865     raeburn  7501:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7502:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7503:                             if (ref($item) eq 'HASH') {
                   7504:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7505:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7506:                                     return 'ok';
                   7507:                                 }
                   7508:                             }
                   7509:                         }
                   7510:                     } 
1.765     albertel 7511:                 }
                   7512:             }
                   7513:             my %roleshash;
                   7514:             my @courses_and_groups = @courses;
                   7515:             push(@courses_and_groups,@groups); 
                   7516:             if (@courses_and_groups > 0) {
                   7517:                 my (%allgroups,%allroles); 
                   7518:                 my ($start,$end,$role,$sec,$group);
                   7519:                 foreach my $envkey (%env) {
1.1060    raeburn  7520:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7521:                         my $cid = $2.'_'.$3; 
                   7522:                         if ($1 eq 'gr') {
                   7523:                             $group = $4;
                   7524:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7525:                         } else {
                   7526:                             if ($4 eq '') {
                   7527:                                 $sec = 'none';
                   7528:                             } else {
                   7529:                                 $sec = $4;
                   7530:                             }
                   7531:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7532:                         }
1.811     albertel 7533:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7534:                         my $cid = $2.'_'.$3;
                   7535:                         if ($4 eq '') {
                   7536:                             $sec = 'none';
                   7537:                         } else {
                   7538:                             $sec = $4;
                   7539:                         }
                   7540:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7541:                     }
                   7542:                 }
                   7543:                 if (keys(%allroles) == 0) {
                   7544:                     return;
                   7545:                 }
                   7546:                 foreach my $key (@courses_and_groups) {
                   7547:                     my %content = %{$$access_hash{$key}};
                   7548:                     my $cnum = $content{'number'};
                   7549:                     my $cdom = $content{'domain'};
                   7550:                     my $cid = $cdom.'_'.$cnum;
                   7551:                     if (!exists($allroles{$cid})) {
                   7552:                         next;
                   7553:                     }    
                   7554:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7555:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7556:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7557:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7558:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7559:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7560:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7561:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7562:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7563:                                         if (grep/^all$/,@sections) {
                   7564:                                             return 'ok';
                   7565:                                         } else {
                   7566:                                             if (grep/^$sec$/,@sections) {
                   7567:                                                 return 'ok';
                   7568:                                             }
                   7569:                                         }
                   7570:                                     }
                   7571:                                 }
                   7572:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7573:                                     if (grep/^none$/,@groups) {
                   7574:                                         return 'ok';
                   7575:                                     }
                   7576:                                 } else {
                   7577:                                     if (grep/^all$/,@groups) {
                   7578:                                         return 'ok';
                   7579:                                     } 
                   7580:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7581:                                         if (grep/^$group$/,@groups) {
                   7582:                                             return 'ok';
                   7583:                                         }
                   7584:                                     }
                   7585:                                 } 
                   7586:                             }
                   7587:                         }
                   7588:                     }
                   7589:                 }
                   7590:             }
                   7591:             if ($guest) {
                   7592:                 return $guest;
                   7593:             }
                   7594:         }
                   7595:     }
                   7596:     return;
                   7597: }
                   7598: 
                   7599: sub course_group_datechecker {
                   7600:     my ($dates,$now,$status) = @_;
                   7601:     my ($start,$end) = split(/\./,$dates);
                   7602:     if (!$start && !$end) {
                   7603:         return 'ok';
                   7604:     }
                   7605:     if (grep/^active$/,@{$status}) {
                   7606:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7607:             return 'ok';
                   7608:         }
                   7609:     }
                   7610:     if (grep/^previous$/,@{$status}) {
                   7611:         if ($end > $now ) {
                   7612:             return 'ok';
                   7613:         }
                   7614:     }
                   7615:     if (grep/^future$/,@{$status}) {
                   7616:         if ($start > $now) {
                   7617:             return 'ok';
                   7618:         }
                   7619:     }
                   7620:     return; 
                   7621: }
                   7622: 
                   7623: sub parse_portfolio_url {
                   7624:     my ($url) = @_;
                   7625: 
                   7626:     my ($type,$udom,$unum,$group,$file_name);
                   7627:     
1.823     albertel 7628:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7629: 	$type = 1;
                   7630:         $udom = $1;
                   7631:         $unum = $2;
                   7632:         $file_name = $3;
1.823     albertel 7633:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7634: 	$type = 2;
                   7635:         $udom = $1;
                   7636:         $unum = $2;
                   7637:         $group = $3;
                   7638:         $file_name = $3.'/'.$4;
                   7639:     }
                   7640:     if (wantarray) {
                   7641: 	return ($type,$udom,$unum,$file_name,$group);
                   7642:     }
                   7643:     return $type;
                   7644: }
                   7645: 
                   7646: sub is_portfolio_url {
                   7647:     my ($url) = @_;
                   7648:     return scalar(&parse_portfolio_url($url));
                   7649: }
                   7650: 
1.798     raeburn  7651: sub is_portfolio_file {
                   7652:     my ($file) = @_;
1.820     raeburn  7653:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7654:         return 1;
                   7655:     }
                   7656:     return;
                   7657: }
                   7658: 
1.976     raeburn  7659: sub usertools_access {
1.1084    raeburn  7660:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7661:     my ($access,%tools);
                   7662:     if ($context eq '') {
                   7663:         $context = 'tools';
                   7664:     }
                   7665:     if ($context eq 'requestcourses') {
                   7666:         %tools = (
                   7667:                       official   => 1,
                   7668:                       unofficial => 1,
1.1006    raeburn  7669:                       community  => 1,
1.1246    raeburn  7670:                       textbook   => 1,
1.1305    raeburn  7671:                       placement  => 1,
1.1368    raeburn  7672:                       lti        => 1,
1.985     raeburn  7673:                  );
1.1183    raeburn  7674:     } elsif ($context eq 'requestauthor') {
                   7675:         %tools = (
                   7676:                       requestauthor => 1,
                   7677:                  );
1.985     raeburn  7678:     } else {
                   7679:         %tools = (
                   7680:                       aboutme   => 1,
                   7681:                       blog      => 1,
1.1177    raeburn  7682:                       webdav    => 1,
1.985     raeburn  7683:                       portfolio => 1,
                   7684:                  );
                   7685:     }
1.976     raeburn  7686:     return if (!defined($tools{$tool}));
                   7687: 
1.1242    raeburn  7688:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7689:         $udom = $env{'user.domain'};
                   7690:         $uname = $env{'user.name'};
                   7691:     }
                   7692: 
1.978     raeburn  7693:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7694:         if ($action ne 'reload') {
1.985     raeburn  7695:             if ($context eq 'requestcourses') {
                   7696:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7697:             } elsif ($context eq 'requestauthor') {
                   7698:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7699:             } else {
                   7700:                 return $env{'environment.availabletools.'.$tool};
                   7701:             }
                   7702:         }
1.976     raeburn  7703:     }
                   7704: 
1.1183    raeburn  7705:     my ($toolstatus,$inststatus,$envkey);
                   7706:     if ($context eq 'requestauthor') {
                   7707:         $envkey = $context; 
                   7708:     } else {
                   7709:         $envkey = $context.'.'.$tool;
                   7710:     }
1.976     raeburn  7711: 
1.985     raeburn  7712:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7713:          ($action ne 'reload')) {
1.1183    raeburn  7714:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7715:         $inststatus = $env{'environment.inststatus'};
                   7716:     } else {
1.1084    raeburn  7717:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7718:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7719:             $inststatus = $userenvref->{'inststatus'};
                   7720:         } else {
1.1183    raeburn  7721:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7722:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7723:             $inststatus = $userenv{'inststatus'};
                   7724:         }
1.976     raeburn  7725:     }
                   7726: 
                   7727:     if ($toolstatus ne '') {
                   7728:         if ($toolstatus) {
                   7729:             $access = 1;
                   7730:         } else {
                   7731:             $access = 0;
                   7732:         }
                   7733:         return $access;
                   7734:     }
                   7735: 
1.1084    raeburn  7736:     my ($is_adv,%domdef);
                   7737:     if (ref($is_advref) eq 'HASH') {
                   7738:         $is_adv = $is_advref->{'is_adv'};
                   7739:     } else {
                   7740:         $is_adv = &is_advanced_user($udom,$uname);
                   7741:     }
                   7742:     if (ref($domdefref) eq 'HASH') {
                   7743:         %domdef = %{$domdefref};
                   7744:     } else {
                   7745:         %domdef = &get_domain_defaults($udom);
                   7746:     }
1.976     raeburn  7747:     if (ref($domdef{$tool}) eq 'HASH') {
                   7748:         if ($is_adv) {
                   7749:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7750:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7751:                     $access = 1;
                   7752:                 } else {
                   7753:                     $access = 0;
                   7754:                 }
                   7755:                 return $access;
                   7756:             }
                   7757:         }
                   7758:         if ($inststatus ne '') {
                   7759:             my ($hasaccess,$hasnoaccess);
                   7760:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7761:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7762:                     if ($domdef{$tool}{$affiliation}) {
                   7763:                         $hasaccess = 1;
                   7764:                     } else {
                   7765:                         $hasnoaccess = 1;
                   7766:                     }
                   7767:                 }
                   7768:             }
                   7769:             if ($hasaccess || $hasnoaccess) {
                   7770:                 if ($hasaccess) {
                   7771:                     $access = 1;
                   7772:                 } elsif ($hasnoaccess) {
                   7773:                     $access = 0; 
                   7774:                 }
                   7775:                 return $access;
                   7776:             }
                   7777:         } else {
                   7778:             if ($domdef{$tool}{'default'} ne '') {
                   7779:                 if ($domdef{$tool}{'default'}) {
                   7780:                     $access = 1;
                   7781:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7782:                     $access = 0;
                   7783:                 }
                   7784:                 return $access;
                   7785:             }
                   7786:         }
                   7787:     } else {
1.1177    raeburn  7788:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7789:             $access = 1;
                   7790:         } else {
                   7791:             $access = 0;
                   7792:         }
1.976     raeburn  7793:         return $access;
                   7794:     }
                   7795: }
                   7796: 
1.1050    raeburn  7797: sub is_course_owner {
                   7798:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7799:     if (($udom eq '') || ($uname eq '')) {
                   7800:         $udom = $env{'user.domain'};
                   7801:         $uname = $env{'user.name'};
                   7802:     }
                   7803:     unless (($udom eq '') || ($uname eq '')) {
                   7804:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7805:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7806:                 return 1;
                   7807:             } else {
                   7808:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7809:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7810:                     return 1;
                   7811:                 }
                   7812:             }
                   7813:         }
                   7814:     }
                   7815:     return;
                   7816: }
                   7817: 
1.976     raeburn  7818: sub is_advanced_user {
                   7819:     my ($udom,$uname) = @_;
1.1085    raeburn  7820:     if ($udom ne '' && $uname ne '') {
                   7821:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7822:             if (wantarray) {
                   7823:                 return ($env{'user.adv'},$env{'user.author'});
                   7824:             } else {
                   7825:                 return $env{'user.adv'};
                   7826:             }
1.1085    raeburn  7827:         }
                   7828:     }
1.976     raeburn  7829:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7830:     my %allroles;
1.1128    raeburn  7831:     my ($is_adv,$is_author);
1.976     raeburn  7832:     foreach my $role (keys(%roleshash)) {
                   7833:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7834:         my $area = '/'.$tdomain.'/'.$trest;
                   7835:         if ($sec ne '') {
                   7836:             $area .= '/'.$sec;
                   7837:         }
                   7838:         if (($area ne '') && ($trole ne '')) {
                   7839:             my $spec=$trole.'.'.$area;
                   7840:             if ($trole =~ /^cr\//) {
                   7841:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7842:             } elsif ($trole ne 'gr') {
                   7843:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7844:             }
1.1128    raeburn  7845:             if ($trole eq 'au') {
                   7846:                 $is_author = 1;
                   7847:             }
1.976     raeburn  7848:         }
                   7849:     }
                   7850:     foreach my $role (keys(%allroles)) {
                   7851:         last if ($is_adv);
                   7852:         foreach my $item (split(/:/,$allroles{$role})) {
                   7853:             if ($item ne '') {
                   7854:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7855:                 if ($privilege eq 'adv') {
                   7856:                     $is_adv = 1;
                   7857:                     last;
                   7858:                 }
                   7859:             }
                   7860:         }
                   7861:     }
1.1128    raeburn  7862:     if (wantarray) {
                   7863:         return ($is_adv,$is_author);
                   7864:     }
1.976     raeburn  7865:     return $is_adv;
                   7866: }
1.798     raeburn  7867: 
1.1035    raeburn  7868: sub check_can_request {
1.1368    raeburn  7869:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7870:     my $canreq = 0;
1.1368    raeburn  7871:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7872:         $uname = $env{'user.name'};
                   7873:         $udom = $env{'user.domain'};
                   7874:     }
1.1035    raeburn  7875:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7876:     my @options = ('approval','validate','autolimit');
                   7877:     my $optregex = join('|',@options);
                   7878:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7879:         foreach my $type (@{$types}) {
1.1368    raeburn  7880:             if (&usertools_access($uname,$udom,$type,undef,
                   7881:                                   'requestcourses')) {
1.1035    raeburn  7882:                 $canreq ++;
1.1036    raeburn  7883:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7884:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7885:                 }
1.1368    raeburn  7886:                 if ($dom eq $udom) {
1.1035    raeburn  7887:                     $can_request->{$type} = 1;
                   7888:                 }
                   7889:             }
1.1368    raeburn  7890:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7891:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7892:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7893:                 if (@curr > 0) {
1.1036    raeburn  7894:                     foreach my $item (@curr) {
                   7895:                         if (ref($request_domains) eq 'HASH') {
                   7896:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7897:                             if ($otherdom ne '') {
                   7898:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7899:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7900:                                         push(@{$request_domains->{$type}},$otherdom);
                   7901:                                     }
                   7902:                                 } else {
                   7903:                                     push(@{$request_domains->{$type}},$otherdom);
                   7904:                                 }
                   7905:                             }
                   7906:                         }
                   7907:                     }
1.1368    raeburn  7908:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7909:                         $canreq ++;
1.1035    raeburn  7910:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7911:                             $can_request->{$type} = 1;
                   7912:                         }
                   7913:                     }
                   7914:                 }
                   7915:             }
                   7916:         }
                   7917:     }
                   7918:     return $canreq;
                   7919: }
                   7920: 
1.341     www      7921: # ---------------------------------------------- Custom access rule evaluation
                   7922: 
                   7923: sub customaccess {
                   7924:     my ($priv,$uri)=@_;
1.807     albertel 7925:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7926:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7927:     $udom = &LONCAPA::clean_domain($udom);
                   7928:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7929:     my $access=0;
1.800     albertel 7930:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7931: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7932: 	if ($type eq 'user') {
                   7933: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7934: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7935: 		if ($tdom) {
                   7936: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7937: 		}
1.896     albertel 7938: 		if ($tuname) {
                   7939: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7940: 		}
                   7941: 		$access=($effect eq 'allow');
                   7942: 		last;
                   7943: 	    }
                   7944: 	} else {
                   7945: 	    if ($role) {
                   7946: 		if ($role ne $urole) { next; }
                   7947: 	    }
                   7948: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7949: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7950: 		if ($tdom) {
                   7951: 		    if ($tdom ne $udom) { next; }
                   7952: 		}
                   7953: 		if ($tcrs) {
                   7954: 		    if ($tcrs ne $ucrs) { next; }
                   7955: 		}
                   7956: 		if ($tsec) {
                   7957: 		    if ($tsec ne $usec) { next; }
                   7958: 		}
                   7959: 		$access=($effect eq 'allow');
                   7960: 		last;
                   7961: 	    }
                   7962: 	    if ($realm eq '' && $role eq '') {
                   7963: 		$access=($effect eq 'allow');
                   7964: 	    }
1.402     bowersj2 7965: 	}
1.341     www      7966:     }
                   7967:     return $access;
                   7968: }
                   7969: 
1.103     harris41 7970: # ------------------------------------------------- Check for a user privilege
1.12      www      7971: 
                   7972: sub allowed {
1.1281    raeburn  7973:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7974:     my $ver_orguri=$uri;
1.439     www      7975:     $uri=&deversion($uri);
1.152     www      7976:     my $orguri=$uri;
1.52      www      7977:     $uri=&declutter($uri);
1.809     raeburn  7978: 
1.810     raeburn  7979:     if ($priv eq 'evb') {
                   7980: # Evade communication block restrictions for specified role in a course
                   7981:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7982:             return $1;
                   7983:         } else {
                   7984:             return;
                   7985:         }
                   7986:     }
                   7987: 
1.620     albertel 7988:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7989: # Free bre access to adm and meta resources
1.1343    raeburn  7990:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7991: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7992: 	&& ($priv eq 'bre')) {
1.14      www      7993: 	return 'F';
1.159     www      7994:     }
                   7995: 
1.545     banghart 7996: # Free bre access to user's own portfolio contents
1.714     raeburn  7997:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7998:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7999: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8000:         my %setters;
                   8001:         my ($startblock,$endblock) = 
                   8002:             &Apache::loncommon::blockcheck(\%setters,'port');
                   8003:         if ($startblock && $endblock) {
                   8004:             return 'B';
                   8005:         } else {
                   8006:             return 'F';
                   8007:         }
1.545     banghart 8008:     }
                   8009: 
1.762     raeburn  8010: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8011:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8012:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8013:         if (exists($env{'request.course.id'})) {
                   8014:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8015:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8016:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8017:                 my $courseprivid=$env{'request.course.id'};
                   8018:                 $courseprivid=~s/\_/\//;
                   8019:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8020:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8021:                     return $1; 
1.762     raeburn  8022:                 } else {
                   8023:                     if ($env{'request.course.sec'}) {
                   8024:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8025:                     }
                   8026:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8027:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8028:                         return $2;
                   8029:                     }
1.714     raeburn  8030:                 }
                   8031:             }
                   8032:         }
                   8033:     }
                   8034: 
1.159     www      8035: # Free bre to public access
                   8036: 
                   8037:     if ($priv eq 'bre') {
1.1362    raeburn  8038:         my $copyright;
                   8039:         unless ($uri =~ /ext\.tool/) {
                   8040:             $copyright=&metadata($uri,'copyright');
                   8041:         }
1.620     albertel 8042: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8043:            return 'F'; 
                   8044:         }
1.238     www      8045:         if ($copyright eq 'priv') {
                   8046:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8047: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8048: 		return '';
                   8049:             }
                   8050:         }
                   8051:         if ($copyright eq 'domain') {
                   8052:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8053: 	    unless (($env{'user.domain'} eq $1) ||
                   8054:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8055: 		return '';
                   8056:             }
1.262     matthew  8057:         }
1.620     albertel 8058:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8059:             # Library role, so allow browsing of resources in this domain.
                   8060:             return 'F';
1.238     www      8061:         }
1.341     www      8062:         if ($copyright eq 'custom') {
                   8063: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8064:         }
1.14      www      8065:     }
1.264     matthew  8066:     # Domain coordinator is trying to create a course
1.620     albertel 8067:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8068:         # uri is the requested domain in this case.
                   8069:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8070:         # a role of dc for the domain in question.
1.620     albertel 8071:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8072:     }
1.29      www      8073: 
1.52      www      8074:     my $thisallowed='';
                   8075:     my $statecond=0;
                   8076:     my $courseprivid='';
                   8077: 
1.1039    raeburn  8078:     my $ownaccess;
1.1043    raeburn  8079:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8080:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8081:         if ($uri eq '') {
                   8082:             $ownaccess = 1;
                   8083:         } else {
                   8084:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8085:                 my $udom = $env{'user.domain'};
                   8086:                 my $uname = $env{'user.name'};
                   8087:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8088:                     $ownaccess = 1;
1.1040    raeburn  8089:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8090:                     unless ($uri =~ m{\.\./}) {
                   8091:                         $ownaccess = 1;
                   8092:                     }
                   8093:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8094:                     my $now = time;
                   8095:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8096:                         my $adom = $1;
                   8097:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8098:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  8099:                                 my ($start,$end) = split('.',$env{$key});
                   8100:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8101:                                     $ownaccess = 1;
                   8102:                                     last;
                   8103:                                 }
                   8104:                             }
                   8105:                         }
                   8106:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8107:                         my $adom = $1;
                   8108:                         my $aname = $2;
1.1042    raeburn  8109:                         foreach my $role ('ca','aa') { 
                   8110:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8111:                                 my ($start,$end) =
                   8112:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   8113:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8114:                                     $ownaccess = 1;
                   8115:                                     last;
                   8116:                                 }
1.1039    raeburn  8117:                             }
                   8118:                         }
                   8119:                     }
                   8120:                 }
                   8121:             }
                   8122:         }
                   8123:     }
                   8124: 
1.52      www      8125: # Course
                   8126: 
1.620     albertel 8127:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8128:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8129:             $thisallowed.=$1;
                   8130:         }
1.52      www      8131:     }
1.29      www      8132: 
1.52      www      8133: # Domain
                   8134: 
1.620     albertel 8135:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8136:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8137:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8138:             $thisallowed.=$1;
                   8139:         }
1.12      www      8140:     }
1.52      www      8141: 
1.1141    raeburn  8142: # User who is not author or co-author might still be able to edit
                   8143: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8144:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8145:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8146:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8147:             $thisallowed.=$1;
                   8148:         }
                   8149:     }
                   8150: 
1.52      www      8151: # Course: uri itself is a course
1.66      www      8152:     my $courseuri=$uri;
                   8153:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8154:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8155: 
1.620     albertel 8156:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8157:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8158:         if ($priv eq 'mip') {
                   8159:             my $rem = $1;
                   8160:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8161:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8162:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8163:                 if ($cdom ne '') {
1.1410    raeburn  8164:                     my %passwdconf = &get_passwdconf($cdom);
                   8165:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8166:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8167:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8168:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8169:                                 unless (@inststatuses) {
                   8170:                                     @inststatuses = ('default');
                   8171:                                 }
                   8172:                                 foreach my $status (@inststatuses) {
                   8173:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8174:                                         $thisallowed.=$rem;
                   8175:                                     }
                   8176:                                 }
                   8177:                             }
                   8178:                         }
1.1409    raeburn  8179:                     }
                   8180:                 }
                   8181:             }
                   8182:         } else {
                   8183:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8184:                 $thisallowed.=$1;
                   8185:             }
1.1039    raeburn  8186:         }
1.12      www      8187:     }
1.29      www      8188: 
1.665     albertel 8189: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8190: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8191:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8192: 	$thisallowed='';
1.671     raeburn  8193:         my ($match)=&is_on_map($uri);
                   8194:         if ($match) {
                   8195:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8196:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8197:                 my $value = $1;
1.1402    raeburn  8198:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8199:                 if ($deeplinkblock) {
                   8200:                     $thisallowed='D';
                   8201:                 } elsif ($noblockcheck) {
1.1281    raeburn  8202:                     $thisallowed.=$value;
1.1162    raeburn  8203:                 } else {
1.1281    raeburn  8204:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8205:                     if (@blockers > 0) {
                   8206:                         $thisallowed = 'B';
                   8207:                     } else {
                   8208:                         $thisallowed.=$value;
                   8209:                     }
1.1162    raeburn  8210:                 }
1.671     raeburn  8211:             }
                   8212:         } else {
1.705     albertel 8213:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8214:             if ($refuri) {
                   8215:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8216:                     $thisallowed='F';
1.671     raeburn  8217:                 } else {
                   8218:                     $refuri=&declutter($refuri);
                   8219:                     my ($match) = &is_on_map($refuri);
                   8220:                     if ($match) {
1.1402    raeburn  8221:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8222:                         if ($deeplinkblock) {
                   8223:                             $thisallowed='D';
                   8224:                         } elsif ($noblockcheck) {
1.1281    raeburn  8225:                             $thisallowed='F';
1.1162    raeburn  8226:                         } else {
1.1281    raeburn  8227:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8228:                             if (@blockers > 0) {
                   8229:                                 $thisallowed = 'B';
                   8230:                             } else {
                   8231:                                 $thisallowed='F';
                   8232:                             }
1.1162    raeburn  8233:                         }
1.671     raeburn  8234:                     }
1.669     raeburn  8235:                 }
1.671     raeburn  8236:             }
                   8237:         }
1.314     www      8238:     }
1.492     albertel 8239: 
1.766     albertel 8240:     if ($priv eq 'bre'
                   8241: 	&& $thisallowed ne 'F' 
                   8242: 	&& $thisallowed ne '2'
                   8243: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8244: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8245:     }
1.1250    raeburn  8246: 
1.52      www      8247: # Full access at system, domain or course-wide level? Exit.
1.29      www      8248:     if ($thisallowed=~/F/) {
                   8249: 	return 'F';
                   8250:     }
                   8251: 
1.52      www      8252: # If this is generating or modifying users, exit with special codes
1.29      www      8253: 
1.643     www      8254:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8255: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8256: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8257: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8258: 	    unless ($auname) { return $thisallowed; }
                   8259: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8260: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8261: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8262: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8263: 	}
1.52      www      8264: 	return $thisallowed;
                   8265:     }
                   8266: #
1.103     harris41 8267: # Gathered so far: system, domain and course wide privileges
1.52      www      8268: #
                   8269: # Course: See if uri or referer is an individual resource that is part of 
                   8270: # the course
                   8271: 
1.620     albertel 8272:     if ($env{'request.course.id'}) {
1.232     www      8273: 
1.1409    raeburn  8274: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8275: 
                   8276:         if ($priv eq 'mip') {
                   8277:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8278:                 return $thisallowed;
                   8279:             } else {
                   8280:                 return '';
                   8281:             }
                   8282:         }
                   8283: 
1.620     albertel 8284:        $courseprivid=$env{'request.course.id'};
                   8285:        if ($env{'request.course.sec'}) {
                   8286:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8287:        }
                   8288:        $courseprivid=~s/\_/\//;
                   8289:        my $checkreferer=1;
1.232     www      8290:        my ($match,$cond)=&is_on_map($uri);
                   8291:        if ($match) {
                   8292:            $statecond=$cond;
1.620     albertel 8293:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8294:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8295:                my $value = $1;
                   8296:                if ($priv eq 'bre') {
1.1281    raeburn  8297:                    if ($noblockcheck) {
                   8298:                        $thisallowed.=$value;
1.1162    raeburn  8299:                    } else {
1.1281    raeburn  8300:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8301:                        if (@blockers > 0) {
                   8302:                            $thisallowed = 'B';
                   8303:                        } else {
                   8304:                            $thisallowed.=$value;
                   8305:                        }
1.1162    raeburn  8306:                    }
                   8307:                } else {
                   8308:                    $thisallowed.=$value;
                   8309:                }
1.52      www      8310:                $checkreferer=0;
                   8311:            }
1.29      www      8312:        }
1.83      www      8313:        
1.148     www      8314:        if ($checkreferer) {
1.620     albertel 8315: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8316:             unless ($refuri) {
1.800     albertel 8317:                 foreach my $key (keys(%env)) {
                   8318: 		    if ($key=~/^httpref\..*\*/) {
                   8319: 			my $pattern=$key;
1.156     www      8320:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8321:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8322:                         $pattern=~s/\//\\\//g;
1.152     www      8323:                         if ($orguri=~/$pattern/) {
1.800     albertel 8324: 			    $refuri=$env{$key};
1.148     www      8325:                         }
                   8326:                     }
1.191     harris41 8327:                 }
1.148     www      8328:             }
1.232     www      8329: 
1.148     www      8330:          if ($refuri) { 
1.152     www      8331: 	  $refuri=&declutter($refuri);
1.232     www      8332:           my ($match,$cond)=&is_on_map($refuri);
                   8333:             if ($match) {
                   8334:               my $refstatecond=$cond;
1.620     albertel 8335:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8336:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8337:                   my $value = $1;
                   8338:                   if ($priv eq 'bre') {
1.1402    raeburn  8339:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8340:                       if ($deeplinkblock) {
                   8341:                           $thisallowed = 'D';
                   8342:                       } elsif ($noblockcheck) {
1.1281    raeburn  8343:                           $thisallowed.=$value;
1.1162    raeburn  8344:                       } else {
1.1281    raeburn  8345:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8346:                           if (@blockers > 0) {
                   8347:                               $thisallowed = 'B';
                   8348:                           } else {
                   8349:                               $thisallowed.=$value;
                   8350:                           }
1.1162    raeburn  8351:                       }
                   8352:                   } else {
                   8353:                       $thisallowed.=$value;
                   8354:                   }
1.53      www      8355:                   $uri=$refuri;
                   8356:                   $statecond=$refstatecond;
1.52      www      8357:               }
                   8358:           }
1.148     www      8359:         }
1.29      www      8360:        }
1.52      www      8361:    }
1.29      www      8362: 
1.52      www      8363: #
1.103     harris41 8364: # Gathered now: all privileges that could apply, and condition number
1.52      www      8365: # 
                   8366: #
                   8367: # Full or no access?
                   8368: #
1.29      www      8369: 
1.52      www      8370:     if ($thisallowed=~/F/) {
                   8371: 	return 'F';
                   8372:     }
1.29      www      8373: 
1.52      www      8374:     unless ($thisallowed) {
                   8375:         return '';
                   8376:     }
1.29      www      8377: 
1.52      www      8378: # Restrictions exist, deal with them
                   8379: #
                   8380: #   C:according to course preferences
                   8381: #   R:according to resource settings
                   8382: #   L:unless locked
                   8383: #   X:according to user session state
                   8384: #
                   8385: 
                   8386: # Possibly locked functionality, check all courses
1.54      www      8387: # Locks might take effect only after 10 minutes cache expiration for other
                   8388: # courses, and 2 minutes for current course
1.52      www      8389: 
                   8390:     my $envkey;
                   8391:     if ($thisallowed=~/L/) {
1.1000    raeburn  8392:         foreach $envkey (keys(%env)) {
1.54      www      8393:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8394:                my $courseid=$2;
                   8395:                my $roleid=$1.'.'.$2;
1.92      www      8396:                $courseid=~s/^\///;
1.54      www      8397:                my $expiretime=600;
1.620     albertel 8398:                if ($env{'request.role'} eq $roleid) {
1.54      www      8399: 		  $expiretime=120;
                   8400:                }
                   8401: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8402:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8403:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8404: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8405:                }
1.620     albertel 8406:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8407:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8408: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8409:                        &log($env{'user.domain'},$env{'user.name'},
                   8410:                             $env{'user.home'},
1.57      www      8411:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8412:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8413:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8414: 		       return '';
                   8415:                    }
                   8416:                }
1.620     albertel 8417:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8418:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8419: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8420:                        &log($env{'user.domain'},$env{'user.name'},
                   8421:                             $env{'user.home'},
1.57      www      8422:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8423:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8424:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8425: 		       return '';
                   8426:                    }
                   8427:                }
                   8428: 	   }
1.29      www      8429:        }
1.52      www      8430:     }
                   8431:    
                   8432: #
                   8433: # Rest of the restrictions depend on selected course
                   8434: #
                   8435: 
1.620     albertel 8436:     unless ($env{'request.course.id'}) {
1.766     albertel 8437: 	if ($thisallowed eq 'A') {
                   8438: 	    return 'A';
1.814     raeburn  8439:         } elsif ($thisallowed eq 'B') {
                   8440:             return 'B';
1.766     albertel 8441: 	} else {
                   8442: 	    return '1';
                   8443: 	}
1.52      www      8444:     }
1.29      www      8445: 
1.52      www      8446: #
                   8447: # Now user is definitely in a course
                   8448: #
1.53      www      8449: 
                   8450: 
                   8451: # Course preferences
                   8452: 
                   8453:    if ($thisallowed=~/C/) {
1.620     albertel 8454:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8455:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8456:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8457: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8458: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8459: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8460: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8461: 			$env{'request.course.id'});
                   8462: 	   }
1.237     www      8463:            return '';
                   8464:        }
                   8465: 
1.620     albertel 8466:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8467: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8468: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8469: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8470: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8471: 			$env{'request.course.id'});
                   8472: 	   }
1.54      www      8473:            return '';
                   8474:        }
1.53      www      8475:    }
                   8476: 
                   8477: # Resource preferences
                   8478: 
                   8479:    if ($thisallowed=~/R/) {
1.620     albertel 8480:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8481:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8482: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8483: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8484: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8485: 	   }
                   8486: 	   return '';
1.54      www      8487:        }
1.53      www      8488:    }
1.30      www      8489: 
1.246     www      8490: # Restricted by state or randomout?
1.30      www      8491: 
1.52      www      8492:    if ($thisallowed=~/X/) {
1.620     albertel 8493:       if ($env{'acc.randomout'}) {
1.579     albertel 8494: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8495:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8496:             return ''; 
                   8497:          }
1.247     www      8498:       }
                   8499:       if (&condval($statecond)) {
1.52      www      8500: 	 return '2';
                   8501:       } else {
                   8502:          return '';
                   8503:       }
                   8504:    }
1.30      www      8505: 
1.766     albertel 8506:     if ($thisallowed eq 'A') {
                   8507: 	return 'A';
1.814     raeburn  8508:     } elsif ($thisallowed eq 'B') {
                   8509:         return 'B';
1.1402    raeburn  8510:     } elsif ($thisallowed eq 'D') {
                   8511:         return 'D';
1.766     albertel 8512:     }
1.52      www      8513:    return 'F';
1.232     www      8514: }
1.1162    raeburn  8515: 
1.1192    raeburn  8516: # ------------------------------------------- Check construction space access
                   8517: 
                   8518: sub constructaccess {
                   8519:     my ($url,$setpriv)=@_;
                   8520: 
                   8521: # We do not allow editing of previous versions of files
                   8522:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8523: 
                   8524: # Get username and domain from URL
                   8525:     my ($ownername,$ownerdomain,$ownerhome);
                   8526: 
                   8527:     ($ownerdomain,$ownername) =
1.1325    raeburn  8528:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8529: 
                   8530: # The URL does not really point to any authorspace, forget it
                   8531:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8532: 
                   8533: # Now we need to see if the user has access to the authorspace of
                   8534: # $ownername at $ownerdomain
                   8535: 
                   8536:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8537: # Real author for this?
                   8538:        $ownerhome = $env{'user.home'};
                   8539:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8540:           return ($ownername,$ownerdomain,$ownerhome);
                   8541:        }
                   8542:     } else {
                   8543: # Co-author for this?
                   8544:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8545:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8546:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8547:             return ($ownername,$ownerdomain,$ownerhome);
                   8548:         }
1.1312    raeburn  8549:         if ($env{'request.course.id'}) {
                   8550:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8551:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8552:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8553:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8554:                     return ($ownername,$ownerdomain,$ownerhome);
                   8555:                 }
                   8556:             }
                   8557:         }
1.1192    raeburn  8558:     }
                   8559: 
                   8560: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8561: # we might as well leave
                   8562:    unless ($setpriv) { return ''; }
                   8563: 
                   8564: # Backdoor access?
                   8565:     my $allowed=&allowed('eco',$ownerdomain);
                   8566: # Nope
                   8567:     unless ($allowed) { return ''; }
                   8568: # Looks like we may have access, but could be locked by the owner of the construction space
                   8569:     if ($allowed eq 'U') {
                   8570:         my %blocked=&get('environment',['domcoord.author'],
                   8571:                          $ownerdomain,$ownername);
                   8572: # Is blocked by owner
                   8573:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8574:     }
                   8575:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8576: # Grant temporary access
                   8577:         my $then=$env{'user.login.time'};
1.1209    raeburn  8578:         my $update=$env{'user.update.time'};
1.1192    raeburn  8579:         if (!$update) { $update = $then; }
                   8580:         my $refresh=$env{'user.refresh.time'};
                   8581:         if (!$refresh) { $refresh = $update; }
                   8582:         my $now = time;
                   8583:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8584:                            $now,'ca','constructaccess');
                   8585:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8586:         return($ownername,$ownerdomain,$ownerhome);
                   8587:     }
                   8588: # No business here
                   8589:     return '';
                   8590: }
                   8591: 
1.1282    raeburn  8592: # ----------------------------------------------------------- Content Blocking
                   8593: 
                   8594: {
                   8595: # Caches for faster Course Contents display where content blocking
                   8596: # is in operation (i.e., interval param set) for timed quiz.
                   8597: #
                   8598: # User for whom data are being temporarily cached.
                   8599: my $cacheduser='';
                   8600: # Cached blockers for this user (a hash of blocking items). 
                   8601: my %cachedblockers=();
                   8602: # When the data were last cached.
                   8603: my $cachedlast='';
                   8604: 
                   8605: sub load_all_blockers {
                   8606:     my ($uname,$udom,$blocks)=@_;
                   8607:     if (($uname ne '') && ($udom ne '')) { 
                   8608:         if (($cacheduser eq $uname.':'.$udom) &&
                   8609:             (abs($cachedlast-time)<5)) {
                   8610:             return;
                   8611:         }
                   8612:     }
                   8613:     $cachedlast=time;
                   8614:     $cacheduser=$uname.':'.$udom;
                   8615:     %cachedblockers = &get_commblock_resources($blocks);
                   8616: }
                   8617: 
1.1162    raeburn  8618: sub get_comm_blocks {
                   8619:     my ($cdom,$cnum) = @_;
                   8620:     if ($cdom eq '' || $cnum eq '') {
                   8621:         return unless ($env{'request.course.id'});
                   8622:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8623:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8624:     }
                   8625:     my %commblocks;
                   8626:     my $hashid=$cdom.'_'.$cnum;
                   8627:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8628:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8629:         %commblocks = %{$blocksref};
                   8630:     } else {
                   8631:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8632:         my $cachetime = 600;
                   8633:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8634:     }
                   8635:     return %commblocks;
                   8636: }
                   8637: 
1.1282    raeburn  8638: sub get_commblock_resources {
                   8639:     my ($blocks) = @_;
                   8640:     my %blockers = ();
                   8641:     return %blockers unless ($env{'request.course.id'});
                   8642:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8643:     my %commblocks;
                   8644:     if (ref($blocks) eq 'HASH') {
                   8645:         %commblocks = %{$blocks};
                   8646:     } else {
                   8647:         %commblocks = &get_comm_blocks();
                   8648:     }
1.1282    raeburn  8649:     return %blockers unless (keys(%commblocks) > 0); 
                   8650:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8651:     return %blockers unless (ref($navmap));
1.1162    raeburn  8652:     my $now = time;
                   8653:     foreach my $block (keys(%commblocks)) {
                   8654:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8655:             my ($start,$end) = ($1,$2);
                   8656:             if ($start <= $now && $end >= $now) {
                   8657:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8658:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8659:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8660:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8661:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8662:                             }
                   8663:                         }
                   8664:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8665:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8666:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8667:                             }
                   8668:                         }
                   8669:                     }
                   8670:                 }
                   8671:             }
                   8672:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8673:             my $item = $1;
1.1163    raeburn  8674:             my @to_test;
1.1162    raeburn  8675:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8676:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8677:                     my @interval;
                   8678:                     my $type = 'map';
                   8679:                     if ($item eq 'course') {
                   8680:                         $type = 'course';
                   8681:                         @interval=&EXT("resource.0.interval");
                   8682:                     } else {
                   8683:                         if ($item =~ /___\d+___/) {
                   8684:                             $type = 'resource';
                   8685:                             @interval=&EXT("resource.0.interval",$item);
                   8686:                             if (ref($navmap)) {                        
                   8687:                                 my $res = $navmap->getBySymb($item); 
                   8688:                                 push(@to_test,$res);
                   8689:                             }
1.1162    raeburn  8690:                         } else {
1.1282    raeburn  8691:                             my $mapsymb = &symbread($item,1);
                   8692:                             if ($mapsymb) {
                   8693:                                 if (ref($navmap)) {
                   8694:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8695:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8696:                                     foreach my $res (@to_test) {
                   8697:                                         my $symb = $res->symb();
                   8698:                                         next if ($symb eq $mapsymb);
                   8699:                                         if ($symb ne '') {
                   8700:                                             @interval=&EXT("resource.0.interval",$symb);
                   8701:                                             if ($interval[1] eq 'map') {
                   8702:                                                 last;
1.1162    raeburn  8703:                                             }
                   8704:                                         }
                   8705:                                     }
                   8706:                                 }
                   8707:                             }
                   8708:                         }
1.1282    raeburn  8709:                     }
1.1310    raeburn  8710:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8711:                         my $timelimit = $1; 
1.1282    raeburn  8712:                         my $first_access;
                   8713:                         if ($type eq 'resource') {
                   8714:                             $first_access=&get_first_access($interval[1],$item);
                   8715:                         } elsif ($type eq 'map') {
                   8716:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8717:                         } else {
                   8718:                             $first_access=&get_first_access($interval[1]);
                   8719:                         }
                   8720:                         if ($first_access) {
1.1292    raeburn  8721:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8722:                             if ($timesup > $now) {
                   8723:                                 my $activeblock;
                   8724:                                 foreach my $res (@to_test) {
1.1283    raeburn  8725:                                     if ($res->answerable()) {
1.1282    raeburn  8726:                                         $activeblock = 1;
                   8727:                                         last;
                   8728:                                     }
                   8729:                                 }
                   8730:                                 if ($activeblock) {
                   8731:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8732:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8733:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8734:                                          }
                   8735:                                     }
                   8736:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8737:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8738:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8739:                                         }
1.1162    raeburn  8740:                                     }
                   8741:                                 }
                   8742:                             }
                   8743:                         }
                   8744:                     }
                   8745:                 }
                   8746:             }
                   8747:         }
                   8748:     }
1.1282    raeburn  8749:     return %blockers;
1.1162    raeburn  8750: }
                   8751: 
1.1282    raeburn  8752: sub has_comm_blocking {
                   8753:     my ($priv,$symb,$uri,$blocks) = @_;
                   8754:     my @blockers;
                   8755:     return unless ($env{'request.course.id'});
                   8756:     return unless ($priv eq 'bre');
                   8757:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8758:     return if ($env{'request.state'} eq 'construct');
                   8759:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8760:     return unless (keys(%cachedblockers) > 0);
                   8761:     my (%possibles,@symbs);
                   8762:     if (!$symb) {
                   8763:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8764:     }
1.1282    raeburn  8765:     if ($symb) {
                   8766:         @symbs = ($symb);
                   8767:     } elsif (keys(%possibles)) { 
                   8768:         @symbs = keys(%possibles);
                   8769:     }
                   8770:     my $noblock;
                   8771:     foreach my $symb (@symbs) {
                   8772:         last if ($noblock);
                   8773:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8774:         foreach my $block (keys(%cachedblockers)) {
                   8775:             if ($block =~ /^firstaccess____(.+)$/) {
                   8776:                 my $item = $1;
                   8777:                 if (($item eq $map) || ($item eq $symb)) {
                   8778:                     $noblock = 1;
                   8779:                     last;
                   8780:                 }
                   8781:             }
                   8782:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8783:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8784:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8785:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8786:                             push(@blockers,$block);
                   8787:                         }
                   8788:                     }
                   8789:                 }
1.1162    raeburn  8790:             }
1.1282    raeburn  8791:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8792:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8793:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8794:                         push(@blockers,$block);
                   8795:                     }
                   8796:                 }
1.1162    raeburn  8797:             }
                   8798:         }
                   8799:     }
1.1282    raeburn  8800:     return if ($noblock);
                   8801:     return @blockers;
                   8802: }
1.1162    raeburn  8803: }
                   8804: 
1.1402    raeburn  8805: sub deeplink_check {
                   8806:     my ($priv,$symb,$uri) = @_;
                   8807:     return unless ($env{'request.course.id'});
                   8808:     return unless ($priv eq 'bre');
                   8809:     return if ($env{'request.state'} eq 'construct');
                   8810:     return if ($env{'request.role.adv'});
                   8811:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8812:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8813:     my (%possibles,@symbs);
                   8814:     if (!$symb) {
                   8815:         $symb = &symbread($uri,1,1,1,\%possibles);
                   8816:     }
                   8817:     if ($symb) {
                   8818:         @symbs = ($symb);
                   8819:     } elsif (keys(%possibles)) {
                   8820:         @symbs = keys(%possibles);
                   8821:     }
                   8822: 
                   8823:     my ($login,$switchrole,$allow);
                   8824:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   8825:         my $key = $1;
                   8826:         my $tinyurl;
                   8827:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   8828:         if (defined($cached)) {
                   8829:              $tinyurl = $result;
                   8830:         } else {
                   8831:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   8832:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   8833:              if ($currtiny{$key} ne '') {
                   8834:                  $tinyurl = $currtiny{$key};
                   8835:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   8836:              }
                   8837:         }
                   8838:         if ($tinyurl ne '') {
                   8839:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
                   8840:             if ($cnumreq eq $cnum) {
                   8841:                 $login = $posslogin;
                   8842:             } else {
                   8843:                 $switchrole = 1;
                   8844:             }
                   8845:         }
                   8846:     }
                   8847:     foreach my $symb (@symbs) {
                   8848:         last if ($allow);
                   8849:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8850:         if ($deeplink eq '') {
                   8851:             $allow = 1;
                   8852:         } else {
                   8853:             my ($listed,$scope,$access) = split(/,/,$deeplink);
                   8854:             if ($access eq 'any') {
                   8855:                 $allow = 1;
                   8856:             } elsif ($login) {
                   8857:                 if ($access eq 'only') {
                   8858:                     if ($scope eq 'res') {
                   8859:                         if ($symb eq $login) {
                   8860:                             $allow = 1;
                   8861:                         }
                   8862:                     } elsif ($scope eq 'map') {
                   8863: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
                   8864:                     } elsif ($scope eq 'rec') {
                   8865: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
                   8866:                     }
                   8867:                 } else {
                   8868:                     my ($acctype,$item) = split(/:/,$access);
                   8869:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
                   8870:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
                   8871:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8872:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
                   8873:                                 $allow = 1;
                   8874:                             }
                   8875:                         }
                   8876:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   8877:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   8878:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8879:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
                   8880:                                 $allow = 1;
                   8881:                             }
                   8882:                         }
                   8883:                     }
                   8884:                 }
                   8885:             }
                   8886:         }
                   8887:     }
                   8888:     return if ($allow);
                   8889:     return 1;
                   8890: }
                   8891: 
1.1282    raeburn  8892: # -------------------------------- Deversion and split uri into path an filename   
                   8893: 
1.1133    foxr     8894: #
1.1282    raeburn  8895: #   Removes the version from a URI and
1.1133    foxr     8896: #   splits it in to its filename and path to the filename.
                   8897: #   Seems like File::Basename could have done this more clearly.
                   8898: #   Parameters:
                   8899: #      $uri   - input URI
                   8900: #   Returns:
                   8901: #     Two element list consisting of 
                   8902: #     $pathname  - the URI up to and excluding the trailing /
                   8903: #     $filename  - The part of the URI following the last /
                   8904: #  NOTE:
                   8905: #    Another realization of this is simply:
                   8906: #    use File::Basename;
                   8907: #    ...
                   8908: #    $uri = shift;
                   8909: #    $filename = basename($uri);
                   8910: #    $path     = dirname($uri);
                   8911: #    return ($filename, $path);
                   8912: #
                   8913: #     The implementation below is probably faster however.
                   8914: #
1.710     albertel 8915: sub split_uri_for_cond {
                   8916:     my $uri=&deversion(&declutter(shift));
                   8917:     my @uriparts=split(/\//,$uri);
                   8918:     my $filename=pop(@uriparts);
                   8919:     my $pathname=join('/',@uriparts);
                   8920:     return ($pathname,$filename);
                   8921: }
1.232     www      8922: # --------------------------------------------------- Is a resource on the map?
                   8923: 
                   8924: sub is_on_map {
1.710     albertel 8925:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8926:     #Trying to find the conditional for the file
1.620     albertel 8927:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8928: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8929:     if ($match) {
1.289     bowersj2 8930: 	return (1,$1);
                   8931:     } else {
1.434     www      8932: 	return (0,0);
1.289     bowersj2 8933:     }
1.12      www      8934: }
                   8935: 
1.427     www      8936: # --------------------------------------------------------- Get symb from alias
                   8937: 
                   8938: sub get_symb_from_alias {
                   8939:     my $symb=shift;
                   8940:     my ($map,$resid,$url)=&decode_symb($symb);
                   8941: # Already is a symb
                   8942:     if ($url) { return $symb; }
                   8943: # Must be an alias
                   8944:     my $aliassymb='';
                   8945:     my %bighash;
1.620     albertel 8946:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8947:                             &GDBM_READER(),0640)) {
                   8948:         my $rid=$bighash{'mapalias_'.$symb};
                   8949: 	if ($rid) {
                   8950: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8951: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8952: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8953: 	}
                   8954:         untie %bighash;
                   8955:     }
                   8956:     return $aliassymb;
                   8957: }
                   8958: 
1.12      www      8959: # ----------------------------------------------------------------- Define Role
                   8960: 
                   8961: sub definerole {
                   8962:   if (allowed('mcr','/')) {
1.1326    raeburn  8963:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8964:     foreach my $role (split(':',$sysrole)) {
                   8965: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8966:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8967:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8968: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8969:                return "refused:s:$crole&$cqual"; 
                   8970:             }
                   8971:         }
1.191     harris41 8972:     }
1.800     albertel 8973:     foreach my $role (split(':',$domrole)) {
                   8974: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8975:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8976:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8977: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8978:                return "refused:d:$crole&$cqual"; 
                   8979:             }
                   8980:         }
1.191     harris41 8981:     }
1.800     albertel 8982:     foreach my $role (split(':',$courole)) {
                   8983: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8984:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8985:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8986: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8987:                return "refused:c:$crole&$cqual"; 
                   8988:             }
                   8989:         }
1.191     harris41 8990:     }
1.1326    raeburn  8991:     my $uhome;
                   8992:     if (($uname ne '') && ($udom ne '')) {
                   8993:         $uhome = &homeserver($uname,$udom);
                   8994:         return $uhome if ($uhome eq 'no_host');
                   8995:     } else {
                   8996:         $uname = $env{'user.name'};
                   8997:         $udom = $env{'user.domain'};
                   8998:         $uhome = $env{'user.home'};
                   8999:     }
1.620     albertel 9000:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9001:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9002:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9003:     return reply($command,$uhome);
1.12      www      9004:   } else {
                   9005:     return 'refused';
                   9006:   }
1.105     harris41 9007: }
                   9008: 
                   9009: # ---------------- Make a metadata query against the network of library servers
                   9010: 
                   9011: sub metadata_query {
1.1237    raeburn  9012:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9013:     my %rhash;
1.845     albertel 9014:     my %libserv = &all_library();
1.244     matthew  9015:     my @server_list = (defined($server_array) ? @$server_array
                   9016:                                               : keys(%libserv) );
                   9017:     for my $server (@server_list) {
1.1237    raeburn  9018:         my $domains = ''; 
                   9019:         if (ref($domains_hash) eq 'HASH') {
                   9020:             $domains = $domains_hash->{$server}; 
                   9021:         }
1.118     harris41 9022: 	unless ($custom or $customshow) {
1.1237    raeburn  9023: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9024: 	    $rhash{$server}=$reply;
                   9025: 	}
                   9026: 	else {
                   9027: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9028: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9029: 			     $server);
                   9030: 	    $rhash{$server}=$reply;
                   9031: 	}
1.112     harris41 9032:     }
1.118     harris41 9033:     return \%rhash;
1.240     www      9034: }
                   9035: 
                   9036: # ----------------------------------------- Send log queries and wait for reply
                   9037: 
                   9038: sub log_query {
                   9039:     my ($uname,$udom,$query,%filters)=@_;
                   9040:     my $uhome=&homeserver($uname,$udom);
                   9041:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9042:     my $uhost=&hostname($uhome);
1.800     albertel 9043:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9044:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9045:                        $uhome);
1.479     albertel 9046:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9047:     return get_query_reply($queryid);
                   9048: }
                   9049: 
1.818     raeburn  9050: # -------------------------- Update MySQL table for portfolio file
                   9051: 
                   9052: sub update_portfolio_table {
1.821     raeburn  9053:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9054:     if ($group ne '') {
                   9055:         $file_name =~s /^\Q$group\E//;
                   9056:     }
1.818     raeburn  9057:     my $homeserver = &homeserver($uname,$udom);
                   9058:     my $queryid=
1.821     raeburn  9059:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9060:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9061:     my $reply = &get_query_reply($queryid);
                   9062:     return $reply;
                   9063: }
                   9064: 
1.899     raeburn  9065: # -------------------------- Update MySQL allusers table
                   9066: 
                   9067: sub update_allusers_table {
                   9068:     my ($uname,$udom,$names) = @_;
                   9069:     my $homeserver = &homeserver($uname,$udom);
                   9070:     my $queryid=
                   9071:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9072:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9073:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9074:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9075:                'generation='.&escape($names->{'generation'}).'%%'.
                   9076:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9077:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9078:     return;
1.899     raeburn  9079: }
                   9080: 
1.508     raeburn  9081: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9082: 
                   9083: sub fetch_enrollment_query {
1.511     raeburn  9084:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9085:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9086:     my $maxtries = 1;
1.508     raeburn  9087:     if ($context eq 'automated') {
                   9088:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9089:         $sleep = 2;
                   9090:         $loopmax = 100;
1.547     raeburn  9091:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9092:     } else {
                   9093:         $homeserver = &homeserver($cnum,$dom);
                   9094:     }
1.838     albertel 9095:     my $host=&hostname($homeserver);
1.506     raeburn  9096:     my $cmd = '';
1.1000    raeburn  9097:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9098:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9099:     }
                   9100:     $cmd =~ s/%%$//;
                   9101:     $cmd = &escape($cmd);
                   9102:     my $query = 'fetchenrollment';
1.620     albertel 9103:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9104:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9105:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9106:         return 'error: '.$queryid;
                   9107:     }
1.1317    raeburn  9108:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9109:     my $tries = 1;
                   9110:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9111:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9112:         $tries ++;
                   9113:     }
1.526     raeburn  9114:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9115:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9116:     } else {
1.901     albertel 9117:         my @responses = split(/:/,$reply);
1.1322    raeburn  9118:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9119:             foreach my $line (@responses) {
                   9120:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9121:                 $$replyref{$key} = $value;
                   9122:             }
                   9123:         } else {
1.1117    foxr     9124:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9125:             foreach my $line (@responses) {
                   9126:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9127:                 $$replyref{$key} = $value;
                   9128:                 if ($value > 0) {
1.800     albertel 9129:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9130:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9131:                         my $destname = $pathname.'/'.$filename;
                   9132:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9133:                         if ($xml_classlist =~ /^error/) {
                   9134:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9135:                         } else {
1.1359    raeburn  9136:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9137:                                 print FILE &unescape($xml_classlist);
                   9138:                                 close(FILE);
1.526     raeburn  9139:                             } else {
                   9140:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9141:                             }
                   9142:                         }
                   9143:                     }
                   9144:                 }
                   9145:             }
                   9146:         }
                   9147:         return 'ok';
                   9148:     }
                   9149:     return 'error';
                   9150: }
                   9151: 
1.242     www      9152: sub get_query_reply {
1.1317    raeburn  9153:     my ($queryid,$sleep,$loopmax) = @_;;
                   9154:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9155:         $sleep = 0.2;
                   9156:     }
                   9157:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9158:         $loopmax = 100;
                   9159:     }
1.1117    foxr     9160:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9161:     my $reply='';
1.1317    raeburn  9162:     for (1..$loopmax) {
                   9163: 	sleep($sleep);
1.240     www      9164:         if (-e $replyfile.'.end') {
1.1359    raeburn  9165: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9166: 		$reply = join('',<$fh>);
                   9167: 		close($fh);
1.240     www      9168: 	   } else { return 'error: reply_file_error'; }
1.242     www      9169:            return &unescape($reply);
                   9170: 	}
1.240     www      9171:     }
1.242     www      9172:     return 'timeout:'.$queryid;
1.240     www      9173: }
                   9174: 
                   9175: sub courselog_query {
1.241     www      9176: #
                   9177: # possible filters:
                   9178: # url: url or symb
                   9179: # username
                   9180: # domain
                   9181: # action: view, submit, grade
                   9182: # start: timestamp
                   9183: # end: timestamp
                   9184: #
1.240     www      9185:     my (%filters)=@_;
1.620     albertel 9186:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9187:     if ($filters{'url'}) {
                   9188: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9189:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9190:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9191:     }
1.620     albertel 9192:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9193:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9194:     return &log_query($cname,$cdom,'courselog',%filters);
                   9195: }
                   9196: 
                   9197: sub userlog_query {
1.858     raeburn  9198: #
                   9199: # possible filters:
                   9200: # action: log check role
                   9201: # start: timestamp
                   9202: # end: timestamp
                   9203: #
1.240     www      9204:     my ($uname,$udom,%filters)=@_;
                   9205:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9206: }
                   9207: 
1.506     raeburn  9208: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9209: 
                   9210: sub auto_run {
1.508     raeburn  9211:     my ($cnum,$cdom) = @_;
1.876     raeburn  9212:     my $response = 0;
                   9213:     my $settings;
                   9214:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9215:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9216:         $settings = $domconfig{'autoenroll'};
                   9217:         if ($settings->{'run'} eq '1') {
                   9218:             $response = 1;
                   9219:         }
                   9220:     } else {
1.934     raeburn  9221:         my $homeserver;
                   9222:         if (&is_course($cdom,$cnum)) {
                   9223:             $homeserver = &homeserver($cnum,$cdom);
                   9224:         } else {
                   9225:             $homeserver = &domain($cdom,'primary');
                   9226:         }
                   9227:         if ($homeserver ne 'no_host') {
                   9228:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9229:         }
1.876     raeburn  9230:     }
1.506     raeburn  9231:     return $response;
                   9232: }
1.776     albertel 9233: 
1.506     raeburn  9234: sub auto_get_sections {
1.508     raeburn  9235:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9236:     my $homeserver;
                   9237:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9238:         $homeserver = &homeserver($cnum,$cdom);
                   9239:     }
                   9240:     if (!defined($homeserver)) { 
                   9241:         if ($cdom =~ /^$match_domain$/) {
                   9242:             $homeserver = &domain($cdom,'primary');
                   9243:         }
                   9244:     }
                   9245:     my @secs;
                   9246:     if (defined($homeserver)) {
                   9247:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9248:         unless ($response eq 'refused') {
                   9249:             @secs = split(/:/,$response);
                   9250:         }
1.506     raeburn  9251:     }
                   9252:     return @secs;
                   9253: }
1.776     albertel 9254: 
1.506     raeburn  9255: sub auto_new_course {
1.1099    raeburn  9256:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9257:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9258:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9259:     return $response;
                   9260: }
1.776     albertel 9261: 
1.506     raeburn  9262: sub auto_validate_courseID {
1.508     raeburn  9263:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9264:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9265:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9266:     return $response;
                   9267: }
1.776     albertel 9268: 
1.1007    raeburn  9269: sub auto_validate_instcode {
1.1020    raeburn  9270:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9271:     my ($homeserver,$response);
                   9272:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9273:         $homeserver = &homeserver($cnum,$cdom);
                   9274:     }
                   9275:     if (!defined($homeserver)) {
                   9276:         if ($cdom =~ /^$match_domain$/) {
                   9277:             $homeserver = &domain($cdom,'primary');
                   9278:         }
                   9279:     }
1.1065    raeburn  9280:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9281:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9282:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9283:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9284: }
                   9285: 
1.506     raeburn  9286: sub auto_create_password {
1.873     raeburn  9287:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9288:     my ($homeserver,$response);
1.506     raeburn  9289:     my $create_passwd = 0;
                   9290:     my $authchk = '';
1.873     raeburn  9291:     if ($udom =~ /^$match_domain$/) {
                   9292:         $homeserver = &domain($udom,'primary');
                   9293:     }
                   9294:     if ($homeserver eq '') {
                   9295:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9296:             $homeserver = &homeserver($cnum,$cdom);
                   9297:         }
                   9298:     }
                   9299:     if ($homeserver eq '') {
                   9300:         $authchk = 'nodomain';
1.506     raeburn  9301:     } else {
1.873     raeburn  9302:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9303:         if ($response eq 'refused') {
                   9304:             $authchk = 'refused';
                   9305:         } else {
1.901     albertel 9306:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9307:         }
1.506     raeburn  9308:     }
                   9309:     return ($authparam,$create_passwd,$authchk);
                   9310: }
                   9311: 
1.706     raeburn  9312: sub auto_photo_permission {
                   9313:     my ($cnum,$cdom,$students) = @_;
                   9314:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9315:     my ($outcome,$perm_reqd,$conditions) = 
                   9316: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9317:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9318: 	return (undef,undef);
                   9319:     }
1.706     raeburn  9320:     return ($outcome,$perm_reqd,$conditions);
                   9321: }
                   9322: 
                   9323: sub auto_checkphotos {
                   9324:     my ($uname,$udom,$pid) = @_;
                   9325:     my $homeserver = &homeserver($uname,$udom);
                   9326:     my ($result,$resulttype);
                   9327:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9328: 				   &escape($uname).':'.&escape($pid),
                   9329: 				   $homeserver));
1.709     albertel 9330:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9331: 	return (undef,undef);
                   9332:     }
1.706     raeburn  9333:     if ($outcome) {
                   9334:         ($result,$resulttype) = split(/:/,$outcome);
                   9335:     } 
                   9336:     return ($result,$resulttype);
                   9337: }
                   9338: 
                   9339: sub auto_photochoice {
                   9340:     my ($cnum,$cdom) = @_;
                   9341:     my $homeserver = &homeserver($cnum,$cdom);
                   9342:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9343: 						       &escape($cdom),
                   9344: 						       $homeserver)));
1.709     albertel 9345:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9346: 	return (undef,undef);
                   9347:     }
1.706     raeburn  9348:     return ($update,$comment);
                   9349: }
                   9350: 
                   9351: sub auto_photoupdate {
                   9352:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9353:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9354:     my $host=&hostname($homeserver);
1.706     raeburn  9355:     my $cmd = '';
                   9356:     my $maxtries = 1;
1.800     albertel 9357:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9358:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9359:     }
                   9360:     $cmd =~ s/%%$//;
                   9361:     $cmd = &escape($cmd);
                   9362:     my $query = 'institutionalphotos';
                   9363:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9364:     unless ($queryid=~/^\Q$host\E\_/) {
                   9365:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9366:         return 'error: '.$queryid;
                   9367:     }
                   9368:     my $reply = &get_query_reply($queryid);
                   9369:     my $tries = 1;
                   9370:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9371:         $reply = &get_query_reply($queryid);
                   9372:         $tries ++;
                   9373:     }
                   9374:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9375:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9376:     } else {
                   9377:         my @responses = split(/:/,$reply);
                   9378:         my $outcome = shift(@responses); 
                   9379:         foreach my $item (@responses) {
                   9380:             my ($key,$value) = split(/=/,$item);
                   9381:             $$photo{$key} = $value;
                   9382:         }
                   9383:         return $outcome;
                   9384:     }
                   9385:     return 'error';
                   9386: }
                   9387: 
1.521     raeburn  9388: sub auto_instcode_format {
1.793     albertel 9389:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9390: 	$cat_order) = @_;
1.521     raeburn  9391:     my $courses = '';
1.772     raeburn  9392:     my @homeservers;
1.521     raeburn  9393:     if ($caller eq 'global') {
1.841     albertel 9394: 	my %servers = &get_servers($codedom,'library');
                   9395: 	foreach my $tryserver (keys(%servers)) {
                   9396: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9397: 		push(@homeservers,$tryserver);
                   9398: 	    }
1.584     raeburn  9399:         }
1.1022    raeburn  9400:     } elsif ($caller eq 'requests') {
                   9401:         if ($codedom =~ /^$match_domain$/) {
                   9402:             my $chome = &domain($codedom,'primary');
                   9403:             unless ($chome eq 'no_host') {
                   9404:                 push(@homeservers,$chome);
                   9405:             }
                   9406:         }
1.521     raeburn  9407:     } else {
1.772     raeburn  9408:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9409:     }
1.793     albertel 9410:     foreach my $code (keys(%{$instcodes})) {
                   9411:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9412:     }
                   9413:     chop($courses);
1.772     raeburn  9414:     my $ok_response = 0;
                   9415:     my $response;
                   9416:     while (@homeservers > 0 && $ok_response == 0) {
                   9417:         my $server = shift(@homeservers); 
                   9418:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9419:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9420:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9421: 		split(/:/,$response);
1.772     raeburn  9422:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9423:             push(@{$codetitles},&str2array($codetitles_str));
                   9424:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9425:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9426:             $ok_response = 1;
                   9427:         }
                   9428:     }
                   9429:     if ($ok_response) {
1.521     raeburn  9430:         return 'ok';
1.772     raeburn  9431:     } else {
                   9432:         return $response;
1.521     raeburn  9433:     }
                   9434: }
                   9435: 
1.792     raeburn  9436: sub auto_instcode_defaults {
                   9437:     my ($domain,$returnhash,$code_order) = @_;
                   9438:     my @homeservers;
1.841     albertel 9439: 
                   9440:     my %servers = &get_servers($domain,'library');
                   9441:     foreach my $tryserver (keys(%servers)) {
                   9442: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9443: 	    push(@homeservers,$tryserver);
                   9444: 	}
1.792     raeburn  9445:     }
1.841     albertel 9446: 
1.792     raeburn  9447:     my $response;
1.841     albertel 9448:     foreach my $server (@homeservers) {
1.792     raeburn  9449:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9450:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9451: 	
                   9452: 	foreach my $pair (split(/\&/,$response)) {
                   9453: 	    my ($name,$value)=split(/\=/,$pair);
                   9454: 	    if ($name eq 'code_order') {
                   9455: 		@{$code_order} = split(/\&/,&unescape($value));
                   9456: 	    } else {
                   9457: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9458: 	    }
                   9459: 	}
                   9460: 	return 'ok';
1.792     raeburn  9461:     }
1.841     albertel 9462: 
                   9463:     return $response;
1.1003    raeburn  9464: }
                   9465: 
                   9466: sub auto_possible_instcodes {
1.1007    raeburn  9467:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9468:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9469:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9470:         return;
                   9471:     }
1.1003    raeburn  9472:     my (@homeservers,$uhome);
                   9473:     if (defined(&domain($domain,'primary'))) {
                   9474:         $uhome=&domain($domain,'primary');
                   9475:         push(@homeservers,&domain($domain,'primary'));
                   9476:     } else {
                   9477:         my %servers = &get_servers($domain,'library');
                   9478:         foreach my $tryserver (keys(%servers)) {
                   9479:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9480:                 push(@homeservers,$tryserver);
                   9481:             }
                   9482:         }
                   9483:     }
                   9484:     my $response;
                   9485:     foreach my $server (@homeservers) {
                   9486:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9487:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9488:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9489:             split(':',$response);
                   9490:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9491:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9492:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9493:             my ($name,$value)=split('=',$item);
                   9494:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9495:         }
                   9496:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9497:             my ($name,$value)=split('=',$item);
                   9498:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9499:         }
                   9500:         return 'ok';
                   9501:     }
                   9502:     return $response;
                   9503: }
1.792     raeburn  9504: 
1.1010    raeburn  9505: sub auto_courserequest_checks {
                   9506:     my ($dom) = @_;
1.1020    raeburn  9507:     my ($homeserver,%validations);
                   9508:     if ($dom =~ /^$match_domain$/) {
                   9509:         $homeserver = &domain($dom,'primary');
                   9510:     }
                   9511:     unless ($homeserver eq 'no_host') {
                   9512:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9513:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9514:             my @items = split(/&/,$response);
                   9515:             foreach my $item (@items) {
                   9516:                 my ($key,$value) = split('=',$item);
                   9517:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9518:             }
                   9519:         }
                   9520:     }
1.1010    raeburn  9521:     return %validations; 
                   9522: }
                   9523: 
1.1020    raeburn  9524: sub auto_courserequest_validation {
1.1255    raeburn  9525:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9526:     my ($homeserver,$response);
                   9527:     if ($dom =~ /^$match_domain$/) {
                   9528:         $homeserver = &domain($dom,'primary');
                   9529:     }
1.1255    raeburn  9530:     unless ($homeserver eq 'no_host') {
                   9531:         my $customdata;
                   9532:         if (ref($custominfo) eq 'HASH') {
                   9533:             $customdata = &freeze_escape($custominfo);
                   9534:         }
1.1020    raeburn  9535:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9536:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9537:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9538:                                     $customdata,$homeserver));
1.1020    raeburn  9539:     }
                   9540:     return $response;
                   9541: }
                   9542: 
1.777     albertel 9543: sub auto_validate_class_sec {
1.918     raeburn  9544:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9545:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9546:     my $ownerlist;
                   9547:     if (ref($owners) eq 'ARRAY') {
                   9548:         $ownerlist = join(',',@{$owners});
                   9549:     } else {
                   9550:         $ownerlist = $owners;
                   9551:     }
1.773     raeburn  9552:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9553:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9554:     return $response;
                   9555: }
                   9556: 
1.1367    raeburn  9557: sub auto_validate_instclasses {
                   9558:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9559:     my ($homeserver,%validations);
                   9560:     $homeserver = &homeserver($cnum,$cdom);
                   9561:     unless ($homeserver eq 'no_host') {
                   9562:         my $ownerlist;
                   9563:         if (ref($owners) eq 'ARRAY') {
                   9564:             $ownerlist = join(',',@{$owners});
                   9565:         } else {
                   9566:             $ownerlist = $owners;
                   9567:         }
                   9568:         if (ref($classesref) eq 'HASH') {
                   9569:             my $classes = &freeze_escape($classesref);
                   9570:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9571:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9572:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9573:                 my @items = split(/&/,$response);
                   9574:                 foreach my $item (@items) {
                   9575:                     my ($key,$value) = split('=',$item);
                   9576:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9577:                 }
                   9578:             }
                   9579:         }
                   9580:     }
                   9581:     return %validations;
                   9582: }
                   9583: 
1.1248    raeburn  9584: sub auto_crsreq_update {
                   9585:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9586:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9587:     my ($homeserver,%crsreqresponse);
                   9588:     if ($cdom =~ /^$match_domain$/) {
                   9589:         $homeserver = &domain($cdom,'primary');
                   9590:     }
                   9591:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9592:         my $info;
                   9593:         if (ref($inbound) eq 'HASH') {
                   9594:             $info = &freeze_escape($inbound);
                   9595:         }
                   9596:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9597:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9598:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9599:                             &escape($title).':'.&escape($code).':'.
                   9600:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9601:                             $homeserver);
1.1248    raeburn  9602:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9603:             my @items = split(/&/,$response);
                   9604:             foreach my $item (@items) {
                   9605:                 my ($key,$value) = split('=',$item);
                   9606:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9607:             }
                   9608:         }
                   9609:     }
                   9610:     return \%crsreqresponse;
                   9611: }
                   9612: 
1.1305    raeburn  9613: sub auto_export_grades {
1.1309    raeburn  9614:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9615:     my ($homeserver,%exportresponse);
                   9616:     if ($cdom =~ /^$match_domain$/) {
                   9617:         $homeserver = &domain($cdom,'primary');
                   9618:     }
                   9619:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9620:         my $info;
                   9621:         if (ref($inforef) eq 'HASH') {
                   9622:             $info = &freeze_escape($inforef);
                   9623:         }
                   9624:         if (ref($gradesref) eq 'HASH') {
                   9625:             my $grades = &freeze_escape($gradesref);
                   9626:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9627:                                 $info.':'.$grades,$homeserver);
                   9628:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9629:                 my @items = split(/&/,$response);
                   9630:                 foreach my $item (@items) {
                   9631:                     my ($key,$value) = split('=',$item);
                   9632:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9633:                 }
                   9634:             }
                   9635:         }
                   9636:     }
                   9637:     return \%exportresponse;
1.1305    raeburn  9638: }
                   9639: 
1.1287    raeburn  9640: sub check_instcode_cloning {
                   9641:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9642:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9643:         return;
                   9644:     }
                   9645:     my $canclone;
                   9646:     if (@{$code_order} > 0) {
                   9647:         my $instcoderegexp ='^';
                   9648:         my @clonecodes = split(/\&/,$cloner);
                   9649:         foreach my $item (@{$code_order}) {
                   9650:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9651:                 foreach my $pair (@clonecodes) {
                   9652:                     my ($key,$val) = split(/\=/,$pair,2);
                   9653:                     $val = &unescape($val);
                   9654:                     if ($key eq $item) {
                   9655:                         $instcoderegexp .= '('.$val.')';
                   9656:                         last;
                   9657:                     }
                   9658:                 }
                   9659:             } else {
                   9660:                 $instcoderegexp .= $codedefaults->{$item};
                   9661:             }
                   9662:         }
                   9663:         $instcoderegexp .= '$';
                   9664:         my (@from,@to);
                   9665:         eval {
                   9666:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9667:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9668:         };
                   9669:         if ((@from > 0) && (@to > 0)) {
                   9670:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9671:             if (!@diffs) {
                   9672:                 $canclone = 1;
                   9673:             }
                   9674:         }
                   9675:     }
                   9676:     return $canclone;
                   9677: }
                   9678: 
                   9679: sub default_instcode_cloning {
                   9680:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9681:     my (%codedefaults,@code_order,$canclone);
                   9682:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9683:         %codedefaults = %{$codedefaultsref};
                   9684:         @code_order = @{$codeorderref};
                   9685:     } elsif ($clonedom) {
                   9686:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9687:     }
                   9688:     if (($domdefclone) && (@code_order)) {
                   9689:         my @clonecodes = split(/\+/,$domdefclone);
                   9690:         my $instcoderegexp ='^';
                   9691:         foreach my $item (@code_order) {
                   9692:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9693:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9694:             } else {
                   9695:                 $instcoderegexp .= $codedefaults{$item};
                   9696:             }
                   9697:         }
                   9698:         $instcoderegexp .= '$';
                   9699:         my (@from,@to);
                   9700:         eval {
                   9701:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9702:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9703:         };
                   9704:         if ((@from > 0) && (@to > 0)) {
                   9705:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9706:             if (!@diffs) {
                   9707:                 $canclone = 1;
                   9708:             }
                   9709:         }
                   9710:     }
                   9711:     return $canclone;
                   9712: }
                   9713: 
1.679     raeburn  9714: # ------------------------------------------------------- Course Group routines
                   9715: 
                   9716: sub get_coursegroups {
1.809     raeburn  9717:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9718:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9719: }
                   9720: 
1.679     raeburn  9721: sub modify_coursegroup {
                   9722:     my ($cdom,$cnum,$groupsettings) = @_;
                   9723:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9724: }
                   9725: 
1.809     raeburn  9726: sub toggle_coursegroup_status {
                   9727:     my ($cdom,$cnum,$group,$action) = @_;
                   9728:     my ($from_namespace,$to_namespace);
                   9729:     if ($action eq 'delete') {
                   9730:         $from_namespace = 'coursegroups';
                   9731:         $to_namespace = 'deleted_groups';
                   9732:     } else {
                   9733:         $from_namespace = 'deleted_groups';
                   9734:         $to_namespace = 'coursegroups';
                   9735:     }
                   9736:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9737:     if (my $tmp = &error(%curr_group)) {
                   9738:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9739:         return ('read error',$tmp);
                   9740:     } else {
                   9741:         my %savedsettings = %curr_group; 
1.809     raeburn  9742:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9743:         my $deloutcome;
                   9744:         if ($result eq 'ok') {
1.809     raeburn  9745:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9746:         } else {
                   9747:             return ('write error',$result);
                   9748:         }
                   9749:         if ($deloutcome eq 'ok') {
                   9750:             return 'ok';
                   9751:         } else {
                   9752:             return ('delete error',$deloutcome);
                   9753:         }
                   9754:     }
                   9755: }
                   9756: 
1.679     raeburn  9757: sub modify_group_roles {
1.957     raeburn  9758:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9759:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9760:     my $role = 'gr/'.&escape($userprivs);
                   9761:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9762:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9763:     if ($result eq 'ok') {
                   9764:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9765:     }
1.679     raeburn  9766:     return $result;
                   9767: }
                   9768: 
                   9769: sub modify_coursegroup_membership {
                   9770:     my ($cdom,$cnum,$membership) = @_;
                   9771:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9772:     return $result;
                   9773: }
                   9774: 
1.682     raeburn  9775: sub get_active_groups {
                   9776:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9777:     my $now = time;
                   9778:     my %groups = ();
                   9779:     foreach my $key (keys(%env)) {
1.811     albertel 9780:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9781:             my ($start,$end) = split(/\./,$env{$key});
                   9782:             if (($end!=0) && ($end<$now)) { next; }
                   9783:             if (($start!=0) && ($start>$now)) { next; }
                   9784:             if ($1 eq $cdom && $2 eq $cnum) {
                   9785:                 $groups{$3} = $env{$key} ;
                   9786:             }
                   9787:         }
                   9788:     }
                   9789:     return %groups;
                   9790: }
                   9791: 
1.683     raeburn  9792: sub get_group_membership {
                   9793:     my ($cdom,$cnum,$group) = @_;
                   9794:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9795: }
                   9796: 
                   9797: sub get_users_groups {
                   9798:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9799:     my @usersgroups;
1.683     raeburn  9800:     my $cachetime=1800;
                   9801: 
                   9802:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9803:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9804:     if (defined($cached)) {
1.734     albertel 9805:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9806:     } else {  
                   9807:         $grouplist = '';
1.816     raeburn  9808:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9809:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9810:         my $access_end = $env{'course.'.$courseid.
                   9811:                               '.default_enrollment_end_date'};
                   9812:         my $now = time;
                   9813:         foreach my $key (keys(%roleshash)) {
                   9814:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9815:                 my $group = $1;
                   9816:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9817:                     my $start = $2;
                   9818:                     my $end = $1;
                   9819:                     if ($start == -1) { next; } # deleted from group
                   9820:                     if (($start!=0) && ($start>$now)) { next; }
                   9821:                     if (($end!=0) && ($end<$now)) {
                   9822:                         if ($access_end && $access_end < $now) {
                   9823:                             if ($access_end - $end < 86400) {
                   9824:                                 push(@usersgroups,$group);
1.733     raeburn  9825:                             }
                   9826:                         }
1.817     raeburn  9827:                         next;
1.733     raeburn  9828:                     }
1.817     raeburn  9829:                     push(@usersgroups,$group);
1.683     raeburn  9830:                 }
                   9831:             }
                   9832:         }
1.817     raeburn  9833:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9834:         $grouplist = join(':',@usersgroups);
                   9835:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9836:     }
1.733     raeburn  9837:     return @usersgroups;
1.683     raeburn  9838: }
                   9839: 
                   9840: sub devalidate_getgroups_cache {
                   9841:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9842:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9843: 
1.683     raeburn  9844:     my $hashid="$udom:$uname:$courseid";
                   9845:     &devalidate_cache_new('getgroups',$hashid);
                   9846: }
                   9847: 
1.12      www      9848: # ------------------------------------------------------------------ Plain Text
                   9849: 
                   9850: sub plaintext {
1.988     raeburn  9851:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9852:     if ($short =~ m{^cr/}) {
1.758     albertel 9853: 	return (split('/',$short))[-1];
                   9854:     }
1.742     raeburn  9855:     if (!defined($cid)) {
                   9856:         $cid = $env{'request.course.id'};
                   9857:     }
                   9858:     my %rolenames = (
1.1008    raeburn  9859:                       Course    => 'std',
                   9860:                       Community => 'alt1',
1.1305    raeburn  9861:                       Placement => 'std',
1.742     raeburn  9862:                     );
1.1037    raeburn  9863:     if ($cid ne '') {
                   9864:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9865:             unless ($forcedefault) {
                   9866:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9867:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9868:                 return &Apache::lonlocal::mt($roletext);
                   9869:             }
                   9870:         }
                   9871:     }
                   9872:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9873:         (defined($rolenames{$type})) && 
                   9874:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9875:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9876:     } elsif ($cid ne '') {
                   9877:         my $crstype = $env{'course.'.$cid.'.type'};
                   9878:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9879:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9880:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9881:         }
1.742     raeburn  9882:     }
1.1037    raeburn  9883:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9884: }
                   9885: 
                   9886: # ----------------------------------------------------------------- Assign Role
                   9887: 
                   9888: sub assignrole {
1.957     raeburn  9889:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9890:         $context)=@_;
1.21      www      9891:     my $mrole;
                   9892:     if ($role =~ /^cr\//) {
1.393     www      9893:         my $cwosec=$url;
1.811     albertel 9894:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9895: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9896:            my $refused = 1;
                   9897:            if ($context eq 'requestcourses') {
                   9898:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9899:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9900:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9901:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9902:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9903:                            if ($crsenv{'internal.courseowner'} eq
                   9904:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9905:                                $refused = '';
                   9906:                            }
                   9907:                        }
                   9908:                    }
                   9909:                }
                   9910:            }
                   9911:            if ($refused) {
                   9912:                &logthis('Refused custom assignrole: '.
                   9913:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9914:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9915:                return 'refused';
                   9916:            }
1.104     www      9917:         }
1.21      www      9918:         $mrole='cr';
1.678     raeburn  9919:     } elsif ($role =~ /^gr\//) {
                   9920:         my $cwogrp=$url;
1.811     albertel 9921:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9922:         unless (&allowed('mdg',$cwogrp)) {
                   9923:             &logthis('Refused group assignrole: '.
                   9924:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9925:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9926:             return 'refused';
                   9927:         }
                   9928:         $mrole='gr';
1.21      www      9929:     } else {
1.82      www      9930:         my $cwosec=$url;
1.811     albertel 9931:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9932:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9933:             my $refused;
                   9934:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9935:                 if (!(&allowed('c'.$role,$url))) {
                   9936:                     $refused = 1;
                   9937:                 }
                   9938:             } else {
                   9939:                 $refused = 1;
                   9940:             }
1.947     raeburn  9941:             if ($refused) {
1.1045    raeburn  9942:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9943:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9944:                     my %crsenv;
                   9945:                     if ($role eq 'cc' || $role eq 'co') {
                   9946:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9947:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9948:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9949:                                 if ($crsenv{'internal.courseowner'} eq 
                   9950:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9951:                                     $refused = '';
                   9952:                                 }
                   9953:                             }
                   9954:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9955:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9956:                                 if ($crsenv{'internal.courseowner'} eq 
                   9957:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9958:                                     $refused = '';
                   9959:                                 }
                   9960:                             }
                   9961:                         }
                   9962:                     }
1.1368    raeburn  9963:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9964:                     if ($role eq 'st') {
                   9965:                         $refused = '';
1.1377    raeburn  9966:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9967:                         $refused = '';
                   9968:                     }
1.1017    raeburn  9969:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9970:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9971:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9972:                         my $wrongcc;
                   9973:                         if ($cnum =~ /^$match_community$/) {
                   9974:                             $wrongcc = 1 if ($role eq 'cc');
                   9975:                         } else {
                   9976:                             $wrongcc = 1 if ($role eq 'co');
                   9977:                         }
                   9978:                         unless ($wrongcc) {
                   9979:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9980:                             if ($crsenv{'internal.courseowner'} eq 
                   9981:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9982:                                 $refused = '';
                   9983:                             }
1.1017    raeburn  9984:                         }
                   9985:                     }
1.1183    raeburn  9986:                 } elsif ($context eq 'requestauthor') {
                   9987:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9988:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9989:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9990:                             $refused = '';
                   9991:                         } else {
                   9992:                             my %domdefaults = &get_domain_defaults($udom);
                   9993:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9994:                                 my $checkbystatus;
                   9995:                                 if ($env{'user.adv'}) { 
                   9996:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9997:                                     if ($disposition eq 'automatic') {
                   9998:                                         $refused = '';
                   9999:                                     } elsif ($disposition eq '') {
                   10000:                                         $checkbystatus = 1;
                   10001:                                     } 
                   10002:                                 } else {
                   10003:                                     $checkbystatus = 1;
                   10004:                                 }
                   10005:                                 if ($checkbystatus) {
                   10006:                                     if ($env{'environment.inststatus'}) {
                   10007:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10008:                                         foreach my $type (@inststatuses) {
                   10009:                                             if (($type ne '') &&
                   10010:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10011:                                                 $refused = '';
                   10012:                                             }
                   10013:                                         }
                   10014:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10015:                                         $refused = '';
                   10016:                                     }
                   10017:                                 }
                   10018:                             }
                   10019:                         }
                   10020:                     }
1.1017    raeburn  10021:                 }
                   10022:                 if ($refused) {
1.947     raeburn  10023:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10024:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10025: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10026:                     return 'refused';
                   10027:                 }
1.932     raeburn  10028:             }
1.1131    raeburn  10029:         } elsif ($role eq 'au') {
                   10030:             if ($url ne '/'.$udom.'/') {
                   10031:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10032:                          ' to assign author role for '.$uname.':'.$udom.
                   10033:                          ' in domain: '.$url.' refused (wrong domain).');
                   10034:                 return 'refused';
                   10035:             }
1.104     www      10036:         }
1.21      www      10037:         $mrole=$role;
                   10038:     }
1.620     albertel 10039:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10040:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10041:     if ($end) { $command.='_'.$end; }
1.21      www      10042:     if ($start) {
                   10043: 	if ($end) { 
1.81      www      10044:            $command.='_'.$start; 
1.21      www      10045:         } else {
1.81      www      10046:            $command.='_0_'.$start;
1.21      www      10047:         }
                   10048:     }
1.739     raeburn  10049:     my $origstart = $start;
                   10050:     my $origend = $end;
1.957     raeburn  10051:     my $delflag;
1.357     www      10052: # actually delete
                   10053:     if ($deleteflag) {
1.373     www      10054: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10055: # modify command to delete the role
1.620     albertel 10056:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10057:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10058: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10059: # set start and finish to negative values for userrolelog
                   10060:            $start=-1;
                   10061:            $end=-1;
1.957     raeburn  10062:            $delflag = 1;
1.357     www      10063:         }
                   10064:     }
                   10065: # send command
1.349     www      10066:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10067: # log new user role if status is ok
1.349     www      10068:     if ($answer eq 'ok') {
1.663     raeburn  10069: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10070:         if (($role eq 'cc') || ($role eq 'in') ||
                   10071:             ($role eq 'ep') || ($role eq 'ad') ||
                   10072:             ($role eq 'ta') || ($role eq 'st') ||
                   10073:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10074:             ($role eq 'co')) {
1.1200    raeburn  10075: # for course roles, perform group memberships changes triggered by role change.
                   10076:             unless ($role =~ /^gr/) {
                   10077:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10078:                                                  $origstart,$selfenroll,$context);
                   10079:             }
1.1184    raeburn  10080:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10081:                            $selfenroll,$context);
                   10082:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10083:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10084:                  ($role eq 'da')) {
1.1184    raeburn  10085:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10086:                            $context);
                   10087:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10088:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10089:                              $context); 
                   10090:         }
1.1053    raeburn  10091:         if ($role eq 'cc') {
                   10092:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10093:         }
1.349     www      10094:     }
                   10095:     return $answer;
1.169     harris41 10096: }
                   10097: 
1.1053    raeburn  10098: sub autoupdate_coowners {
                   10099:     my ($url,$end,$start,$uname,$udom) = @_;
                   10100:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10101:     if (($cdom ne '') && ($cnum ne '')) {
                   10102:         my $now = time;
                   10103:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10104:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10105:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10106:             my $instcode = $coursehash{'internal.coursecode'};
                   10107:             if ($instcode ne '') {
1.1056    raeburn  10108:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10109:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10110:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10111:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   10112:                         if ($result eq 'valid') {
                   10113:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10114:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10115:                                     push(@newcoowners,$coowner);
                   10116:                                 }
                   10117:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10118:                                     push(@newcoowners,$uname.':'.$udom);
                   10119:                                 }
                   10120:                                 @newcoowners = sort(@newcoowners);
                   10121:                             } else {
                   10122:                                 push(@newcoowners,$uname.':'.$udom);
                   10123:                             }
                   10124:                         } else {
                   10125:                             if ($coursehash{'internal.co-owners'}) {
                   10126:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10127:                                     unless ($coowner eq $uname.':'.$udom) {
                   10128:                                         push(@newcoowners,$coowner);
                   10129:                                     }
                   10130:                                 }
                   10131:                                 unless (@newcoowners > 0) {
                   10132:                                     $delcoowners = 1;
                   10133:                                     $coowners = '';
                   10134:                                 }
                   10135:                             }
                   10136:                         }
                   10137:                         if (@newcoowners || $delcoowners) {
                   10138:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10139:                                             $delcoowners,@newcoowners);
                   10140:                         }
                   10141:                     }
                   10142:                 }
                   10143:             }
                   10144:         }
                   10145:     }
                   10146: }
                   10147: 
                   10148: sub store_coowners {
                   10149:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10150:     my $cid = $cdom.'_'.$cnum;
                   10151:     my ($coowners,$delresult,$putresult);
                   10152:     if (@newcoowners) {
                   10153:         $coowners = join(',',@newcoowners);
                   10154:         my %coownershash = (
                   10155:                             'internal.co-owners' => $coowners,
                   10156:                            );
                   10157:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10158:         if ($putresult eq 'ok') {
                   10159:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10160:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10161:             }
                   10162:         }
                   10163:     }
                   10164:     if ($delcoowners) {
                   10165:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10166:         if ($delresult eq 'ok') {
                   10167:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10168:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10169:             }
                   10170:         }
                   10171:     }
                   10172:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10173:         my %crsinfo =
                   10174:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10175:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10176:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10177:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10178:         }
                   10179:     }
                   10180: }
                   10181: 
1.169     harris41 10182: # -------------------------------------------------- Modify user authentication
1.197     www      10183: # Overrides without validation
                   10184: 
1.169     harris41 10185: sub modifyuserauth {
                   10186:     my ($udom,$uname,$umode,$upass)=@_;
                   10187:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10188:     my $allowed;
                   10189:     if (&allowed('mau',$udom)) {
                   10190:         $allowed = 1;
                   10191:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10192:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10193:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10194:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10195:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10196:         if (($cdom ne '') && ($cnum ne '')) {
                   10197:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10198:             if ($is_owner) {
                   10199:                 $allowed = 1;
                   10200:             }
                   10201:         }
                   10202:     }
                   10203:     unless ($allowed) { return 'refused'; }
1.197     www      10204:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10205:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10206:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10207:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10208: 		     &escape($upass),$uhome);
1.620     albertel 10209:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10210:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   10211:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   10212:     &log($udom,,$uname,$uhome,
1.620     albertel 10213:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10214:                                      $env{'user.name'}.', '.$umode.
1.197     www      10215:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 10216:     unless ($reply eq 'ok') {
1.197     www      10217:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10218: 	return 'error: '.$reply;
                   10219:     }   
1.170     harris41 10220:     return 'ok';
1.80      www      10221: }
                   10222: 
1.81      www      10223: # --------------------------------------------------------------- Modify a user
1.80      www      10224: 
1.81      www      10225: sub modifyuser {
1.206     matthew  10226:     my ($udom,    $uname, $uid,
                   10227:         $umode,   $upass, $first,
                   10228:         $middle,  $last,  $gene,
1.1058    raeburn  10229:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10230:     $udom= &LONCAPA::clean_domain($udom);
                   10231:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10232:     my $showcandelete = 'none';
                   10233:     if (ref($candelete) eq 'ARRAY') {
                   10234:         if (@{$candelete} > 0) {
                   10235:             $showcandelete = join(', ',@{$candelete});
                   10236:         }
                   10237:     }
1.81      www      10238:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10239:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10240: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10241:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10242:                                      ' desiredhome not specified'). 
1.620     albertel 10243:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10244:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10245:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10246:     my $newuser;
                   10247:     if ($uhome eq 'no_host') {
                   10248:         $newuser = 1;
1.1368    raeburn  10249:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10250:                 ($umode eq 'lti')) {
                   10251:             return 'error: more information needed to create new user';
                   10252:         }
1.1075    raeburn  10253:     }
1.80      www      10254: # ----------------------------------------------------------------- Create User
1.406     albertel 10255:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10256: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10257:         my $unhome='';
1.844     albertel 10258:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10259:             $unhome = $desiredhome;
1.620     albertel 10260: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10261: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10262:         } else { # load balancing routine for determining $unhome
1.81      www      10263:             my $loadm=10000000;
1.841     albertel 10264: 	    my %servers = &get_servers($udom,'library');
                   10265: 	    foreach my $tryserver (keys(%servers)) {
                   10266: 		my $answer=reply('load',$tryserver);
                   10267: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10268: 		    $loadm=$answer;
                   10269: 		    $unhome=$tryserver;
                   10270: 		}
1.80      www      10271: 	    }
                   10272:         }
                   10273:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10274: 	    return 'error: unable to find a home server for '.$uname.
                   10275:                    ' in domain '.$udom;
1.80      www      10276:         }
                   10277:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10278:                          &escape($upass),$unhome);
                   10279: 	unless ($reply eq 'ok') {
                   10280:             return 'error: '.$reply;
                   10281:         }   
1.230     stredwic 10282:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10283:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10284: 	    return 'error: unable verify users home machine.';
1.80      www      10285:         }
1.209     matthew  10286:     }   # End of creation of new user
1.80      www      10287: # ---------------------------------------------------------------------- Add ID
                   10288:     if ($uid) {
                   10289:        $uid=~tr/A-Z/a-z/;
                   10290:        my %uidhash=&idrget($udom,$uname);
1.196     www      10291:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10292:          && (!$forceid)) {
1.80      www      10293: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10294: 	      return 'error: user id "'.$uid.'" does not match '.
                   10295:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10296:           }
                   10297:        } else {
1.1300    raeburn  10298: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10299:        }
                   10300:     }
                   10301: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10302:     my @tmp=&get('environment',
1.899     raeburn  10303: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10304:                     'permanentemail','inststatus'],
1.134     albertel 10305: 		   $udom,$uname);
1.1075    raeburn  10306:     my (%names,%oldnames);
1.313     matthew  10307:     if ($tmp[0] =~ m/^error:.*/) { 
                   10308:         %names=(); 
                   10309:     } else {
                   10310:         %names = @tmp;
1.1075    raeburn  10311:         %oldnames = %names;
1.313     matthew  10312:     }
1.388     www      10313: #
1.1058    raeburn  10314: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10315: # of users did not contain them), do not overwrite existing values
                   10316: # unless field is in $candelete array ref.  
                   10317: #
                   10318: 
                   10319:     my @fields = ('firstname','middlename','lastname','generation',
                   10320:                   'permanentemail','id');
                   10321:     my %newvalues;
                   10322:     if (ref($candelete) eq 'ARRAY') {
                   10323:         foreach my $field (@fields) {
                   10324:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10325:                 if ($field eq 'firstname') {
                   10326:                     $names{$field} = $first;
                   10327:                 } elsif ($field eq 'middlename') {
                   10328:                     $names{$field} = $middle;
                   10329:                 } elsif ($field eq 'lastname') {
                   10330:                     $names{$field} = $last;
                   10331:                 } elsif ($field eq 'generation') { 
                   10332:                     $names{$field} = $gene;
                   10333:                 } elsif ($field eq 'permanentemail') {
                   10334:                     $names{$field} = $email;
                   10335:                 } elsif ($field eq 'id') {
                   10336:                     $names{$field}  = $uid;
                   10337:                 }
                   10338:             }
                   10339:         }
                   10340:     }
1.388     www      10341:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10342:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10343:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10344:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10345:     if ($email) {
                   10346:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10347:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10348:     }
1.899     raeburn  10349:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10350:     if (defined($inststatus)) {
                   10351:         $names{'inststatus'} = '';
                   10352:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10353:         if (ref($usertypes) eq 'HASH') {
                   10354:             my @okstatuses; 
                   10355:             foreach my $item (split(/:/,$inststatus)) {
                   10356:                 if (defined($usertypes->{$item})) {
                   10357:                     push(@okstatuses,$item);  
                   10358:                 }
                   10359:             }
                   10360:             if (@okstatuses) {
                   10361:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10362:             }
                   10363:         }
                   10364:     }
1.1075    raeburn  10365:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10366:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10367:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10368:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10369:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10370:     } else {
                   10371:         $logmsg .= ' during self creation';
                   10372:     }
1.1075    raeburn  10373:     my $changed;
                   10374:     if ($newuser) {
                   10375:         $changed = 1;
                   10376:     } else {
                   10377:         foreach my $field (@fields) {
                   10378:             if ($names{$field} ne $oldnames{$field}) {
                   10379:                 $changed = 1;
                   10380:                 last;
                   10381:             }
                   10382:         }
                   10383:     }
                   10384:     unless ($changed) {
                   10385:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10386:         &logthis($logmsg);
                   10387:         return 'ok';
                   10388:     }
                   10389:     my $reply = &put('environment', \%names, $udom,$uname);
                   10390:     if ($reply ne 'ok') { 
                   10391:         return 'error: '.$reply;
                   10392:     }
1.1087    raeburn  10393:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10394:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10395:     }
1.1075    raeburn  10396:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10397:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10398:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10399:     &logthis($logmsg);
1.134     albertel 10400:     return 'ok';
1.80      www      10401: }
                   10402: 
1.81      www      10403: # -------------------------------------------------------------- Modify student
1.80      www      10404: 
1.81      www      10405: sub modifystudent {
                   10406:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10407:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10408:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10409:     if (!$cid) {
1.620     albertel 10410: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10411: 	    return 'not_in_class';
                   10412: 	}
1.80      www      10413:     }
                   10414: # --------------------------------------------------------------- Make the user
1.81      www      10415:     my $reply=&modifyuser
1.209     matthew  10416: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10417:          $desiredhome,$email,$inststatus);
1.80      www      10418:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10419:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10420:     # student's environment
1.297     matthew  10421:     $uid = undef if (!$forceid);
1.455     albertel 10422:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10423:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10424:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10425:     return $reply;
                   10426: }
                   10427: 
                   10428: sub modify_student_enrollment {
1.1216    raeburn  10429:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10430:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10431:     my ($cdom,$cnum,$chome);
                   10432:     if (!$cid) {
1.620     albertel 10433: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10434: 	    return 'not_in_class';
                   10435: 	}
1.620     albertel 10436: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10437: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10438:     } else {
                   10439: 	($cdom,$cnum)=split(/_/,$cid);
                   10440:     }
1.620     albertel 10441:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10442:     if (!$chome) {
1.457     raeburn  10443: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10444:     }
1.455     albertel 10445:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10446:     # Make sure the user exists
1.81      www      10447:     my $uhome=&homeserver($uname,$udom);
                   10448:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10449: 	return 'error: no such user';
                   10450:     }
1.297     matthew  10451:     # Get student data if we were not given enough information
                   10452:     if (!defined($first)  || $first  eq '' || 
                   10453:         !defined($last)   || $last   eq '' || 
                   10454:         !defined($uid)    || $uid    eq '' || 
                   10455:         !defined($middle) || $middle eq '' || 
                   10456:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10457:         # They did not supply us with enough data to enroll the student, so
                   10458:         # we need to pick up more information.
1.297     matthew  10459:         my %tmp = &get('environment',
1.294     matthew  10460:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10461:                        ,$udom,$uname);
                   10462: 
1.800     albertel 10463:         #foreach my $key (keys(%tmp)) {
                   10464:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10465:         #}
1.294     matthew  10466:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10467:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10468:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10469:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10470:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10471:     }
1.556     albertel 10472:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10473:     my $user = "$uname:$udom";
                   10474:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10475:     my $reply=cput('classlist',
1.1148    raeburn  10476: 		   {$user => 
1.1314    raeburn  10477: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10478: 		   $cdom,$cnum);
1.1148    raeburn  10479:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10480:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10481:     } else { 
1.81      www      10482: 	return 'error: '.$reply;
                   10483:     }
1.297     matthew  10484:     # Add student role to user
1.83      www      10485:     my $uurl='/'.$cid;
1.81      www      10486:     $uurl=~s/\_/\//g;
                   10487:     if ($usec) {
                   10488: 	$uurl.='/'.$usec;
                   10489:     }
1.1148    raeburn  10490:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10491:                              $selfenroll,$context);
                   10492:     if ($result ne 'ok') {
                   10493:         if ($old_entry{$user} ne '') {
                   10494:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10495:         } else {
                   10496:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10497:         }
                   10498:     }
                   10499:     return $result; 
1.21      www      10500: }
                   10501: 
1.556     albertel 10502: sub format_name {
                   10503:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10504:     my $name;
                   10505:     if ($first ne 'lastname') {
                   10506: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10507:     } else {
                   10508: 	if ($lastname=~/\S/) {
                   10509: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10510: 	    $name=~s/\s+,/,/;
                   10511: 	} else {
                   10512: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10513: 	}
                   10514:     }
                   10515:     $name=~s/^\s+//;
                   10516:     $name=~s/\s+$//;
                   10517:     $name=~s/\s+/ /g;
                   10518:     return $name;
                   10519: }
                   10520: 
1.84      www      10521: # ------------------------------------------------- Write to course preferences
                   10522: 
                   10523: sub writecoursepref {
                   10524:     my ($courseid,%prefs)=@_;
                   10525:     $courseid=~s/^\///;
                   10526:     $courseid=~s/\_/\//g;
                   10527:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10528:     my $chome=homeserver($cnum,$cdomain);
                   10529:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10530: 	return 'error: no such course';
                   10531:     }
                   10532:     my $cstring='';
1.800     albertel 10533:     foreach my $pref (keys(%prefs)) {
                   10534: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10535:     }
1.84      www      10536:     $cstring=~s/\&$//;
                   10537:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10538: }
                   10539: 
                   10540: # ---------------------------------------------------------- Make/modify course
                   10541: 
                   10542: sub createcourse {
1.741     raeburn  10543:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10544:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10545:     $url=&declutter($url);
                   10546:     my $cid='';
1.1028    raeburn  10547:     if ($context eq 'requestcourses') {
                   10548:         my $can_create = 0;
                   10549:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10550:         if ($udom eq $ownerdom) {
                   10551:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10552:                                   $context)) {
                   10553:                 $can_create = 1;
                   10554:             }
                   10555:         } else {
                   10556:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10557:                                            $category);
                   10558:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10559:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10560:                 if (@curr > 0) {
                   10561:                     my @options = qw(approval validate autolimit);
                   10562:                     my $optregex = join('|',@options);
                   10563:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10564:                         $can_create = 1;
                   10565:                     }
                   10566:                 }
                   10567:             }
                   10568:         }
                   10569:         if ($can_create) {
                   10570:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10571:                 unless (&allowed('ccc',$udom)) {
                   10572:                     return 'refused'; 
                   10573:                 }
1.1017    raeburn  10574:             }
                   10575:         } else {
                   10576:             return 'refused';
                   10577:         }
1.1028    raeburn  10578:     } elsif (!&allowed('ccc',$udom)) {
                   10579:         return 'refused';
1.84      www      10580:     }
1.1011    raeburn  10581: # --------------------------------------------------------------- Get Unique ID
                   10582:     my $uname;
                   10583:     if ($cnum =~ /^$match_courseid$/) {
                   10584:         my $chome=&homeserver($cnum,$udom,'true');
                   10585:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10586:             $uname = $cnum;
                   10587:         } else {
1.1038    raeburn  10588:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10589:         }
                   10590:     } else {
1.1038    raeburn  10591:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10592:     }
                   10593:     return $uname if ($uname =~ /^error/);
                   10594: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10595:     if (!defined($course_server)) {
                   10596:         if (defined(&domain($udom,'primary'))) {
                   10597:             $course_server = &domain($udom,'primary');
                   10598:         } else {
                   10599:             $course_server = $env{'user.home'}; 
                   10600:         }
                   10601:     }
                   10602:     my %host_servers =
                   10603:         &Apache::lonnet::get_servers($udom,'library');
                   10604:     unless ($host_servers{$course_server}) {
                   10605:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10606:     }
1.84      www      10607: # ------------------------------------------------------------- Make the course
                   10608:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10609:                       $course_server);
1.84      www      10610:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10611:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10612:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10613: 	return 'error: no such course';
                   10614:     }
1.271     www      10615: # ----------------------------------------------------------------- Course made
1.516     raeburn  10616: # log existence
1.1029    raeburn  10617:     my $now = time;
1.918     raeburn  10618:     my $newcourse = {
                   10619:                     $udom.'_'.$uname => {
1.921     raeburn  10620:                                      description => $description,
                   10621:                                      inst_code   => $inst_code,
                   10622:                                      owner       => $course_owner,
                   10623:                                      type        => $crstype,
1.1029    raeburn  10624:                                      creator     => $env{'user.name'}.':'.
                   10625:                                                     $env{'user.domain'},
                   10626:                                      created     => $now,
                   10627:                                      context     => $context,
1.918     raeburn  10628:                                                 },
                   10629:                     };
1.921     raeburn  10630:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10631: # set toplevel url
1.271     www      10632:     my $topurl=$url;
                   10633:     unless ($nonstandard) {
                   10634: # ------------------------------------------ For standard courses, make top url
                   10635:         my $mapurl=&clutter($url);
1.278     www      10636:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10637:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10638: <map>
                   10639: <resource id="1" type="start"></resource>
                   10640: <resource id="2" src="$mapurl"></resource>
                   10641: <resource id="3" type="finish"></resource>
                   10642: <link index="1" from="1" to="2"></link>
                   10643: <link index="2" from="2" to="3"></link>
                   10644: </map>
                   10645: ENDINITMAP
                   10646:         $topurl=&declutter(
1.638     albertel 10647:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10648:                           );
                   10649:     }
                   10650: # ----------------------------------------------------------- Write preferences
1.84      www      10651:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10652:                      ('description'              => $description,
                   10653:                       'url'                      => $topurl,
                   10654:                       'internal.creator'         => $env{'user.name'}.':'.
                   10655:                                                     $env{'user.domain'},
                   10656:                       'internal.created'         => $now,
                   10657:                       'internal.creationcontext' => $context)
                   10658:                     );
1.84      www      10659:     return '/'.$udom.'/'.$uname;
                   10660: }
                   10661: 
1.1011    raeburn  10662: # ------------------------------------------------------------------- Create ID
                   10663: sub generate_coursenum {
1.1038    raeburn  10664:     my ($udom,$crstype) = @_;
1.1011    raeburn  10665:     my $domdesc = &domain($udom);
                   10666:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10667:     my $first;
                   10668:     if ($crstype eq 'Community') {
                   10669:         $first = '0';
                   10670:     } else {
                   10671:         $first = int(1+rand(9)); 
                   10672:     } 
                   10673:     my $uname=$first.
1.1011    raeburn  10674:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10675:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10676:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10677: # ----------------------------------------------- Make sure that does not exist
                   10678:     my $uhome=&homeserver($uname,$udom,'true');
                   10679:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10680:         if ($crstype eq 'Community') {
                   10681:             $first = '0';
                   10682:         } else {
                   10683:             $first = int(1+rand(9));
                   10684:         }
                   10685:         $uname=$first.
1.1011    raeburn  10686:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10687:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10688:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10689:         $uhome=&homeserver($uname,$udom,'true');
                   10690:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10691:             return 'error: unable to generate unique course-ID';
                   10692:         }
                   10693:     }
                   10694:     return $uname;
                   10695: }
                   10696: 
1.813     albertel 10697: sub is_course {
1.1167    droeschl 10698:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10699:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10700: 
1.1381    raeburn  10701:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10702:     my $uhome=&homeserver($cnum,$cdom);
                   10703:     my $iscourse;
                   10704:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10705:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10706:     } else {
                   10707:         my $hashid = $cdom.':'.$cnum;
                   10708:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10709:         unless (defined($cached)) {
                   10710:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10711:                                         $cnum,undef,undef,'.');
                   10712:             $iscourse = 0;
                   10713:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10714:                 $iscourse = 1;
                   10715:             }
                   10716:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10717:         }
                   10718:     }
                   10719:     return unless ($iscourse);
1.1167    droeschl 10720:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10721: }
                   10722: 
1.1015    raeburn  10723: sub store_userdata {
                   10724:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10725:     my $result;
1.1016    raeburn  10726:     if ($datakey ne '') {
1.1013    raeburn  10727:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10728:             if ($udom eq '' || $uname eq '') {
                   10729:                 $udom = $env{'user.domain'};
                   10730:                 $uname = $env{'user.name'};
                   10731:             }
                   10732:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10733:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10734:                 $result = 'error: no_host';
                   10735:             } else {
                   10736:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10737:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10738: 
                   10739:                 my $namevalue='';
                   10740:                 foreach my $key (keys(%{$storehash})) {
                   10741:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10742:                 }
                   10743:                 $namevalue=~s/\&$//;
1.1224    raeburn  10744:                 unless ($namespace eq 'courserequests') {
                   10745:                     $datakey = &escape($datakey);
                   10746:                 }
1.1105    raeburn  10747:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10748:                                   $namevalue,$uhome);
1.1013    raeburn  10749:             }
                   10750:         } else {
                   10751:             $result = 'error: data to store was not a hash reference'; 
                   10752:         }
                   10753:     } else {
                   10754:         $result= 'error: invalid requestkey'; 
                   10755:     }
                   10756:     return $result;
                   10757: }
                   10758: 
1.21      www      10759: # ---------------------------------------------------------- Assign Custom Role
                   10760: 
                   10761: sub assigncustomrole {
1.957     raeburn  10762:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10763:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10764:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10765: }
                   10766: 
                   10767: # ----------------------------------------------------------------- Revoke Role
                   10768: 
                   10769: sub revokerole {
1.957     raeburn  10770:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10771:     my $now=time;
1.965     raeburn  10772:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10773: }
                   10774: 
                   10775: # ---------------------------------------------------------- Revoke Custom Role
                   10776: 
                   10777: sub revokecustomrole {
1.957     raeburn  10778:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10779:     my $now=time;
1.357     www      10780:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10781:            $deleteflag,$selfenroll,$context);
1.17      www      10782: }
                   10783: 
1.533     banghart 10784: # ------------------------------------------------------------ Disk usage
1.535     albertel 10785: sub diskusage {
1.955     raeburn  10786:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10787:     $directorypath =~ s/\/$//;
                   10788:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10789:                        .&escape($getpropath).':'.&escape($uname).':'
                   10790:                        .&escape($udom),homeserver($uname,$udom));
                   10791:     if ($listing eq 'unknown_cmd') {
                   10792:         if ($getpropath) {
                   10793:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10794:         }
                   10795:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10796:     }
1.514     albertel 10797:     return $listing;
1.512     banghart 10798: }
                   10799: 
1.566     banghart 10800: sub is_locked {
1.1096    raeburn  10801:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10802:     my @check;
                   10803:     my $is_locked;
1.1093    raeburn  10804:     push (@check,$file_name);
1.613     albertel 10805:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10806: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10807:     my ($tmp)=keys(%locked);
                   10808:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10809:     
1.566     banghart 10810:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10811:         $is_locked = 'false';
                   10812:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10813:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10814:                $is_locked = 'true';
1.1096    raeburn  10815:                if (ref($which) eq 'ARRAY') {
                   10816:                    push(@{$which},$entry);
                   10817:                } else {
                   10818:                    last;
                   10819:                }
1.745     raeburn  10820:            }
                   10821:        }
1.566     banghart 10822:     } else {
                   10823:         $is_locked = 'false';
                   10824:     }
1.1093    raeburn  10825:     return $is_locked;
1.566     banghart 10826: }
                   10827: 
1.759     albertel 10828: sub declutter_portfile {
                   10829:     my ($file) = @_;
1.833     albertel 10830:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10831:     return $file;
                   10832: }
                   10833: 
1.559     banghart 10834: # ------------------------------------------------------------- Mark as Read Only
                   10835: 
                   10836: sub mark_as_readonly {
                   10837:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10838:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10839:     my ($tmp)=keys(%current_permissions);
                   10840:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10841:     foreach my $file (@{$files}) {
1.759     albertel 10842: 	$file = &declutter_portfile($file);
1.561     banghart 10843:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10844:     }
1.613     albertel 10845:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10846:     return;
                   10847: }
                   10848: 
1.572     banghart 10849: # ------------------------------------------------------------Save Selected Files
                   10850: 
                   10851: sub save_selected_files {
                   10852:     my ($user, $path, @files) = @_;
                   10853:     my $filename = $user."savedfiles";
1.573     banghart 10854:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10855:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10856:     foreach my $file (@files) {
1.620     albertel 10857:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10858:     }
                   10859:     foreach my $file (@other_files) {
1.574     banghart 10860:         print (OUT $file."\n");
1.572     banghart 10861:     }
1.574     banghart 10862:     close (OUT);
1.572     banghart 10863:     return 'ok';
                   10864: }
                   10865: 
1.574     banghart 10866: sub clear_selected_files {
                   10867:     my ($user) = @_;
                   10868:     my $filename = $user."savedfiles";
1.1359    raeburn  10869:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10870:     print (OUT undef);
                   10871:     close (OUT);
                   10872:     return ("ok");    
                   10873: }
                   10874: 
1.572     banghart 10875: sub files_in_path {
                   10876:     my ($user, $path) = @_;
                   10877:     my $filename = $user."savedfiles";
                   10878:     my %return_files;
1.1359    raeburn  10879:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10880:     while (my $line_in = <IN>) {
1.574     banghart 10881:         chomp ($line_in);
                   10882:         my @paths_and_file = split (m!/!, $line_in);
                   10883:         my $file_part = pop (@paths_and_file);
                   10884:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10885:         $path_part.='/';
                   10886:         my $path_and_file = $path_part.$file_part;
                   10887:         if ($path_part eq $path) {
                   10888:             $return_files{$file_part}= 'selected';
                   10889:         }
                   10890:     }
1.574     banghart 10891:     close (IN);
                   10892:     return (\%return_files);
1.572     banghart 10893: }
                   10894: 
                   10895: # called in portfolio select mode, to show files selected NOT in current directory
                   10896: sub files_not_in_path {
                   10897:     my ($user, $path) = @_;
                   10898:     my $filename = $user."savedfiles";
                   10899:     my @return_files;
                   10900:     my $path_part;
1.1359    raeburn  10901:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10902:     while (my $line = <IN>) {
1.572     banghart 10903:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10904:         my @paths_and_file = split(m|/|, $line);
                   10905:         my $file_part = pop(@paths_and_file);
                   10906:         chomp($file_part);
                   10907:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10908:         $path_part .= '/';
                   10909:         my $path_and_file = $path_part.$file_part;
                   10910:         if ($path_part ne $path) {
1.800     albertel 10911:             push(@return_files, ($path_and_file));
1.572     banghart 10912:         }
                   10913:     }
1.800     albertel 10914:     close(OUT);
1.574     banghart 10915:     return (@return_files);
1.572     banghart 10916: }
                   10917: 
1.1273    raeburn  10918: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10919:  
                   10920: sub portfiles_versioning {
                   10921:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10922:     my $portfolio_root = '/userfiles/portfolio';
                   10923:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10924:     foreach my $file (@{$portfiles}) {
                   10925:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10926:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10927:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10928:         my $getpropath = 1;
                   10929:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10930:                                              $stu_name,$getpropath);
                   10931:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10932:         my $new_answer = 
                   10933:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10934:         if ($new_answer ne 'problem getting file') {
                   10935:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10936:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10937:                               [$symb,$env{'request.course.id'},'graded']);
                   10938:         }
                   10939:     }
                   10940: }
                   10941: 
                   10942: sub get_next_version {
                   10943:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10944:     my $version;
                   10945:     if (ref($dir_list) eq 'ARRAY') {
                   10946:         foreach my $row (@{$dir_list}) {
                   10947:             my ($file) = split(/\&/,$row,2);
                   10948:             my ($file_name,$file_version,$file_ext) =
                   10949:                 &file_name_version_ext($file);
                   10950:             if (($file_name eq $answer_name) &&
                   10951:                 ($file_ext eq $answer_ext)) {
                   10952:                      # gets here if filename and extension match,
                   10953:                      # regardless of version
                   10954:                 if ($file_version ne '') {
                   10955:                     # a versioned file is found  so save it for later
                   10956:                     if ($file_version > $version) {
                   10957:                         $version = $file_version;
                   10958:                     }
                   10959:                 }
                   10960:             }
                   10961:         }
                   10962:     }
                   10963:     $version ++;
                   10964:     return($version);
                   10965: }
                   10966: 
                   10967: sub version_selected_portfile {
                   10968:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10969:     my ($answer_name,$answer_ver,$answer_ext) =
                   10970:         &file_name_version_ext($file_name);
                   10971:     my $new_answer;
                   10972:     $env{'form.copy'} =
                   10973:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10974:     if($env{'form.copy'} eq '-1') {
                   10975:         $new_answer = 'problem getting file';
                   10976:     } else {
                   10977:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10978:         my $copy_result = 
                   10979:             &finishuserfileupload($stu_name,$domain,'copy',
                   10980:                                   '/portfolio'.$directory.$new_answer);
                   10981:     }
                   10982:     undef($env{'form.copy'});
                   10983:     return ($new_answer);
                   10984: }
                   10985: 
                   10986: sub file_name_version_ext {
                   10987:     my ($file)=@_;
                   10988:     my @file_parts = split(/\./, $file);
                   10989:     my ($name,$version,$ext);
                   10990:     if (@file_parts > 1) {
                   10991:         $ext=pop(@file_parts);
                   10992:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10993:             $version=pop(@file_parts);
                   10994:         }
                   10995:         $name=join('.',@file_parts);
                   10996:     } else {
                   10997:         $name=join('.',@file_parts);
                   10998:     }
                   10999:     return($name,$version,$ext);
                   11000: }
                   11001: 
1.745     raeburn  11002: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11003: 
1.745     raeburn  11004: sub get_portfile_permissions {
                   11005:     my ($domain,$user) = @_;
1.613     albertel 11006:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11007:     my ($tmp)=keys(%current_permissions);
                   11008:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11009:     return \%current_permissions;
                   11010: }
                   11011: 
                   11012: #---------------------------------------------Get portfolio file access controls
                   11013: 
1.749     raeburn  11014: sub get_access_controls {
1.745     raeburn  11015:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11016:     my %access;
                   11017:     my $real_file = $file;
                   11018:     $file =~ s/\.meta$//;
1.745     raeburn  11019:     if (defined($file)) {
1.749     raeburn  11020:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11021:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11022:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11023:             }
                   11024:         }
1.745     raeburn  11025:     } else {
1.749     raeburn  11026:         foreach my $key (keys(%{$current_permissions})) {
                   11027:             if ($key =~ /\0accesscontrol$/) {
                   11028:                 if (defined($group)) {
                   11029:                     if ($key !~ m-^\Q$group\E/-) {
                   11030:                         next;
                   11031:                     }
                   11032:                 }
                   11033:                 my ($fullpath) = split(/\0/,$key);
                   11034:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11035:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11036:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11037:                     }
                   11038:                 }
                   11039:             }
                   11040:         }
                   11041:     }
                   11042:     return %access;
                   11043: }
                   11044: 
                   11045: sub modify_access_controls {
                   11046:     my ($file_name,$changes,$domain,$user)=@_;
                   11047:     my ($outcome,$deloutcome);
                   11048:     my %store_permissions;
                   11049:     my %new_values;
                   11050:     my %new_control;
                   11051:     my %translation;
                   11052:     my @deletions = ();
                   11053:     my $now = time;
                   11054:     if (exists($$changes{'activate'})) {
                   11055:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11056:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11057:             my $numnew = scalar(@newitems);
                   11058:             for (my $i=0; $i<$numnew; $i++) {
                   11059:                 my $newkey = $newitems[$i];
                   11060:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11061:                 if ($newkey =~ /^\d+:/) { 
                   11062:                     $newkey =~ s/^(\d+)/$newid/;
                   11063:                     $translation{$1} = $newid;
                   11064:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11065:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11066:                     $translation{$1} = $newid;
                   11067:                 }
1.749     raeburn  11068:                 $new_values{$file_name."\0".$newkey} = 
                   11069:                                           $$changes{'activate'}{$newitems[$i]};
                   11070:                 $new_control{$newkey} = $now;
                   11071:             }
                   11072:         }
                   11073:     }
                   11074:     my %todelete;
                   11075:     my %changed_items;
                   11076:     foreach my $action ('delete','update') {
                   11077:         if (exists($$changes{$action})) {
                   11078:             if (ref($$changes{$action}) eq 'HASH') {
                   11079:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11080:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11081:                     if ($action eq 'delete') { 
                   11082:                         $todelete{$itemnum} = 1;
                   11083:                     } else {
                   11084:                         $changed_items{$itemnum} = $key;
                   11085:                     }
                   11086:                 }
1.745     raeburn  11087:             }
                   11088:         }
1.749     raeburn  11089:     }
                   11090:     # get lock on access controls for file.
                   11091:     my $lockhash = {
                   11092:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11093:                                                        ':'.$env{'user.domain'},
                   11094:                    }; 
                   11095:     my $tries = 0;
                   11096:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11097:    
1.1288    damieng  11098:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11099:         $tries ++;
1.1289    damieng  11100:         sleep(0.1);
1.749     raeburn  11101:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11102:     }
                   11103:     if ($gotlock eq 'ok') {
                   11104:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11105:         my ($tmp)=keys(%curr_permissions);
                   11106:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11107:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11108:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11109:             if (ref($curr_controls) eq 'HASH') {
                   11110:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11111:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11112:                     if (defined($todelete{$itemnum})) {
                   11113:                         push(@deletions,$file_name."\0".$control_item);
                   11114:                     } else {
                   11115:                         if (defined($changed_items{$itemnum})) {
                   11116:                             $new_control{$changed_items{$itemnum}} = $now;
                   11117:                             push(@deletions,$file_name."\0".$control_item);
                   11118:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11119:                         } else {
                   11120:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11121:                         }
                   11122:                     }
1.745     raeburn  11123:                 }
                   11124:             }
                   11125:         }
1.970     raeburn  11126:         my ($group);
                   11127:         if (&is_course($domain,$user)) {
                   11128:             ($group,my $file) = split(/\//,$file_name,2);
                   11129:         }
1.749     raeburn  11130:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11131:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11132:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11133:         #  remove lock
                   11134:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11135:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11136:         my $sqlresult =
1.970     raeburn  11137:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11138:                                     $group);
1.749     raeburn  11139:     } else {
                   11140:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11141:     }
1.749     raeburn  11142:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11143: }
                   11144: 
1.827     raeburn  11145: sub make_public_indefinitely {
1.1271    raeburn  11146:     my (@requrl) = @_;
                   11147:     return &automated_portfile_access('public',\@requrl);
                   11148: }
                   11149: 
                   11150: sub automated_portfile_access {
                   11151:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11152:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11153:         return 'invalid';
                   11154:     }
1.1271    raeburn  11155:     my %urls;
                   11156:     if (ref($addsref) eq 'ARRAY') {
                   11157:         foreach my $requrl (@{$addsref}) {
                   11158:             if (&is_portfolio_url($requrl)) {
                   11159:                 unless (exists($urls{$requrl})) {
                   11160:                     $urls{$requrl} = 'add';
                   11161:                 }
                   11162:             }
                   11163:         }
                   11164:     }
                   11165:     if (ref($delsref) eq 'ARRAY') {
                   11166:         foreach my $requrl (@{$delsref}) { 
                   11167:             if (&is_portfolio_url($requrl)) {
                   11168:                 unless (exists($urls{$requrl})) {
                   11169:                     $urls{$requrl} = 'delete'; 
                   11170:                 }
                   11171:             }
                   11172:         }
                   11173:     }
                   11174:     unless (keys(%urls)) {
                   11175:         return 'invalid';
                   11176:     }
                   11177:     my $ip;
                   11178:     if ($accesstype eq 'ip') {
                   11179:         if (ref($info) eq 'HASH') {
                   11180:             if ($info->{'ip'} ne '') {
                   11181:                 $ip = $info->{'ip'};
                   11182:             }
                   11183:         }
                   11184:         if ($ip eq '') {
                   11185:             return 'invalid';
                   11186:         }
                   11187:     }
                   11188:     my $errors;
1.827     raeburn  11189:     my $now = time;
1.1271    raeburn  11190:     my %current_perms;
                   11191:     foreach my $requrl (sort(keys(%urls))) {
                   11192:         my $action;
                   11193:         if ($urls{$requrl} eq 'add') {
                   11194:             $action = 'activate';
                   11195:         } else {
                   11196:             $action = 'none';
                   11197:         }
                   11198:         my $aclnum = 0;
1.827     raeburn  11199:         my (undef,$udom,$unum,$file_name,$group) =
                   11200:             &parse_portfolio_url($requrl);
1.1271    raeburn  11201:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11202:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11203:         }
                   11204:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11205:                                                    $group,$file_name);
                   11206:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11207:             my ($num,$scope,$end,$start) = 
                   11208:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11209:             if ($scope eq $accesstype) {
                   11210:                 if (($start <= $now) && ($end == 0)) {
                   11211:                     if ($accesstype eq 'ip') {
                   11212:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11213:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11214:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11215:                                     if ($urls{$requrl} eq 'add') {
                   11216:                                         $action = 'none';
                   11217:                                         last;
                   11218:                                     } else {
                   11219:                                         $action = 'delete';
                   11220:                                         $aclnum = $num;
                   11221:                                         last;
                   11222:                                     }
                   11223:                                 }
                   11224:                             }
                   11225:                         }
                   11226:                     } elsif ($accesstype eq 'public') {
                   11227:                         if ($urls{$requrl} eq 'add') {
                   11228:                             $action = 'none';
                   11229:                             last;
                   11230:                         } else {
                   11231:                             $action = 'delete';
                   11232:                             $aclnum = $num;
                   11233:                             last;
                   11234:                         }
                   11235:                     }
                   11236:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11237:                     $action = 'update';
                   11238:                     $aclnum = $num;
1.1271    raeburn  11239:                     last;
1.827     raeburn  11240:                 }
                   11241:             }
                   11242:         }
                   11243:         if ($action eq 'none') {
1.1271    raeburn  11244:             next;
1.827     raeburn  11245:         } else {
                   11246:             my %changes;
                   11247:             my $newend = 0;
                   11248:             my $newstart = $now;
1.1271    raeburn  11249:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11250:             $changes{$action}{$newkey} = {
1.1271    raeburn  11251:                 type => $accesstype,
1.827     raeburn  11252:                 time => {
                   11253:                     start => $newstart,
                   11254:                     end   => $newend,
                   11255:                 },
                   11256:             };
1.1271    raeburn  11257:             if ($accesstype eq 'ip') {
                   11258:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11259:             }
1.827     raeburn  11260:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11261:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11262:             unless ($outcome eq 'ok') {
                   11263:                 $errors .= $outcome.' ';
                   11264:             }
1.827     raeburn  11265:         }
1.1271    raeburn  11266:     }
                   11267:     if ($errors) {
                   11268:         $errors =~ s/\s$//;
                   11269:         return $errors;
1.827     raeburn  11270:     } else {
1.1271    raeburn  11271:         return 'ok';
1.827     raeburn  11272:     }
                   11273: }
                   11274: 
1.745     raeburn  11275: #------------------------------------------------------Get Marked as Read Only
                   11276: 
                   11277: sub get_marked_as_readonly {
                   11278:     my ($domain,$user,$what,$group) = @_;
                   11279:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11280:     my @readonly_files;
1.629     banghart 11281:     my $cmp1=$what;
                   11282:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11283:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11284:         if (defined($group)) {
                   11285:             if ($file_name !~ m-^\Q$group\E/-) {
                   11286:                 next;
                   11287:             }
                   11288:         }
1.561     banghart 11289:         if (ref($value) eq "ARRAY"){
                   11290:             foreach my $stored_what (@{$value}) {
1.629     banghart 11291:                 my $cmp2=$stored_what;
1.759     albertel 11292:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11293:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11294:                 }
1.629     banghart 11295:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11296:                     push(@readonly_files, $file_name);
1.745     raeburn  11297:                     last;
1.563     banghart 11298:                 } elsif (!defined($what)) {
                   11299:                     push(@readonly_files, $file_name);
1.745     raeburn  11300:                     last;
1.561     banghart 11301:                 }
                   11302:             }
1.745     raeburn  11303:         }
1.561     banghart 11304:     }
                   11305:     return @readonly_files;
                   11306: }
1.577     banghart 11307: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11308: 
1.577     banghart 11309: sub get_marked_as_readonly_hash {
1.745     raeburn  11310:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11311:     my %readonly_files;
1.745     raeburn  11312:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11313:         if (defined($group)) {
                   11314:             if ($file_name !~ m-^\Q$group\E/-) {
                   11315:                 next;
                   11316:             }
                   11317:         }
1.577     banghart 11318:         if (ref($value) eq "ARRAY"){
                   11319:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11320:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11321:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11322:                         if ($lock_descriptor eq 'graded') {
                   11323:                             $readonly_files{$file_name} = 'graded';
                   11324:                         } elsif ($lock_descriptor eq 'handback') {
                   11325:                             $readonly_files{$file_name} = 'handback';
                   11326:                         } else {
                   11327:                             if (!exists($readonly_files{$file_name})) {
                   11328:                                 $readonly_files{$file_name} = 'locked';
                   11329:                             }
                   11330:                         }
1.745     raeburn  11331:                     }
1.750     banghart 11332:                 } 
1.577     banghart 11333:             }
                   11334:         } 
                   11335:     }
                   11336:     return %readonly_files;
                   11337: }
1.559     banghart 11338: # ------------------------------------------------------------ Unmark as Read Only
                   11339: 
                   11340: sub unmark_as_readonly {
1.629     banghart 11341:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11342:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11343:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11344:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11345:     my $symb_crs = $what;
                   11346:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11347:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11348:     my ($tmp)=keys(%current_permissions);
                   11349:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11350:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11351:     foreach my $file (@readonly_files) {
1.759     albertel 11352: 	my $clean_file = &declutter_portfile($file);
                   11353: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11354: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11355:         my @new_locks;
                   11356:         my @del_keys;
                   11357:         if (ref($current_locks) eq "ARRAY"){
                   11358:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11359:                 my $compare=$locker;
1.749     raeburn  11360:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11361:                     $compare=join('',@{$locker});
1.746     raeburn  11362:                     if ($compare ne $symb_crs) {
                   11363:                         push(@new_locks, $locker);
                   11364:                     }
1.563     banghart 11365:                 }
                   11366:             }
1.650     albertel 11367:             if (scalar(@new_locks) > 0) {
1.563     banghart 11368:                 $current_permissions{$file} = \@new_locks;
                   11369:             } else {
                   11370:                 push(@del_keys, $file);
1.613     albertel 11371:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11372:                 delete($current_permissions{$file});
1.563     banghart 11373:             }
                   11374:         }
1.561     banghart 11375:     }
1.613     albertel 11376:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11377:     return;
                   11378: }
1.512     banghart 11379: 
1.17      www      11380: # ------------------------------------------------------------ Directory lister
                   11381: 
                   11382: sub dirlist {
1.955     raeburn  11383:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11384:     $uri=~s/^\///;
                   11385:     $uri=~s/\/$//;
1.253     stredwic 11386:     my ($udom, $uname);
1.955     raeburn  11387:     if ($getuserdir) {
1.253     stredwic 11388:         $udom = $userdomain;
                   11389:         $uname = $username;
1.955     raeburn  11390:     } else {
                   11391:         (undef,$udom,$uname)=split(/\//,$uri);
                   11392:         if(defined($userdomain)) {
                   11393:             $udom = $userdomain;
                   11394:         }
                   11395:         if(defined($username)) {
                   11396:             $uname = $username;
                   11397:         }
1.253     stredwic 11398:     }
1.955     raeburn  11399:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11400: 
1.955     raeburn  11401:     $dirRoot = $perlvar{'lonDocRoot'};
                   11402:     if (defined($getpropath)) {
                   11403:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11404:         $dirRoot =~ s/\/$//;
1.955     raeburn  11405:     } elsif (defined($getuserdir)) {
                   11406:         my $subdir=$uname.'__';
                   11407:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11408:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11409:                    ."/$udom/$subdir/$uname";
                   11410:     } elsif (defined($alternateRoot)) {
                   11411:         $dirRoot = $alternateRoot;
1.751     banghart 11412:     }
1.253     stredwic 11413: 
                   11414:     if($udom) {
                   11415:         if($uname) {
1.1135    raeburn  11416:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11417:             if ($uhome eq 'no_host') {
                   11418:                 return ([],'no_host');
                   11419:             }
1.955     raeburn  11420:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11421:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11422:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11423:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11424:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11425:             } else {
                   11426:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11427:             }
1.605     matthew  11428:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11429:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11430:                 @listing_results = split(/:/,$listing);
                   11431:             } else {
                   11432:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11433:             }
1.1135    raeburn  11434:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11435:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11436:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11437:                 return ([],$listing);
                   11438:             } else {
                   11439:                 return (\@listing_results);
1.1135    raeburn  11440:             }
1.955     raeburn  11441:         } elsif(!$alternateRoot) {
1.1136    raeburn  11442:             my (%allusers,%listerror);
1.841     albertel 11443: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11444:  	    foreach my $tryserver (keys(%servers)) {
                   11445:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11446:                                   &escape($udom),$tryserver);
                   11447:                 if ($listing eq 'unknown_cmd') {
                   11448: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11449: 				      $udom, $tryserver);
                   11450:                 } else {
                   11451:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11452:                 }
1.841     albertel 11453: 		if ($listing eq 'unknown_cmd') {
                   11454: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11455: 				      $udom, $tryserver);
                   11456: 		    @listing_results = split(/:/,$listing);
                   11457: 		} else {
                   11458: 		    @listing_results =
                   11459: 			map { &unescape($_); } split(/:/,$listing);
                   11460: 		}
1.1136    raeburn  11461:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11462:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11463:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11464:                     $listerror{$tryserver} = $listing;
                   11465:                 } else {
1.841     albertel 11466: 		    foreach my $line (@listing_results) {
                   11467: 			my ($entry) = split(/&/,$line,2);
                   11468: 			$allusers{$entry} = 1;
                   11469: 		    }
                   11470: 		}
1.253     stredwic 11471:             }
1.1136    raeburn  11472:             my @alluserslist=();
1.800     albertel 11473:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11474:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11475:             }
1.1318    droeschl 11476: 
                   11477:             if (!%listerror) {
                   11478:                 # no errors
                   11479:                 return (\@alluserslist);
                   11480:             } elsif (scalar(keys(%servers)) == 1) {
                   11481:                 # one library server, one error 
                   11482:                 my ($key) = keys(%listerror);
                   11483:                 return (\@alluserslist, $listerror{$key});
                   11484:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11485:                 # con_lost indicates that we might miss data from at least one
                   11486:                 # library server
                   11487:                 return (\@alluserslist, 'con_lost');
                   11488:             } else {
                   11489:                 # multiple library servers and no con_lost -> data should be
                   11490:                 # complete. 
                   11491:                 return (\@alluserslist);
                   11492:             }
                   11493: 
1.253     stredwic 11494:         } else {
1.1136    raeburn  11495:             return ([],'missing username');
1.253     stredwic 11496:         }
1.955     raeburn  11497:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11498:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11499:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11500:         return (\@all_domains);
1.955     raeburn  11501:     } else {
1.1136    raeburn  11502:         return ([],'missing domain');
1.275     stredwic 11503:     }
                   11504: }
                   11505: 
                   11506: # --------------------------------------------- GetFileTimestamp
                   11507: # This function utilizes dirlist and returns the date stamp for
                   11508: # when it was last modified.  It will also return an error of -1
                   11509: # if an error occurs
                   11510: 
                   11511: sub GetFileTimestamp {
1.955     raeburn  11512:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11513:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11514:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11515:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11516:                                     undef,$getuserdir);
                   11517:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11518:         return -1;
                   11519:     }
                   11520:     if (ref($fileref) eq 'ARRAY') {
                   11521:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11522:         # @stats contains first the filename, then the stat output
                   11523:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11524:     } else {
                   11525:         return -1;
1.253     stredwic 11526:     }
1.26      www      11527: }
                   11528: 
1.712     albertel 11529: sub stat_file {
                   11530:     my ($uri) = @_;
1.787     albertel 11531:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11532: 
1.955     raeburn  11533:     my ($udom,$uname,$file);
1.712     albertel 11534:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11535: 	($udom,$uname,$file) =
1.811     albertel 11536: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11537: 	$file = 'userfiles/'.$file;
                   11538:     }
                   11539:     if ($uri =~ m-^/res/-) {
                   11540: 	($udom,$uname) = 
1.807     albertel 11541: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11542: 	$file = $uri;
                   11543:     }
                   11544: 
                   11545:     if (!$udom || !$uname || !$file) {
                   11546: 	# unable to handle the uri
                   11547: 	return ();
                   11548:     }
1.956     raeburn  11549:     my $getpropath;
                   11550:     if ($file =~ /^userfiles\//) {
                   11551:         $getpropath = 1;
                   11552:     }
1.1136    raeburn  11553:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11554:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11555:         return ();
                   11556:     } else {
                   11557:         if (ref($listref) eq 'ARRAY') {
                   11558:             my @stats = split('&',$listref->[0]);
                   11559: 	    shift(@stats); #filename is first
                   11560: 	    return @stats;
                   11561:         }
1.712     albertel 11562:     }
                   11563:     return ();
                   11564: }
                   11565: 
1.1313    raeburn  11566: # --------------------------------------------------------- recursedirs
                   11567: # Recursive function to traverse either a specific user's Authoring Space
                   11568: # or corresponding Published Resource Space, and populate the hash ref:
                   11569: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11570: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11571: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11572: # files in Authoring Space.
                   11573: #
                   11574: # Inputs:
                   11575: #
                   11576: # $is_home - true if current server is home server for user's space
                   11577: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11578: # $docroot - Document root (i.e., /home/httpd/html
                   11579: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11580: # $relpath - Current path (relative to top level).
                   11581: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11582: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11583: #
                   11584: # Returns: nothing
                   11585: #
                   11586: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11587: #
                   11588: # Currently used by interface/londocs.pm to create linked select boxes for
                   11589: # directory and filename to import a Course "Author" resource into a course, and
                   11590: # also to create linked select boxes for Authoring Space and Directory to choose
                   11591: # save location for creation of a new "standard" problem from the Course Editor.
                   11592: #
                   11593: 
                   11594: sub recursedirs {
                   11595:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11596:     return unless (ref($dirhashref) eq 'HASH');
                   11597:     my $currpath = $docroot.$toppath;
                   11598:     if ($relpath) {
                   11599:         $currpath .= "/$relpath";
                   11600:     }
                   11601:     my $savefile;
                   11602:     if (ref($filehashref)) {
                   11603:         $savefile = 1;
                   11604:     }
                   11605:     if ($is_home) {
                   11606:         if (opendir(my $dirh,$currpath)) {
                   11607:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11608:                 next if ($item eq '');
                   11609:                 if (-d "$currpath/$item") {
                   11610:                     my $newpath;
                   11611:                     if ($relpath) {
                   11612:                         $newpath = "$relpath/$item";
                   11613:                     } else {
                   11614:                         $newpath = $item;
                   11615:                     }
                   11616:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11617:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11618:                 } elsif ($savefile) {
                   11619:                     if ($context eq 'priv') {
                   11620:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11621:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11622:                         }
                   11623:                     } else {
                   11624:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11625:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11626:                         }
                   11627:                     }
                   11628:                 }
                   11629:             }
                   11630:             closedir($dirh);
                   11631:         }
                   11632:     } else {
                   11633:         my ($dirlistref,$listerror) =
                   11634:             &dirlist($toppath.$relpath);
                   11635:         my @dir_lines;
                   11636:         my $dirptr=16384;
                   11637:         if (ref($dirlistref) eq 'ARRAY') {
                   11638:             foreach my $dir_line (sort
                   11639:                               {
                   11640:                                   my ($afile)=split('&',$a,2);
                   11641:                                   my ($bfile)=split('&',$b,2);
                   11642:                                   return (lc($afile) cmp lc($bfile));
                   11643:                               } (@{$dirlistref})) {
                   11644:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11645:                     split(/\&/,$dir_line,16);
                   11646:                 $item =~ s/\s+$//;
                   11647:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11648:                 if ($dirptr&$testdir) {
                   11649:                     my $newpath;
                   11650:                     if ($relpath) {
                   11651:                         $newpath = "$relpath/$item";
                   11652:                     } else {
                   11653:                         $relpath = '/';
                   11654:                         $newpath = $item;
                   11655:                     }
                   11656:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11657:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11658:                 } elsif ($savefile) {
                   11659:                     if ($context eq 'priv') {
                   11660:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11661:                             $filehashref->{$relpath}{$item} = 1;
                   11662:                         }
                   11663:                     } else {
                   11664:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11665:                             $filehashref->{$relpath}{$item} = 1;
                   11666:                         }
                   11667:                     }
                   11668:                 }
                   11669:             }
                   11670:         }
                   11671:     }
                   11672:     return;
                   11673: }
                   11674: 
1.26      www      11675: # -------------------------------------------------------- Value of a Condition
                   11676: 
1.713     albertel 11677: # gets the value of a specific preevaluated condition
                   11678: #    stored in the string  $env{user.state.<cid>}
                   11679: # or looks up a condition reference in the bighash and if if hasn't
                   11680: # already been evaluated recurses into docondval to get the value of
                   11681: # the condition, then memoizing it to 
                   11682: #   $env{user.state.<cid>.<condition>}
1.40      www      11683: sub directcondval {
                   11684:     my $number=shift;
1.620     albertel 11685:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11686: 	&Apache::lonuserstate::evalstate();
                   11687:     }
1.713     albertel 11688:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11689: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11690:     } elsif ($number =~ /^_/) {
                   11691: 	my $sub_condition;
                   11692: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11693: 		&GDBM_READER(),0640)) {
                   11694: 	    $sub_condition=$bighash{'conditions'.$number};
                   11695: 	    untie(%bighash);
                   11696: 	}
                   11697: 	my $value = &docondval($sub_condition);
1.949     raeburn  11698: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11699: 	return $value;
                   11700:     }
1.620     albertel 11701:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11702:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11703:     } else {
                   11704:        return 2;
                   11705:     }
                   11706: }
                   11707: 
1.713     albertel 11708: # get the collection of conditions for this resource
1.26      www      11709: sub condval {
                   11710:     my $condidx=shift;
1.54      www      11711:     my $allpathcond='';
1.713     albertel 11712:     foreach my $cond (split(/\|/,$condidx)) {
                   11713: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11714: 	    $allpathcond.=
                   11715: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11716: 	}
1.191     harris41 11717:     }
1.54      www      11718:     $allpathcond=~s/\|$//;
1.713     albertel 11719:     return &docondval($allpathcond);
                   11720: }
                   11721: 
                   11722: #evaluates an expression of conditions
                   11723: sub docondval {
                   11724:     my ($allpathcond) = @_;
                   11725:     my $result=0;
                   11726:     if ($env{'request.course.id'}
                   11727: 	&& defined($allpathcond)) {
                   11728: 	my $operand='|';
                   11729: 	my @stack;
                   11730: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11731: 	    if ($chunk eq '(') {
                   11732: 		push @stack,($operand,$result);
                   11733: 	    } elsif ($chunk eq ')') {
                   11734: 		my $before=pop @stack;
                   11735: 		if (pop @stack eq '&') {
                   11736: 		    $result=$result>$before?$before:$result;
                   11737: 		} else {
                   11738: 		    $result=$result>$before?$result:$before;
                   11739: 		}
                   11740: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11741: 		$operand=$chunk;
                   11742: 	    } else {
                   11743: 		my $new=directcondval($chunk);
                   11744: 		if ($operand eq '&') {
                   11745: 		    $result=$result>$new?$new:$result;
                   11746: 		} else {
                   11747: 		    $result=$result>$new?$result:$new;
                   11748: 		}
                   11749: 	    }
                   11750: 	}
1.26      www      11751:     }
                   11752:     return $result;
1.421     albertel 11753: }
                   11754: 
                   11755: # ---------------------------------------------------- Devalidate courseresdata
                   11756: 
                   11757: sub devalidatecourseresdata {
                   11758:     my ($coursenum,$coursedomain)=@_;
                   11759:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11760:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11761: }
                   11762: 
1.763     www      11763: 
1.200     www      11764: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11765: #
                   11766: #  Parameters:
                   11767: #      $coursenum    - Number of the course.
                   11768: #      $coursedomain - Domain at which the course was created.
                   11769: #  Returns:
                   11770: #     A hash of the course parameters along (I think) with timestamps
                   11771: #     and version info.
1.877     foxr     11772: 
1.624     albertel 11773: sub get_courseresdata {
                   11774:     my ($coursenum,$coursedomain)=@_;
1.200     www      11775:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11776:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11777:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11778:     my %dumpreply;
1.417     albertel 11779:     unless (defined($cached)) {
1.624     albertel 11780: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11781: 	$result=\%dumpreply;
1.251     albertel 11782: 	my ($tmp) = keys(%dumpreply);
                   11783: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11784: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11785: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11786: 	    return $tmp;
1.416     albertel 11787: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11788: 	    $result=undef;
1.599     albertel 11789: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11790: 	}
                   11791:     }
1.624     albertel 11792:     return $result;
                   11793: }
                   11794: 
1.633     albertel 11795: sub devalidateuserresdata {
                   11796:     my ($uname,$udom)=@_;
                   11797:     my $hashid="$udom:$uname";
                   11798:     &devalidate_cache_new('userres',$hashid);
                   11799: }
                   11800: 
1.624     albertel 11801: sub get_userresdata {
                   11802:     my ($uname,$udom)=@_;
                   11803:     #most student don\'t have any data set, check if there is some data
                   11804:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11805: 
                   11806:     my $hashid="$udom:$uname";
                   11807:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11808:     if (!defined($cached)) {
                   11809: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11810: 	$result=\%resourcedata;
                   11811: 	&do_cache_new('userres',$hashid,$result,600);
                   11812:     }
                   11813:     my ($tmp)=keys(%$result);
                   11814:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11815: 	return $result;
                   11816:     }
                   11817:     #error 2 occurs when the .db doesn't exist
                   11818:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11819:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11820: 	    &logthis("<font color=\"blue\">WARNING:".
                   11821: 		     " Trying to get resource data for ".
                   11822: 		     $uname." at ".$udom.": ".
                   11823: 		     $tmp."</font>");
                   11824:         }
1.624     albertel 11825:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11826: 	#&EXT_cache_set($udom,$uname);
                   11827: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11828: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11829:     }
                   11830:     return $tmp;
                   11831: }
1.879     foxr     11832: #----------------------------------------------- resdata - return resource data
                   11833: #  Purpose:
                   11834: #    Return resource data for either users or for a course.
                   11835: #  Parameters:
                   11836: #     $name      - Course/user name.
                   11837: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11838: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11839: #     $mapp      - decluttered URL of enclosing map  
                   11840: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11841: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11842: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11843: #     $courseid  - CourseID (first part of param identifier).
                   11844: #     $modifier  - Middle part of param identifier.
                   11845: #     $what      - Last part of param identifier.
1.879     foxr     11846: #     @which     - Array of names of resources desired.
                   11847: #  Returns:
                   11848: #     The value of the first reasource in @which that is found in the
                   11849: #     resource hash.
                   11850: #  Exceptional Conditions:
                   11851: #     If the $type passed in is not valid (not the string 'course' or 
                   11852: #     'user', an undefined  reference is returned.
                   11853: #     If none of the resources are found, an undef is returned
1.624     albertel 11854: sub resdata {
1.1301    raeburn  11855:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11856:         $modifier,$what,@which)=@_;
1.624     albertel 11857:     my $result;
                   11858:     if ($type eq 'course') {
                   11859: 	$result=&get_courseresdata($name,$domain);
                   11860:     } elsif ($type eq 'user') {
                   11861: 	$result=&get_userresdata($name,$domain);
                   11862:     }
                   11863:     if (!ref($result)) { return $result; }    
1.251     albertel 11864:     foreach my $item (@which) {
1.1301    raeburn  11865:         if ($item->[1] eq 'course') {
                   11866:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11867:                 unless ($$recursed) {
1.1302    raeburn  11868:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11869:                     $$recursed = 1;
                   11870:                 }
                   11871:                 foreach my $item (@${recurseup}) {
                   11872:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11873:                     last if (defined($result->{$norecursechk}));
                   11874:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11875:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11876:                 }
                   11877:             }
                   11878:         }
                   11879:         if (defined($result->{$item->[0]})) {
1.927     albertel 11880: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11881: 	}
1.250     albertel 11882:     }
1.291     albertel 11883:     return undef;
1.200     www      11884: }
                   11885: 
1.1360    raeburn  11886: sub get_domain_lti {
                   11887:     my ($cdom,$context) = @_;
                   11888:     my ($name,%lti);
                   11889:     if ($context eq 'consumer') {
                   11890:         $name = 'ltitools';
                   11891:     } elsif ($context eq 'provider') {
                   11892:         $name = 'lti';
                   11893:     } else {
                   11894:         return %lti;
                   11895:     }
                   11896:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11897:     if (defined($cached)) {
                   11898:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11899:             %lti = %{$result};
1.1298    raeburn  11900:         }
                   11901:     } else {
1.1360    raeburn  11902:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11903:         if (ref($domconfig{$name}) eq 'HASH') {
                   11904:             %lti = %{$domconfig{$name}};
                   11905:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11906:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11907:                 foreach my $id (keys(%lti)) {
                   11908:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11909:                         foreach my $item ('key','secret') {
1.1360    raeburn  11910:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11911:                         }
                   11912:                     }
                   11913:                 }
                   11914:             }
1.1298    raeburn  11915:         }
                   11916:         my $cachetime = 24*60*60;
1.1360    raeburn  11917:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11918:     }
1.1360    raeburn  11919:     return %lti;
1.1298    raeburn  11920: }
                   11921: 
1.1236    raeburn  11922: sub get_numsuppfiles {
                   11923:     my ($cnum,$cdom,$ignorecache)=@_;
                   11924:     my $hashid=$cnum.':'.$cdom;
                   11925:     my ($suppcount,$cached);
                   11926:     unless ($ignorecache) {
                   11927:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11928:     }
                   11929:     unless (defined($cached)) {
                   11930:         my $chome=&homeserver($cnum,$cdom);
                   11931:         unless ($chome eq 'no_host') {
1.1366    raeburn  11932:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11933:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11934:             ($suppcount,$supptools,$errors) =
                   11935:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11936:                                                          $supptools,$errors);
1.1236    raeburn  11937:         }
                   11938:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11939:     }
                   11940:     return $suppcount;
                   11941: }
                   11942: 
1.379     matthew  11943: #
                   11944: # EXT resource caching routines
                   11945: #
                   11946: 
1.1302    raeburn  11947: {
                   11948: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11949: #
                   11950: # The course for which we cache
                   11951: my $cachedmapkey='';
                   11952: # The cached recursive maps for this course
                   11953: my %cachedmaps=();
                   11954: # When this was last done
                   11955: my $cachedmaptime='';
                   11956: 
1.379     matthew  11957: sub clear_EXT_cache_status {
1.383     albertel 11958:     &delenv('cache.EXT.');
1.379     matthew  11959: }
                   11960: 
                   11961: sub EXT_cache_status {
                   11962:     my ($target_domain,$target_user) = @_;
1.383     albertel 11963:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11964:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11965:         # We know already the user has no data
                   11966:         return 1;
                   11967:     } else {
                   11968:         return 0;
                   11969:     }
                   11970: }
                   11971: 
                   11972: sub EXT_cache_set {
                   11973:     my ($target_domain,$target_user) = @_;
1.383     albertel 11974:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11975:     #&appenv({$cachename => time});
1.379     matthew  11976: }
                   11977: 
1.28      www      11978: # --------------------------------------------------------- Value of a Variable
1.58      www      11979: sub EXT {
1.715     albertel 11980: 
1.1228    raeburn  11981:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11982:     unless ($varname) { return ''; }
1.218     albertel 11983:     #get real user name/domain, courseid and symb
                   11984:     my $courseid;
1.359     albertel 11985:     my $publicuser;
1.427     www      11986:     if ($symbparm) {
                   11987: 	$symbparm=&get_symb_from_alias($symbparm);
                   11988:     }
1.218     albertel 11989:     if (!($uname && $udom)) {
1.790     albertel 11990:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11991:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11992:     } else {
1.620     albertel 11993: 	$courseid=$env{'request.course.id'};
1.218     albertel 11994:     }
1.48      www      11995:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11996:     my $rest;
1.320     albertel 11997:     if (defined($therest[0])) {
1.48      www      11998:        $rest=join('.',@therest);
                   11999:     } else {
                   12000:        $rest='';
                   12001:     }
1.320     albertel 12002: 
1.57      www      12003:     my $qualifierrest=$qualifier;
                   12004:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12005:     my $spacequalifierrest=$space;
                   12006:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12007:     if ($realm eq 'user') {
1.48      www      12008: # --------------------------------------------------------------- user.resource
                   12009: 	if ($space eq 'resource') {
1.651     albertel 12010: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12011: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12012: 		 &&
1.744     albertel 12013: 		 ($symbparm eq &symbread()) ) {	
                   12014: 		# if we are in the middle of processing the resource the
                   12015: 		# get the value we are planning on committing
                   12016:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12017:                     return $Apache::lonhomework::results{$qualifierrest};
                   12018:                 } else {
                   12019:                     return $Apache::lonhomework::history{$qualifierrest};
                   12020:                 }
1.335     albertel 12021: 	    } else {
1.359     albertel 12022: 		my %restored;
1.620     albertel 12023: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12024: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12025: 		} else {
                   12026: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12027: 		}
1.335     albertel 12028: 		return $restored{$qualifierrest};
                   12029: 	    }
1.48      www      12030: # ----------------------------------------------------------------- user.access
                   12031:         } elsif ($space eq 'access') {
1.218     albertel 12032: 	    # FIXME - not supporting calls for a specific user
1.48      www      12033:             return &allowed($qualifier,$rest);
                   12034: # ------------------------------------------ user.preferences, user.environment
                   12035:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12036: 	    if (($uname eq $env{'user.name'}) &&
                   12037: 		($udom eq $env{'user.domain'})) {
                   12038: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12039: 	    } else {
1.359     albertel 12040: 		my %returnhash;
                   12041: 		if (!$publicuser) {
                   12042: 		    %returnhash=&userenvironment($udom,$uname,
                   12043: 						 $qualifierrest);
                   12044: 		}
1.218     albertel 12045: 		return $returnhash{$qualifierrest};
                   12046: 	    }
1.48      www      12047: # ----------------------------------------------------------------- user.course
                   12048:         } elsif ($space eq 'course') {
1.218     albertel 12049: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12050:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12051: # ------------------------------------------------------------------- user.role
                   12052:         } elsif ($space eq 'role') {
1.218     albertel 12053: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12054:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12055:             if ($qualifier eq 'value') {
                   12056: 		return $role;
                   12057:             } elsif ($qualifier eq 'extent') {
                   12058:                 return $where;
                   12059:             }
                   12060: # ----------------------------------------------------------------- user.domain
                   12061:         } elsif ($space eq 'domain') {
1.218     albertel 12062:             return $udom;
1.48      www      12063: # ------------------------------------------------------------------- user.name
                   12064:         } elsif ($space eq 'name') {
1.218     albertel 12065:             return $uname;
1.48      www      12066: # ---------------------------------------------------- Any other user namespace
1.29      www      12067:         } else {
1.359     albertel 12068: 	    my %reply;
                   12069: 	    if (!$publicuser) {
                   12070: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12071: 	    }
                   12072: 	    return $reply{$qualifierrest};
1.48      www      12073:         }
1.236     www      12074:     } elsif ($realm eq 'query') {
                   12075: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12076:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12077: 						[$spacequalifierrest]);
1.620     albertel 12078: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12079:    } elsif ($realm eq 'request') {
1.48      www      12080: # ------------------------------------------------------------- request.browser
                   12081:         if ($space eq 'browser') {
1.1145    bisitz   12082:             return $env{'browser.'.$qualifier};
1.57      www      12083: # ------------------------------------------------------------ request.filename
                   12084:         } else {
1.620     albertel 12085:             return $env{'request.'.$spacequalifierrest};
1.29      www      12086:         }
1.28      www      12087:     } elsif ($realm eq 'course') {
1.48      www      12088: # ---------------------------------------------------------- course.description
1.620     albertel 12089:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12090:     } elsif ($realm eq 'resource') {
1.165     www      12091: 
1.620     albertel 12092: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12093: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12094: 	}
1.693     albertel 12095: 
1.1232    raeburn  12096:         if ($qualifier eq '') {
                   12097: 	    if ($space eq 'title') {
                   12098: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12099: 	        return &gettitle($symbparm);
                   12100: 	    }
1.693     albertel 12101: 	
1.1232    raeburn  12102: 	    if ($space eq 'map') {
                   12103: 	        my ($map) = &decode_symb($symbparm);
                   12104: 	        return &symbread($map);
                   12105: 	    }
                   12106:             if ($space eq 'maptitle') {
                   12107:                 my ($map) = &decode_symb($symbparm);
                   12108:                 return &gettitle($map);
                   12109:             }
                   12110: 	    if ($space eq 'filename') {
                   12111: 	        if ($symbparm) {
                   12112: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12113: 	        }
                   12114: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12115: 	    }
1.1232    raeburn  12116: 
1.1233    raeburn  12117:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12118:                 if ($space eq 'visibleparts') {
                   12119:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12120:                     my $item;
                   12121:                     if (ref($navmap)) {
                   12122:                         my $res = $navmap->getBySymb($symbparm);
                   12123:                         my $parts = $res->parts();
                   12124:                         if (ref($parts) eq 'ARRAY') {
                   12125:                             $item = join(',',@{$parts});
                   12126:                         }
                   12127:                         undef($navmap);
1.1232    raeburn  12128:                     }
1.1233    raeburn  12129:                     return $item;
1.1232    raeburn  12130:                 }
                   12131:             }
                   12132:         }
1.693     albertel 12133: 
1.1301    raeburn  12134: 	my ($section, $group, @groups, @recurseup, $recursed);
                   12135: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12136:         if (($courseid eq '') && ($cid)) {
                   12137:             $courseid = $cid;
                   12138:         }
                   12139: 	if (($symbparm && $courseid) && 
                   12140: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12141: 
1.218     albertel 12142: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12143: 
1.60      www      12144: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12145: 	    my $symbp=$symbparm;
1.1301    raeburn  12146: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12147: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12148:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12149: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12150: 	    if (($env{'user.name'} eq $uname) &&
                   12151: 		($env{'user.domain'} eq $udom)) {
                   12152: 		$section=$env{'request.course.sec'};
1.733     raeburn  12153:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12154:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12155: 	    } else {
1.539     albertel 12156: 		if (! defined($usection)) {
1.551     albertel 12157: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12158: 		} else {
                   12159: 		    $section = $usection;
                   12160: 		}
1.733     raeburn  12161:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12162: 	    }
                   12163: 
                   12164: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12165: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12166:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12167: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12168: 
1.593     albertel 12169: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12170: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12171:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12172: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12173: 
1.60      www      12174: # ----------------------------------------------------------- first, check user
1.624     albertel 12175: 
1.1301    raeburn  12176: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12177:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12178: 				       ([$courselevelr,'resource'],
                   12179: 					[$courselevelm,'map'     ],
1.1301    raeburn  12180:                                         [$courseleveli,'map'     ],
1.927     albertel 12181: 					[$courselevel, 'course'  ]));
1.931     albertel 12182: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12183: 
1.594     albertel 12184: # ------------------------------------------------ second, check some of course
1.684     raeburn  12185:             my $coursereply;
1.691     raeburn  12186:             if (@groups > 0) {
                   12187:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12188:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12189:                                        $mapp,\$recursed,\@recurseup);
                   12190:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12191:             }
1.96      www      12192: 
1.684     raeburn  12193: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12194: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12195: 				  'course',$mapp,\$recursed,\@recurseup,
                   12196:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12197: 				  ([$seclevelr,   'resource'],
                   12198: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12199:                                    [$secleveli,   'map'     ],
1.927     albertel 12200: 				   [$seclevel,    'course'  ],
                   12201: 				   [$courselevelr,'resource']));
                   12202: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12203: 
1.60      www      12204: # ------------------------------------------------------ third, check map parms
1.218     albertel 12205: 	    my %parmhash=();
                   12206: 	    my $thisparm='';
                   12207: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12208: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12209: 		    &GDBM_READER(),0640)) {
1.218     albertel 12210: 		$thisparm=$parmhash{$symbparm};
                   12211: 		untie(%parmhash);
                   12212: 	    }
1.927     albertel 12213: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12214: 	}
1.594     albertel 12215: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12216:  
                   12217:         my $what = $spacequalifierrest;
                   12218: 	$what=~s/\./\_/;
1.282     albertel 12219: 	my $filename;
                   12220: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12221: 	if ($symbparm) {
1.409     www      12222: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12223: 	} else {
1.620     albertel 12224: 	    $filename=$env{'request.filename'};
1.282     albertel 12225: 	}
1.1362    raeburn  12226:         my $toolsymb;
                   12227:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12228:             $toolsymb = $symbparm;
                   12229:         }
                   12230: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12231: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12232: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12233: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12234: 
1.1301    raeburn  12235: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12236: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12237: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12238: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12239: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12240: 				     'course',$mapp,\$recursed,\@recurseup,
                   12241:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12242: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12243:                                       [$courseleveli,'map'   ],
1.927     albertel 12244: 				      [$courselevel, 'course']));
                   12245: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12246: 	}
1.145     www      12247: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12248: 	unless ($space eq '0') {
1.336     albertel 12249: 	    my @parts=split(/_/,$space);
                   12250: 	    my $id=pop(@parts);
                   12251: 	    my $part=join('_',@parts);
                   12252: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12253: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12254: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12255: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12256: 	}
1.395     albertel 12257: 	if ($recurse) { return undef; }
1.1362    raeburn  12258: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12259: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12260: # ---------------------------------------------------- Any other user namespace
                   12261:     } elsif ($realm eq 'environment') {
                   12262: # ----------------------------------------------------------------- environment
1.620     albertel 12263: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12264: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12265: 	} else {
1.770     albertel 12266: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12267: 		return '';
                   12268: 	    }
1.219     albertel 12269: 	    my %returnhash=&userenvironment($udom,$uname,
                   12270: 					    $spacequalifierrest);
                   12271: 	    return $returnhash{$spacequalifierrest};
                   12272: 	}
1.28      www      12273:     } elsif ($realm eq 'system') {
1.48      www      12274: # ----------------------------------------------------------------- system.time
                   12275: 	if ($space eq 'time') {
                   12276: 	    return time;
                   12277:         }
1.696     albertel 12278:     } elsif ($realm eq 'server') {
                   12279: # ----------------------------------------------------------------- system.time
                   12280: 	if ($space eq 'name') {
                   12281: 	    return $ENV{'SERVER_NAME'};
                   12282:         }
1.1415  ! raeburn  12283:     } elsif ($realm eq 'client') {
        !          12284:         if ($space eq 'remote_addr') {
        !          12285:             return $ENV{'REMOTE_ADDR'};
        !          12286:         }
1.28      www      12287:     }
1.48      www      12288:     return '';
1.61      www      12289: }
                   12290: 
1.927     albertel 12291: sub get_reply {
                   12292:     my ($reply_value) = @_;
1.940     raeburn  12293:     if (ref($reply_value) eq 'ARRAY') {
                   12294:         if (wantarray) {
                   12295: 	    return @$reply_value;
                   12296:         }
                   12297:         return $reply_value->[0];
                   12298:     } else {
                   12299:         return $reply_value;
1.927     albertel 12300:     }
                   12301: }
                   12302: 
1.691     raeburn  12303: sub check_group_parms {
1.1301    raeburn  12304:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12305:         $recursed,$recurseupref) = @_;
                   12306:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12307:                   [$what,'course']);
                   12308:     my $coursereply;
1.691     raeburn  12309:     foreach my $group (@{$groups}) {
1.1301    raeburn  12310:         my @groupitems = ();
1.691     raeburn  12311:         foreach my $level (@levels) {
1.927     albertel 12312:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12313:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12314:         }
1.1301    raeburn  12315:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12316:                                    $env{'course.'.$courseid.'.domain'},
                   12317:                                    'course',$mapp,$recursed,$recurseupref,
                   12318:                                    $courseid,'.['.$group.'].',$what,
                   12319:                                    @groupitems);
                   12320:         last if (defined($coursereply));
1.691     raeburn  12321:     }
                   12322:     return $coursereply;
                   12323: }
                   12324: 
1.1301    raeburn  12325: sub get_map_hierarchy {
1.1302    raeburn  12326:     my ($mapname,$courseid) = @_;
                   12327:     my @recurseup = ();
1.1301    raeburn  12328:     if ($mapname) {
1.1302    raeburn  12329:         if (($cachedmapkey eq $courseid) &&
                   12330:             (abs($cachedmaptime-time)<5)) {
                   12331:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12332:                 return @{$cachedmaps{$mapname}};
                   12333:             }
                   12334:         }
1.1301    raeburn  12335:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12336:         if (ref($navmap)) {
                   12337:             @recurseup = $navmap->recurseup_maps($mapname);
                   12338:             undef($navmap);
1.1302    raeburn  12339:             $cachedmaps{$mapname} = \@recurseup;
                   12340:             $cachedmaptime=time;
                   12341:             $cachedmapkey=$courseid;
1.1301    raeburn  12342:         }
                   12343:     }
                   12344:     return @recurseup;
                   12345: }
                   12346: 
1.1302    raeburn  12347: }
                   12348: 
1.691     raeburn  12349: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12350:     my ($courseid,@groups) = @_;
                   12351:     @groups = sort(@groups);
1.691     raeburn  12352:     return @groups;
                   12353: }
                   12354: 
1.395     albertel 12355: sub packages_tab_default {
1.1362    raeburn  12356:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12357:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12358: 
                   12359:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12360:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12361: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12362: 	if ($pack_type eq 'default') {
                   12363: 	    $do_default=1;
                   12364: 	} elsif ($pack_type eq 'extension') {
                   12365: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12366: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12367: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12368: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12369: 	}
                   12370:     }
                   12371:     # first look for a package that matches the requested part id
                   12372:     foreach my $package (@specifics) {
                   12373: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12374: 	next if ($pack_part ne $part);
                   12375: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12376: 	    return $packagetab{"$pack_type&$name&default"};
                   12377: 	}
                   12378:     }
                   12379:     # look for any possible matching non extension_ package
                   12380:     foreach my $package (@specifics) {
                   12381: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12382: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12383: 	    return $packagetab{"$pack_type&$name&default"};
                   12384: 	}
1.585     albertel 12385: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12386: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12387: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12388: 	}
                   12389:     }
1.738     albertel 12390:     # look for any posible extension_ match
                   12391:     foreach my $package (@extension) {
                   12392: 	my ($package,$pack_type)=@{$package};
                   12393: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12394: 	    return $packagetab{"$pack_type&$name&default"};
                   12395: 	}
                   12396: 	if (defined($packagetab{$package."&$name&default"})) {
                   12397: 	    return $packagetab{$package."&$name&default"};
                   12398: 	}
                   12399:     }
                   12400:     # look for a global default setting
                   12401:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12402: 	return $packagetab{"default&$name&default"};
                   12403:     }
1.395     albertel 12404:     return undef;
                   12405: }
                   12406: 
1.334     albertel 12407: sub add_prefix_and_part {
                   12408:     my ($prefix,$part)=@_;
                   12409:     my $keyroot;
                   12410:     if (defined($prefix) && $prefix !~ /^__/) {
                   12411: 	# prefix that has a part already
                   12412: 	$keyroot=$prefix;
                   12413:     } elsif (defined($prefix)) {
                   12414: 	# prefix that is missing a part
                   12415: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12416:     } else {
                   12417: 	# no prefix at all
                   12418: 	if (defined($part)) { $keyroot='_'.$part; }
                   12419:     }
                   12420:     return $keyroot;
                   12421: }
                   12422: 
1.71      www      12423: # ---------------------------------------------------------------- Get metadata
                   12424: 
1.599     albertel 12425: my %metaentry;
1.1070    www      12426: my %importedpartids;
1.1369    raeburn  12427: my %importedrespids;
1.71      www      12428: sub metadata {
1.1362    raeburn  12429:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12430:     $uri=&declutter($uri);
1.288     albertel 12431:     # if it is a non metadata possible uri return quickly
1.529     albertel 12432:     if (($uri eq '') || 
                   12433: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12434: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12435:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12436: 	return undef;
                   12437:     }
1.1261    raeburn  12438:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12439: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12440: 	return undef;
1.288     albertel 12441:     }
1.73      www      12442:     my $filename=$uri;
                   12443:     $uri=~s/\.meta$//;
1.172     www      12444: #
                   12445: # Is the metadata already cached?
1.177     www      12446: # Look at timestamp of caching
1.172     www      12447: # Everything is cached by the main uri, libraries are never directly cached
                   12448: #
1.428     albertel 12449:     if (!defined($liburi)) {
1.599     albertel 12450: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12451: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12452:     }
1.1362    raeburn  12453: 
                   12454: #
                   12455: # If the uri is for an external tool the file from
                   12456: # which metadata should be retrieved depends on whether
                   12457: # the tool had been configured to be gradable (set in the Course
                   12458: # Editor or Resource Editor).
                   12459: #
                   12460: # If a valid symb has been included as the third arg in the call
                   12461: # to &metadata() that can be used to retrieve the value of
                   12462: # parameter_0_gradable set for the resource, and included in the
                   12463: # uploaded map containing the tool. The value is retrieved via
                   12464: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12465: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12466: # is retrieved via &get().
                   12467: #
                   12468: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12469: # hiddenresource and encrypturl (during course initialization)
                   12470: # the map-level parameter for resource.0.gradable included in the 
                   12471: # uploaded map containing the tool will not yet have been stored
                   12472: # in the user_course_parms.db file for the user's session, so in 
                   12473: # this case fall back to retrieving gradable status from the
                   12474: # exttool_$marker.db file.
1.1362    raeburn  12475: #
                   12476: # In order to avoid an infinite loop, &metadata() will return
                   12477: # before a call to &EXT(), if the uri is for an external tool
                   12478: # and the $what for which metadata is being requested is
                   12479: # parameter_0_gradable or 0_gradable.
                   12480: #
                   12481: 
                   12482:     if ($uri =~ /ext\.tool$/) {
                   12483:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12484:             return;
                   12485:         } else {
                   12486:             my ($checked,$use_passback);
                   12487:             if ($toolsymb ne '') {
                   12488:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12489:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12490:                     $checked = 1;
                   12491:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12492:                         $use_passback = 1;
                   12493:                     }
                   12494:                 }
                   12495:             }
                   12496:             unless ($checked) {
                   12497:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12498:                 $marker=~s/\D//g;
1.1363    raeburn  12499:                 if ($marker) {
1.1362    raeburn  12500:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12501:                     $use_passback = $toolsettings{'gradable'};
                   12502:                 }
                   12503:             }
                   12504:             if ($use_passback) {
                   12505:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12506:             } else {
                   12507:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12508:             }
                   12509:         }
                   12510:     }
                   12511: 
1.428     albertel 12512:     {
1.1069    www      12513: # Imported parts would go here
1.1369    raeburn  12514:         my @origfiletagids=();
1.1069    www      12515:         my $importedparts=0;
1.1369    raeburn  12516: 
                   12517: # Imported responseids would go here
                   12518:         my $importedresponses=0;
1.172     www      12519: #
                   12520: # Is this a recursive call for a library?
                   12521: #
1.599     albertel 12522: #	if (! exists($metacache{$uri})) {
                   12523: #	    $metacache{$uri}={};
                   12524: #	}
1.924     albertel 12525: 	my $cachetime = 60*60;
1.171     www      12526:         if ($liburi) {
                   12527: 	    $liburi=&declutter($liburi);
                   12528:             $filename=$liburi;
1.401     bowersj2 12529:         } else {
1.599     albertel 12530: 	    &devalidate_cache_new('meta',$uri);
                   12531: 	    undef(%metaentry);
1.401     bowersj2 12532: 	}
1.140     www      12533:         my %metathesekeys=();
1.73      www      12534:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12535: 	my $metastring;
1.1140    www      12536: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12537: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12538: 	    $metastring = 
1.929     albertel 12539: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12540: 					  ('grade_target' => 'meta'));
                   12541: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12542: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12543:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12544: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12545: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12546: 	    $metastring=&getfile($file);
1.489     albertel 12547: 	}
1.208     albertel 12548:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12549:         my $token;
1.140     www      12550:         undef %metathesekeys;
1.71      www      12551:         while ($token=$parser->get_token) {
1.339     albertel 12552: 	    if ($token->[0] eq 'S') {
                   12553: 		if (defined($token->[2]->{'package'})) {
1.172     www      12554: #
                   12555: # This is a package - get package info
                   12556: #
1.339     albertel 12557: 		    my $package=$token->[2]->{'package'};
                   12558: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12559: 		    if (defined($token->[2]->{'id'})) { 
                   12560: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12561: 		    }
1.599     albertel 12562: 		    if ($metaentry{':packages'}) {
                   12563: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12564: 		    } else {
1.599     albertel 12565: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12566: 		    }
1.736     albertel 12567: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12568: 			my $part=$keyroot;
                   12569: 			$part=~s/^\_//;
1.736     albertel 12570: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12571: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12572: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12573: 			    # ignore package.tab specified default values
                   12574:                             # here &package_tab_default() will fetch those
                   12575: 			    if ($subp eq 'default') { next; }
1.736     albertel 12576: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12577: 			    my $unikey;
                   12578: 			    if ($pack =~ /_0$/) {
                   12579: 				$unikey='parameter_0_'.$name;
                   12580: 				$part=0;
                   12581: 			    } else {
                   12582: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12583: 			    }
1.339     albertel 12584: 			    if ($subp eq 'display') {
                   12585: 				$value.=' [Part: '.$part.']';
                   12586: 			    }
1.599     albertel 12587: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12588: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12589: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12590: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12591: 			    }
1.599     albertel 12592: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12593: 				$metaentry{':'.$unikey}=
                   12594: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12595: 			    }
1.339     albertel 12596: 			}
                   12597: 		    }
                   12598: 		} else {
1.172     www      12599: #
                   12600: # This is not a package - some other kind of start tag
1.339     albertel 12601: #
                   12602: 		    my $entry=$token->[1];
1.1068    www      12603: 		    my $unikey='';
1.175     www      12604: 
1.339     albertel 12605: 		    if ($entry eq 'import') {
1.175     www      12606: #
                   12607: # Importing a library here
1.339     albertel 12608: #
1.1067    www      12609:                         my $location=$parser->get_text('/import');
                   12610:                         my $dir=$filename;
                   12611:                         $dir=~s|[^/]*$||;
                   12612:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12613: 
                   12614:                         my $importid=$token->[2]->{'id'};
1.1068    www      12615:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12616: #
                   12617: # Check metadata for imported file to
                   12618: # see if it contained response items
                   12619: #
1.1372    raeburn  12620:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12621:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12622:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12623:                                                            $depthcount+1));
                   12624:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12625:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12626:                                                              undef,$depthcount+1);
                   12627:                             if ($libresponseorder ne '') {
                   12628:                                 if ($#origfiletagids<0) {
                   12629:                                     undef(%importedrespids);
                   12630:                                     undef(%importedpartids);
                   12631:                                 }
1.1373    raeburn  12632:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12633:                                 if (@respids) {
                   12634:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12635:                                 }
                   12636:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12637:                                     $importedresponses = 1;
1.1369    raeburn  12638: # We need to get the original file and the imported file to get the response order correct
                   12639: # Load and inspect original file
1.1372    raeburn  12640:                                     if ($#origfiletagids<0) {
                   12641:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12642:                                         $origfile=&getfile($origfilelocation);
                   12643:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12644:                                     }
1.1369    raeburn  12645:                                 }
                   12646:                             }
                   12647:                         }
1.1370    raeburn  12648: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12649: # hash populated for imported library file
                   12650:                         %metaentry = %currmetaentry;
                   12651:                         undef(%currmetaentry);
1.1374    raeburn  12652:                         if ($importmode eq 'part') {
1.1068    www      12653: # Import as part(s)
1.1069    www      12654:                            $importedparts=1;
                   12655: # We need to get the original file and the imported file to get the part order correct
                   12656: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12657: # Load and inspect original file if we didn't do that already
                   12658:                            if ($#origfiletagids<0) {
                   12659:                                undef(%importedrespids);
                   12660:                                undef(%importedpartids);
                   12661:                                if ($origfile eq '') {
                   12662:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12663:                                    $origfile=&getfile($origfilelocation);
                   12664:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12665:                                }
1.1070    www      12666:                            }
1.1372    raeburn  12667:                            my @impfilepartids;
                   12668: # If <partorder> tag is included in metadata for the imported file
                   12669: # get the parts in the imported file from that.
                   12670:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12671:                                %currmetaentry = %metaentry;
                   12672:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12673:                                                             $depthcount+1);
                   12674:                                %metaentry = %currmetaentry;
                   12675:                                undef(%currmetaentry);
                   12676:                                if ($libpartorder ne '') {
                   12677:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12678:                                }
                   12679:                            } else {
                   12680: # If no <partorder> tag available, load and inspect imported file
                   12681:                                my $impfile=&getfile($location);
                   12682:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12683:                            }
1.1069    www      12684:                            if ($#impfilepartids>=0) {
                   12685: # This problem had parts
1.1070    www      12686:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12687:                            } else {
                   12688: # Importing by turning a single problem into a problem part
                   12689: # It gets the import-tags ID as part-ID
                   12690:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12691:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12692:                            }
1.1068    www      12693:                         } else {
1.1374    raeburn  12694: # Import as problem or as normal import
                   12695:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12696:                             unless ($importmode eq 'problem') {
1.1068    www      12697: # Normal import
1.1374    raeburn  12698:                                 if (defined($token->[2]->{'id'})) {
                   12699:                                     $unikey.='_'.$token->[2]->{'id'};
                   12700:                                 }
                   12701:                             }
                   12702: # Check metadata for imported file to
                   12703: # see if it contained parts
                   12704:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12705:                                 %currmetaentry = %metaentry;
                   12706:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12707:                                                              $depthcount+1);
                   12708:                                 %metaentry = %currmetaentry;
                   12709:                                 undef(%currmetaentry);
                   12710:                                 if ($libpartorder ne '') {
                   12711:                                     $importedparts = 1;
                   12712:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12713:                                 }
                   12714:                             }
1.1067    www      12715:                         }
1.339     albertel 12716: 			if ($depthcount<20) {
1.736     albertel 12717: 			    my $metadata = 
1.1362    raeburn  12718: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12719: 					  $depthcount+1);
                   12720: 			    foreach my $meta (split(',',$metadata)) {
                   12721: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12722: 				$metathesekeys{$meta}=1;
1.339     albertel 12723: 			    }
1.1068    www      12724:                         }
1.1067    www      12725: 		    } else {
                   12726: #
                   12727: # Not importing, some other kind of non-package, non-library start tag
                   12728: # 
                   12729:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12730:                         if (defined($token->[2]->{'id'})) {
                   12731:                             $unikey.='_'.$token->[2]->{'id'};
                   12732:                         }
1.339     albertel 12733: 			if (defined($token->[2]->{'name'})) { 
                   12734: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12735: 			}
                   12736: 			$metathesekeys{$unikey}=1;
1.736     albertel 12737: 			foreach my $param (@{$token->[3]}) {
                   12738: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12739: 				$token->[2]->{$param};
1.339     albertel 12740: 			}
                   12741: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12742: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12743: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12744: 		 # only ws inside the tag, and not in default, so use default
                   12745: 		 # as value
1.599     albertel 12746: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12747: 			} elsif ( $internaltext =~ /\S/ ) {
                   12748: 		  # something interesting inside the tag
                   12749: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12750: 			} else {
1.908     albertel 12751: 		  # no interesting values, don't set a default
1.339     albertel 12752: 			}
1.172     www      12753: # end of not-a-package not-a-library import
1.339     albertel 12754: 		    }
1.172     www      12755: # end of not-a-package start tag
1.339     albertel 12756: 		}
1.172     www      12757: # the next is the end of "start tag"
1.339     albertel 12758: 	    }
                   12759: 	}
1.483     albertel 12760: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12761: 	$extension = lc($extension);
                   12762: 	if ($extension eq 'htm') { $extension='html'; }
                   12763: 
1.737     albertel 12764: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12765: 	    #no specific packages #how's our extension
                   12766: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12767: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12768: 					 \%metathesekeys);
                   12769: 	}
1.883     albertel 12770: 
                   12771: 	if (!exists($metaentry{':packages'})
                   12772: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12773: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12774: 		#no specific packages well let's get default then
                   12775: 		if ($key!~/^default&/) { next; }
1.488     albertel 12776: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12777: 					     \%metathesekeys);
                   12778: 	    }
                   12779: 	}
1.338     www      12780: # are there custom rights to evaluate
1.599     albertel 12781: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12782: 
1.338     www      12783:     #
                   12784:     # Importing a rights file here
1.339     albertel 12785:     #
                   12786: 	    unless ($depthcount) {
1.599     albertel 12787: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12788: 		my $dir=$filename;
                   12789: 		$dir=~s|[^/]*$||;
                   12790: 		$location=&filelocation($dir,$location);
1.736     albertel 12791: 		my $rights_metadata =
1.1362    raeburn  12792: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12793: 			      $depthcount+1);
                   12794: 		foreach my $rights (split(',',$rights_metadata)) {
                   12795: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12796: 		    $metathesekeys{$rights}=1;
1.339     albertel 12797: 		}
                   12798: 	    }
                   12799: 	}
1.737     albertel 12800: 	# uniqifiy package listing
                   12801: 	my %seen;
                   12802: 	my @uniq_packages =
                   12803: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12804: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12805: 
1.1369    raeburn  12806:         if (($importedresponses) || ($importedparts)) {
                   12807:             if ($importedparts) {
1.1070    www      12808: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12809:                 $metaentry{':partorder'}='';
                   12810:                 $metathesekeys{'partorder'}=1;
                   12811:             }
                   12812:             if ($importedresponses) {
                   12813: # We had imported responses and need to rebuil responseorder
                   12814:                 $metaentry{':responseorder'}='';
                   12815:                 $metathesekeys{'responseorder'}=1;
                   12816:             }
                   12817:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12818:                 my $origid = $origfiletagids[$index+1];
                   12819:                 if ($origfiletagids[$index] eq 'part') {
                   12820: # Original part, part of the problem
                   12821:                     if ($importedparts) {
                   12822:                         $metaentry{':partorder'}.=','.$origid;
                   12823:                     }
                   12824:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12825:                     if ($importedparts) {
                   12826: # We have imported parts at this position
1.1373    raeburn  12827:                         if ($importedpartids{$origid} ne '') {
                   12828:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12829:                         }
1.1369    raeburn  12830:                     }
                   12831:                     if ($importedresponses) {
                   12832: # We have imported responses at this position
1.1373    raeburn  12833:                         if ($importedrespids{$origid} ne '') {
                   12834:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12835:                         }
                   12836:                     }
                   12837:                 } else {
                   12838: # Original response item, part of the problem
                   12839:                     if ($importedresponses) {
                   12840:                         $metaentry{':responseorder'}.=','.$origid;
                   12841:                     }
                   12842:                 }
                   12843:             }
                   12844:             if ($importedparts) {
                   12845:                 $metaentry{':partorder'}=~s/^\,//;
                   12846:             }
                   12847:             if ($importedresponses) {
                   12848:                 $metaentry{':responseorder'}=~s/^\,//;
                   12849:             }
1.1070    www      12850:         }
1.737     albertel 12851: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12852: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12853: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12854:         unless ($liburi) {
                   12855: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12856:         }
1.177     www      12857: # this is the end of "was not already recently cached
1.71      www      12858:     }
1.599     albertel 12859:     return $metaentry{':'.$what};
1.261     albertel 12860: }
                   12861: 
1.488     albertel 12862: sub metadata_create_package_def {
1.483     albertel 12863:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12864:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12865:     if ($subp eq 'default') { next; }
                   12866:     
1.599     albertel 12867:     if (defined($metaentry{':packages'})) {
                   12868: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12869:     } else {
1.599     albertel 12870: 	$metaentry{':packages'}=$package;
1.483     albertel 12871:     }
                   12872:     my $value=$packagetab{$key};
                   12873:     my $unikey;
                   12874:     $unikey='parameter_0_'.$name;
1.599     albertel 12875:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12876:     $$metathesekeys{$unikey}=1;
1.599     albertel 12877:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12878: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12879:     }
1.599     albertel 12880:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12881: 	$metaentry{':'.$unikey}=
                   12882: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12883:     }
                   12884: }
                   12885: 
1.261     albertel 12886: sub metadata_generate_part0 {
                   12887:     my ($metadata,$metacache,$uri) = @_;
                   12888:     my %allnames;
1.737     albertel 12889:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12890: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12891: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12892: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12893: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12894: 	    $allnames{$name}=$part;
                   12895: 	  }
                   12896: 	}
                   12897:     }
                   12898:     foreach my $name (keys(%allnames)) {
                   12899:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12900:       my $key=":parameter_0_$name";
1.261     albertel 12901:       $$metacache{"$key.part"}='0';
                   12902:       $$metacache{"$key.name"}=$name;
1.428     albertel 12903:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12904: 					   $allnames{$name}.'_'.$name.
                   12905: 					   '.type'};
1.428     albertel 12906:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12907: 			     '.display'};
1.644     www      12908:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12909:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12910:       $$metacache{"$key.display"}=$olddis;
                   12911:     }
1.71      www      12912: }
                   12913: 
1.764     albertel 12914: # ------------------------------------------------------ Devalidate title cache
                   12915: 
                   12916: sub devalidate_title_cache {
                   12917:     my ($url)=@_;
                   12918:     if (!$env{'request.course.id'}) { return; }
                   12919:     my $symb=&symbread($url);
                   12920:     if (!$symb) { return; }
                   12921:     my $key=$env{'request.course.id'}."\0".$symb;
                   12922:     &devalidate_cache_new('title',$key);
                   12923: }
                   12924: 
1.1014    droeschl 12925: # ------------------------------------------------- Get the title of a course
                   12926: 
                   12927: sub current_course_title {
                   12928:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12929: }
1.301     www      12930: # ------------------------------------------------- Get the title of a resource
                   12931: 
                   12932: sub gettitle {
                   12933:     my $urlsymb=shift;
                   12934:     my $symb=&symbread($urlsymb);
1.534     albertel 12935:     if ($symb) {
1.620     albertel 12936: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12937: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12938: 	if (defined($cached)) { 
                   12939: 	    return $result;
                   12940: 	}
1.534     albertel 12941: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12942: 	my $title='';
1.907     albertel 12943: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12944: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12945: 	} else {
                   12946: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12947: 		    &GDBM_READER(),0640)) {
                   12948: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12949: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12950: 		untie(%bighash);
                   12951: 	    }
1.534     albertel 12952: 	}
                   12953: 	$title=~s/\&colon\;/\:/gs;
                   12954: 	if ($title) {
1.1159    www      12955: # Remember both $symb and $title for dynamic metadata
                   12956:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12957:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12958: # Cache this title and then return it
1.599     albertel 12959: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12960: 	}
                   12961: 	$urlsymb=$url;
                   12962:     }
                   12963:     my $title=&metadata($urlsymb,'title');
                   12964:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12965:     return $title;
1.301     www      12966: }
1.613     albertel 12967: 
1.614     albertel 12968: sub get_slot {
                   12969:     my ($which,$cnum,$cdom)=@_;
                   12970:     if (!$cnum || !$cdom) {
1.790     albertel 12971: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12972: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12973: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12974:     }
1.703     albertel 12975:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12976:     my %slotinfo;
                   12977:     if (exists($remembered{$key})) {
                   12978: 	$slotinfo{$which} = $remembered{$key};
                   12979:     } else {
                   12980: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12981: 	&Apache::lonhomework::showhash(%slotinfo);
                   12982: 	my ($tmp)=keys(%slotinfo);
                   12983: 	if ($tmp=~/^error:/) { return (); }
                   12984: 	$remembered{$key} = $slotinfo{$which};
                   12985:     }
1.616     albertel 12986:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12987: 	return %{$slotinfo{$which}};
                   12988:     }
                   12989:     return $slotinfo{$which};
1.614     albertel 12990: }
1.1150    raeburn  12991: 
                   12992: sub get_reservable_slots {
                   12993:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12994:     my $now = time;
                   12995:     my $reservable_info;
                   12996:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12997:     if (exists($remembered{$key})) {
                   12998:         $reservable_info = $remembered{$key};
                   12999:     } else {
                   13000:         my %resv;
                   13001:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13002:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13003:         $reservable_info = \%resv;
                   13004:         $remembered{$key} = $reservable_info;
                   13005:     }
                   13006:     return $reservable_info;
                   13007: }
                   13008: 
                   13009: sub get_course_slots {
                   13010:     my ($cnum,$cdom) = @_;
                   13011:     my $hashid=$cnum.':'.$cdom;
                   13012:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13013:     if (defined($cached)) {
                   13014:         if (ref($result) eq 'HASH') {
                   13015:             return %{$result};
                   13016:         }
                   13017:     } else {
                   13018:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13019:         my ($tmp) = keys(%slots);
                   13020:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13021:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13022:             return %slots;
                   13023:         }
                   13024:     }
                   13025:     return;
                   13026: }
                   13027: 
                   13028: sub devalidate_slots_cache {
                   13029:     my ($cnum,$cdom)=@_;
                   13030:     my $hashid=$cnum.':'.$cdom;
                   13031:     &devalidate_cache_new('allslots',$hashid);
                   13032: }
                   13033: 
1.1181    raeburn  13034: sub get_coursechange {
                   13035:     my ($cdom,$cnum) = @_;
                   13036:     if ($cdom eq '' || $cnum eq '') {
                   13037:         return unless ($env{'request.course.id'});
                   13038:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13039:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13040:     }
                   13041:     my $hashid=$cdom.'_'.$cnum;
                   13042:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13043:     if ((defined($cached)) && ($change ne '')) {
                   13044:         return $change;
                   13045:     } else {
                   13046:         my %crshash;
                   13047:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13048:         if ($crshash{'internal.contentchange'} eq '') {
                   13049:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13050:             if ($change eq '') {
                   13051:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13052:                 $change = $crshash{'internal.created'};
                   13053:             }
                   13054:         } else {
                   13055:             $change = $crshash{'internal.contentchange'};
                   13056:         }
                   13057:         my $cachetime = 600;
                   13058:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13059:     }
                   13060:     return $change;
                   13061: }
                   13062: 
                   13063: sub devalidate_coursechange_cache {
                   13064:     my ($cnum,$cdom)=@_;
                   13065:     my $hashid=$cnum.':'.$cdom;
                   13066:     &devalidate_cache_new('crschange',$hashid);
                   13067: }
                   13068: 
1.31      www      13069: # ------------------------------------------------- Update symbolic store links
                   13070: 
                   13071: sub symblist {
                   13072:     my ($mapname,%newhash)=@_;
1.438     www      13073:     $mapname=&deversion(&declutter($mapname));
1.31      www      13074:     my %hash;
1.620     albertel 13075:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13076:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13077:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13078: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13079: 		next if ($url eq 'last_known'
                   13080: 			 && $env{'form.no_update_last_known'});
                   13081: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13082: 						    $newhash{$url}->[1],
                   13083: 						    $newhash{$url}->[0]);
1.191     harris41 13084:             }
1.31      www      13085:             if (untie(%hash)) {
                   13086: 		return 'ok';
                   13087:             }
                   13088:         }
                   13089:     }
                   13090:     return 'error';
1.212     www      13091: }
                   13092: 
                   13093: # --------------------------------------------------------------- Verify a symb
                   13094: 
                   13095: sub symbverify {
1.1190    raeburn  13096:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13097:     my $thisfn=$thisurl;
1.439     www      13098:     $thisfn=&declutter($thisfn);
1.215     www      13099: # direct jump to resource in page or to a sequence - will construct own symbs
                   13100:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13101: # check URL part
1.409     www      13102:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13103: 
1.431     www      13104:     unless ($url eq $thisfn) { return 0; }
1.213     www      13105: 
1.216     www      13106:     $symb=&symbclean($symb);
1.510     www      13107:     $thisurl=&deversion($thisurl);
1.439     www      13108:     $thisfn=&deversion($thisfn);
1.213     www      13109: 
                   13110:     my %bighash;
                   13111:     my $okay=0;
1.431     www      13112: 
1.620     albertel 13113:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13114:                             &GDBM_READER(),0640)) {
1.1204    raeburn  13115:         my $noclutter;
1.1032    raeburn  13116:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13117:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13118:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13119:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13120:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13121:                 $noclutter = 1;
                   13122:             }
                   13123:         }
                   13124:         my $ids;
                   13125:         if ($noclutter) {
                   13126:             $ids=$bighash{'ids_'.$thisurl};
                   13127:         } else {
                   13128:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13129:         }
1.1102    raeburn  13130:         unless ($ids) {
                   13131:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13132:             $ids=$bighash{$idkey};
1.216     www      13133:         }
                   13134:         if ($ids) {
                   13135: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13136:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13137:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13138:             }
1.800     albertel 13139: 	    foreach my $id (split(/\,/,$ids)) {
                   13140: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13141:                if (
                   13142:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13143:    eq $symb) {
                   13144:                    if (ref($encstate)) {
                   13145:                        $$encstate = $bighash{'encrypted_'.$id};
                   13146:                    }
1.620     albertel 13147: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13148: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13149:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13150: 		       $okay=1;
1.1202    raeburn  13151:                        last;
1.582     albertel 13152: 		   }
                   13153: 	       }
1.216     www      13154: 	   }
                   13155:         }
1.213     www      13156: 	untie(%bighash);
                   13157:     }
                   13158:     return $okay;
1.31      www      13159: }
                   13160: 
1.210     www      13161: # --------------------------------------------------------------- Clean-up symb
                   13162: 
                   13163: sub symbclean {
                   13164:     my $symb=shift;
1.568     albertel 13165:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13166: # remove version from map
                   13167:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13168: 
1.210     www      13169: # remove version from URL
                   13170:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13171: 
1.507     www      13172: # remove wrapper
                   13173: 
1.510     www      13174:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13175:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13176:     return $symb;
1.409     www      13177: }
                   13178: 
                   13179: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13180: 
                   13181: sub encode_symb {
                   13182:     my ($map,$resid,$url)=@_;
                   13183:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13184: }
1.409     www      13185: 
                   13186: sub decode_symb {
1.568     albertel 13187:     my $symb=shift;
                   13188:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13189:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13190:     return (&fixversion($map),$resid,&fixversion($url));
                   13191: }
                   13192: 
                   13193: sub fixversion {
                   13194:     my $fn=shift;
1.609     banghart 13195:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13196:     my %bighash;
                   13197:     my $uri=&clutter($fn);
1.620     albertel 13198:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13199: # is this cached?
1.599     albertel 13200:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13201:     if (defined($cached)) { return $result; }
                   13202: # unfortunately not cached, or expired
1.620     albertel 13203:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13204: 	    &GDBM_READER(),0640)) {
                   13205:  	if ($bighash{'version_'.$uri}) {
                   13206:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13207:  	    unless (($version eq 'mostrecent') || 
                   13208: 		    ($version==&getversion($uri))) {
1.440     www      13209:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13210:  	    }
                   13211:  	}
                   13212:  	untie %bighash;
1.413     www      13213:     }
1.599     albertel 13214:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13215: }
                   13216: 
                   13217: sub deversion {
                   13218:     my $url=shift;
                   13219:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13220:     return $url;
1.210     www      13221: }
                   13222: 
1.31      www      13223: # ------------------------------------------------------ Return symb list entry
                   13224: 
                   13225: sub symbread {
1.1282    raeburn  13226:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  13227:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  13228:     if (defined($env{$cache_str})) {
                   13229:         if ($ignorecachednull) {
                   13230:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13231:         } else {
                   13232:             return $env{$cache_str};
                   13233:         }
                   13234:     }
1.242     www      13235: # no filename provided? try from environment
1.1265    raeburn  13236:     unless ($thisfn) {
1.620     albertel 13237:         if ($env{'request.symb'}) {
                   13238: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13239: 	}
1.620     albertel 13240: 	$thisfn=$env{'request.filename'};
1.44      www      13241:     }
1.569     albertel 13242:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13243: # is that filename actually a symb? Verify, clean, and return
                   13244:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13245: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 13246: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13247: 	}
1.242     www      13248:     }
1.44      www      13249:     $thisfn=declutter($thisfn);
1.31      www      13250:     my %hash;
1.37      www      13251:     my %bighash;
                   13252:     my $syval='';
1.620     albertel 13253:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13254:         my $targetfn = $thisfn;
1.609     banghart 13255:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13256:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13257:         }
1.687     albertel 13258: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13259: 	    $targetfn=$1;
                   13260: 	}
1.620     albertel 13261:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13262:                       &GDBM_READER(),0640)) {
1.481     raeburn  13263: 	    $syval=$hash{$targetfn};
1.37      www      13264:             untie(%hash);
                   13265:         }
                   13266: # ---------------------------------------------------------- There was an entry
                   13267:         if ($syval) {
1.601     albertel 13268: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13269: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13270: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13271: 		    #return $env{$cache_str}='';
1.601     albertel 13272: 		#}    
                   13273: 		#$syval.=$1;
                   13274: 	    #}
1.37      www      13275:         } else {
                   13276: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13277:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13278:                             &GDBM_READER(),0640)) {
1.37      www      13279: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13280:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13281:               unless ($ids) { 
                   13282:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13283:               }
                   13284:               unless ($ids) {
                   13285: # alias?
                   13286: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13287:               }
1.37      www      13288:               if ($ids) {
                   13289: # ------------------------------------------------------------------- Has ID(s)
                   13290:                  my @possibilities=split(/\,/,$ids);
1.39      www      13291:                  if ($#possibilities==0) {
                   13292: # ----------------------------------------------- There is only one possibility
1.37      www      13293: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13294: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13295: 						    $resid,$thisfn);
1.1282    raeburn  13296:                      if (ref($possibles) eq 'HASH') {
                   13297:                          $possibles->{$syval} = 1;    
                   13298:                      }
                   13299:                      if ($checkforblock) {
                   13300:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   13301:                          if (@blockers) {
                   13302:                              $syval = '';
                   13303:                              return;
                   13304:                          }
                   13305:                      }
                   13306:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13307: # ------------------------------------------ There is more than one possibility
                   13308:                      my $realpossible=0;
1.800     albertel 13309:                      foreach my $id (@possibilities) {
                   13310: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13311:                          my $canaccess;
                   13312:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13313:                              $canaccess = 1;
                   13314:                          } else { 
                   13315:                              $canaccess = &allowed('bre',$file);
                   13316:                          }
                   13317:                          if ($canaccess) {
                   13318:          		     my ($mapid,$resid)=split(/\./,$id);
                   13319:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13320:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13321: 						             $resid,$thisfn);
                   13322:                                  if (ref($possibles) eq 'HASH') {
                   13323:                                      $possibles->{$syval} = 1;
                   13324:                                  }
                   13325:                                  if ($checkforblock) {
                   13326:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   13327:                                      unless (@blockers > 0) {
                   13328:                                          $syval = $poss_syval;
                   13329:                                          $realpossible++;
                   13330:                                      }
                   13331:                                  } else {
                   13332:                                      $syval = $poss_syval;
                   13333:                                      $realpossible++;
                   13334:                                  }
                   13335:                              }
1.39      www      13336: 			 }
1.191     harris41 13337:                      }
1.39      www      13338: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13339:                  } else {
                   13340:                      $syval='';
1.37      www      13341:                  }
                   13342: 	      }
1.1282    raeburn  13343:               untie(%bighash);
1.481     raeburn  13344:            }
1.31      www      13345:         }
1.62      www      13346:         if ($syval) {
1.620     albertel 13347: 	    return $env{$cache_str}=$syval;
1.62      www      13348:         }
1.31      www      13349:     }
1.949     raeburn  13350:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13351:     return $env{$cache_str}='';
1.31      www      13352: }
                   13353: 
                   13354: # ---------------------------------------------------------- Return random seed
                   13355: 
1.32      www      13356: sub numval {
                   13357:     my $txt=shift;
                   13358:     $txt=~tr/A-J/0-9/;
                   13359:     $txt=~tr/a-j/0-9/;
                   13360:     $txt=~tr/K-T/0-9/;
                   13361:     $txt=~tr/k-t/0-9/;
                   13362:     $txt=~tr/U-Z/0-5/;
                   13363:     $txt=~tr/u-z/0-5/;
                   13364:     $txt=~s/\D//g;
1.564     albertel 13365:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13366:     return int($txt);
1.368     albertel 13367: }
                   13368: 
1.484     albertel 13369: sub numval2 {
                   13370:     my $txt=shift;
                   13371:     $txt=~tr/A-J/0-9/;
                   13372:     $txt=~tr/a-j/0-9/;
                   13373:     $txt=~tr/K-T/0-9/;
                   13374:     $txt=~tr/k-t/0-9/;
                   13375:     $txt=~tr/U-Z/0-5/;
                   13376:     $txt=~tr/u-z/0-5/;
                   13377:     $txt=~s/\D//g;
                   13378:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13379:     my $total;
                   13380:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13381:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13382:     return int($total);
                   13383: }
                   13384: 
1.575     albertel 13385: sub numval3 {
                   13386:     use integer;
                   13387:     my $txt=shift;
                   13388:     $txt=~tr/A-J/0-9/;
                   13389:     $txt=~tr/a-j/0-9/;
                   13390:     $txt=~tr/K-T/0-9/;
                   13391:     $txt=~tr/k-t/0-9/;
                   13392:     $txt=~tr/U-Z/0-5/;
                   13393:     $txt=~tr/u-z/0-5/;
                   13394:     $txt=~s/\D//g;
                   13395:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13396:     my $total;
                   13397:     foreach my $val (@txts) { $total+=$val; }
                   13398:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13399:     return $total;
                   13400: }
                   13401: 
1.675     albertel 13402: sub digest {
                   13403:     my ($data)=@_;
                   13404:     my $digest=&Digest::MD5::md5($data);
                   13405:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13406:     my ($e,$f);
                   13407:     {
                   13408:         use integer;
                   13409:         $e=($a+$b);
                   13410:         $f=($c+$d);
                   13411:         if ($_64bit) {
                   13412:             $e=(($e<<32)>>32);
                   13413:             $f=(($f<<32)>>32);
                   13414:         }
                   13415:     }
                   13416:     if (wantarray) {
                   13417: 	return ($e,$f);
                   13418:     } else {
                   13419: 	my $g;
                   13420: 	{
                   13421: 	    use integer;
                   13422: 	    $g=($e+$f);
                   13423: 	    if ($_64bit) {
                   13424: 		$g=(($g<<32)>>32);
                   13425: 	    }
                   13426: 	}
                   13427: 	return $g;
                   13428:     }
                   13429: }
                   13430: 
1.368     albertel 13431: sub latest_rnd_algorithm_id {
1.675     albertel 13432:     return '64bit5';
1.366     albertel 13433: }
1.32      www      13434: 
1.503     albertel 13435: sub get_rand_alg {
                   13436:     my ($courseid)=@_;
1.790     albertel 13437:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13438:     if ($courseid) {
1.620     albertel 13439: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13440:     }
                   13441:     return &latest_rnd_algorithm_id();
                   13442: }
                   13443: 
1.562     albertel 13444: sub validCODE {
                   13445:     my ($CODE)=@_;
                   13446:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13447:     return 0;
                   13448: }
                   13449: 
1.491     albertel 13450: sub getCODE {
1.620     albertel 13451:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13452:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13453: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13454: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13455: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13456:     }
                   13457:     return undef;
                   13458: }
1.1133    foxr     13459: #
                   13460: #  Determines the random seed for a specific context:
                   13461: #
                   13462: # parameters:
                   13463: #   symb      - in course context the symb for the seed.
                   13464: #   course_id - The course id of the form domain_coursenum.
                   13465: #   domain    - Domain for the user.
                   13466: #   course    - Course for the user.
                   13467: #   cenv      - environment of the course.
                   13468: #
                   13469: # NOTE:
                   13470: #   All parameters are picked out of the environment if missing
                   13471: #   or not defined.
                   13472: #   If a symb cannot be determined the current time is used instead.
                   13473: #
                   13474: #  For a given well defined symb, courside, domain, username,
                   13475: #  and course environment, the seed is reproducible.
                   13476: #
1.31      www      13477: sub rndseed {
1.1133    foxr     13478:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13479:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13480:     if (!defined($symb)) {
1.366     albertel 13481: 	unless ($symb=$wsymb) { return time; }
                   13482:     }
1.1146    foxr     13483:     if (!defined $courseid) { 
                   13484: 	$courseid=$wcourseid; 
                   13485:     }
                   13486:     if (!defined $domain) { $domain=$wdomain; }
                   13487:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13488: 
                   13489:     my $which;
                   13490:     if (defined($cenv->{'rndseed'})) {
                   13491: 	$which = $cenv->{'rndseed'};
                   13492:     } else {
                   13493: 	$which =&get_rand_alg($courseid);
                   13494:     }
1.491     albertel 13495:     if (defined(&getCODE())) {
1.1133    foxr     13496: 
1.675     albertel 13497: 	if ($which eq '64bit5') {
                   13498: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13499: 	} elsif ($which eq '64bit4') {
1.575     albertel 13500: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13501: 	} else {
                   13502: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13503: 	}
1.675     albertel 13504:     } elsif ($which eq '64bit5') {
                   13505: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13506:     } elsif ($which eq '64bit4') {
                   13507: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13508:     } elsif ($which eq '64bit3') {
                   13509: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13510:     } elsif ($which eq '64bit2') {
                   13511: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13512:     } elsif ($which eq '64bit') {
                   13513: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13514:     }
                   13515:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13516: }
                   13517: 
                   13518: sub rndseed_32bit {
                   13519:     my ($symb,$courseid,$domain,$username)=@_;
                   13520:     {
                   13521: 	use integer;
                   13522: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13523: 	my $symbseed=numval($symb) << 22;
                   13524: 	my $namechck=unpack("%32C*",$username) << 17;
                   13525: 	my $nameseed=numval($username) << 12;
                   13526: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13527: 	my $courseseed=unpack("%32C*",$courseid);
                   13528: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13529: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13530: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13531: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13532: 	return $num;
                   13533:     }
                   13534: }
                   13535: 
                   13536: sub rndseed_64bit {
                   13537:     my ($symb,$courseid,$domain,$username)=@_;
                   13538:     {
                   13539: 	use integer;
                   13540: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13541: 	my $symbseed=numval($symb) << 10;
                   13542: 	my $namechck=unpack("%32S*",$username);
                   13543: 	
                   13544: 	my $nameseed=numval($username) << 21;
                   13545: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13546: 	my $courseseed=unpack("%32S*",$courseid);
                   13547: 	
                   13548: 	my $num1=$symbchck+$symbseed+$namechck;
                   13549: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13550: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13551: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13552: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13553: 	return "$num1,$num2";
1.155     albertel 13554:     }
1.366     albertel 13555: }
                   13556: 
1.443     albertel 13557: sub rndseed_64bit2 {
                   13558:     my ($symb,$courseid,$domain,$username)=@_;
                   13559:     {
                   13560: 	use integer;
                   13561: 	# strings need to be an even # of cahracters long, it it is odd the
                   13562:         # last characters gets thrown away
                   13563: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13564: 	my $symbseed=numval($symb) << 10;
                   13565: 	my $namechck=unpack("%32S*",$username.' ');
                   13566: 	
                   13567: 	my $nameseed=numval($username) << 21;
1.501     albertel 13568: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13569: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13570: 	
                   13571: 	my $num1=$symbchck+$symbseed+$namechck;
                   13572: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13573: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13574: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13575: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13576: 	return "$num1,$num2";
                   13577:     }
                   13578: }
                   13579: 
                   13580: sub rndseed_64bit3 {
                   13581:     my ($symb,$courseid,$domain,$username)=@_;
                   13582:     {
                   13583: 	use integer;
                   13584: 	# strings need to be an even # of cahracters long, it it is odd the
                   13585:         # last characters gets thrown away
                   13586: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13587: 	my $symbseed=numval2($symb) << 10;
                   13588: 	my $namechck=unpack("%32S*",$username.' ');
                   13589: 	
                   13590: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13591: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13592: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13593: 	
                   13594: 	my $num1=$symbchck+$symbseed+$namechck;
                   13595: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13596: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13597: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13598: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13599: 	
1.503     albertel 13600: 	return "$num1:$num2";
1.443     albertel 13601:     }
                   13602: }
                   13603: 
1.575     albertel 13604: sub rndseed_64bit4 {
                   13605:     my ($symb,$courseid,$domain,$username)=@_;
                   13606:     {
                   13607: 	use integer;
                   13608: 	# strings need to be an even # of cahracters long, it it is odd the
                   13609:         # last characters gets thrown away
                   13610: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13611: 	my $symbseed=numval3($symb) << 10;
                   13612: 	my $namechck=unpack("%32S*",$username.' ');
                   13613: 	
                   13614: 	my $nameseed=numval3($username) << 21;
                   13615: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13616: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13617: 	
                   13618: 	my $num1=$symbchck+$symbseed+$namechck;
                   13619: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13620: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13621: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13622: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13623: 	
1.575     albertel 13624: 	return "$num1:$num2";
                   13625:     }
                   13626: }
                   13627: 
1.675     albertel 13628: sub rndseed_64bit5 {
                   13629:     my ($symb,$courseid,$domain,$username)=@_;
                   13630:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13631:     return "$num1:$num2";
                   13632: }
                   13633: 
1.366     albertel 13634: sub rndseed_CODE_64bit {
                   13635:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13636:     {
1.366     albertel 13637: 	use integer;
1.443     albertel 13638: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13639: 	my $symbseed=numval2($symb);
1.491     albertel 13640: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13641: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13642: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13643: 	my $num1=$symbseed+$CODEchck;
                   13644: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13645: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13646: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13647: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13648: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13649: 	return "$num1:$num2";
1.366     albertel 13650:     }
                   13651: }
                   13652: 
1.575     albertel 13653: sub rndseed_CODE_64bit4 {
                   13654:     my ($symb,$courseid,$domain,$username)=@_;
                   13655:     {
                   13656: 	use integer;
                   13657: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13658: 	my $symbseed=numval3($symb);
                   13659: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13660: 	my $CODEseed=numval3(&getCODE());
                   13661: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13662: 	my $num1=$symbseed+$CODEchck;
                   13663: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13664: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13665: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13666: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13667: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13668: 	return "$num1:$num2";
                   13669:     }
                   13670: }
                   13671: 
1.675     albertel 13672: sub rndseed_CODE_64bit5 {
                   13673:     my ($symb,$courseid,$domain,$username)=@_;
                   13674:     my $code = &getCODE();
                   13675:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13676:     return "$num1:$num2";
                   13677: }
                   13678: 
1.366     albertel 13679: sub setup_random_from_rndseed {
                   13680:     my ($rndseed)=@_;
1.503     albertel 13681:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13682:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13683:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13684:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13685:         } else {
                   13686:             &Math::Random::random_set_seed($num1,$num2);
                   13687:         }
1.366     albertel 13688:     } else {
                   13689: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13690:     }
1.36      albertel 13691: }
                   13692: 
1.474     albertel 13693: sub latest_receipt_algorithm_id {
1.835     albertel 13694:     return 'receipt3';
1.474     albertel 13695: }
                   13696: 
1.480     www      13697: sub recunique {
                   13698:     my $fucourseid=shift;
                   13699:     my $unique;
1.835     albertel 13700:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13701: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13702: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13703:     } else {
                   13704: 	$unique=$perlvar{'lonReceipt'};
                   13705:     }
                   13706:     return unpack("%32C*",$unique);
                   13707: }
                   13708: 
                   13709: sub recprefix {
                   13710:     my $fucourseid=shift;
                   13711:     my $prefix;
1.835     albertel 13712:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13713: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13714: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13715:     } else {
                   13716: 	$prefix=$perlvar{'lonHostID'};
                   13717:     }
                   13718:     return unpack("%32C*",$prefix);
                   13719: }
                   13720: 
1.76      www      13721: sub ireceipt {
1.474     albertel 13722:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13723: 
                   13724:     my $return =&recprefix($fucourseid).'-';
                   13725: 
                   13726:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13727: 	$env{'request.state'} eq 'construct') {
                   13728: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13729: 	return $return;
                   13730:     }
                   13731: 
1.76      www      13732:     my $cuname=unpack("%32C*",$funame);
                   13733:     my $cudom=unpack("%32C*",$fudom);
                   13734:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13735:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13736:     my $cunique=&recunique($fucourseid);
1.474     albertel 13737:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13738:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13739: 
1.790     albertel 13740: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13741: 			       
                   13742: 	$return.= ($cunique%$cuname+
                   13743: 		   $cunique%$cudom+
                   13744: 		   $cusymb%$cuname+
                   13745: 		   $cusymb%$cudom+
                   13746: 		   $cucourseid%$cuname+
                   13747: 		   $cucourseid%$cudom+
                   13748: 		   $cpart%$cuname+
                   13749: 		   $cpart%$cudom);
                   13750:     } else {
                   13751: 	$return.= ($cunique%$cuname+
                   13752: 		   $cunique%$cudom+
                   13753: 		   $cusymb%$cuname+
                   13754: 		   $cusymb%$cudom+
                   13755: 		   $cucourseid%$cuname+
                   13756: 		   $cucourseid%$cudom);
                   13757:     }
                   13758:     return $return;
1.76      www      13759: }
                   13760: 
                   13761: sub receipt {
1.474     albertel 13762:     my ($part)=@_;
1.790     albertel 13763:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13764:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13765: }
1.260     ng       13766: 
1.790     albertel 13767: sub whichuser {
                   13768:     my ($passedsymb)=@_;
                   13769:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13770:     if (defined($env{'form.grade_symb'})) {
                   13771: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13772: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13773: 	if (!$allowed &&
                   13774: 	    exists($env{'request.course.sec'}) &&
                   13775: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13776: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13777: 			      '/'.$env{'request.course.sec'});
                   13778: 	}
                   13779: 	if ($allowed) {
                   13780: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13781: 	    $courseid=$tmp_courseid;
                   13782: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13783: 	    ($name)=&get_env_multiple('form.grade_username');
                   13784: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13785: 	}
                   13786:     }
                   13787:     if (!$passedsymb) {
                   13788: 	$symb=&symbread();
                   13789:     } else {
                   13790: 	$symb=$passedsymb;
                   13791:     }
                   13792:     $courseid=$env{'request.course.id'};
                   13793:     $domain=$env{'user.domain'};
                   13794:     $name=$env{'user.name'};
                   13795:     if ($name eq 'public' && $domain eq 'public') {
                   13796: 	if (!defined($env{'form.username'})) {
                   13797: 	    $env{'form.username'}.=time.rand(10000000);
                   13798: 	}
                   13799: 	$name.=$env{'form.username'};
                   13800:     }
                   13801:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13802: 
                   13803: }
                   13804: 
1.36      albertel 13805: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13806: # returns either the contents of the file or 
                   13807: # -1 if the file doesn't exist
1.481     raeburn  13808: #
                   13809: # if the target is a file that was uploaded via DOCS, 
                   13810: # a check will be made to see if a current copy exists on the local server,
                   13811: # if it does this will be served, otherwise a copy will be retrieved from
                   13812: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13813: # the local server.   
1.472     albertel 13814: 
1.36      albertel 13815: sub getfile {
1.538     albertel 13816:     my ($file) = @_;
1.609     banghart 13817:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13818:     &repcopy($file);
                   13819:     return &readfile($file);
                   13820: }
                   13821: 
                   13822: sub repcopy_userfile {
                   13823:     my ($file)=@_;
1.1142    raeburn  13824:     my $londocroot = $perlvar{'lonDocRoot'};
                   13825:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13826:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13827:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13828: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13829:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13830:     if (-e "$file") {
1.828     www      13831: # we already have a local copy, check it out
1.538     albertel 13832: 	my @fileinfo = stat($file);
1.828     www      13833: 	my $rtncode;
                   13834: 	my $info;
1.538     albertel 13835: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13836: 	if ($lwpresp ne 'ok') {
1.828     www      13837: # there is no such file anymore, even though we had a local copy
1.482     albertel 13838: 	    if ($rtncode eq '404') {
1.538     albertel 13839: 		unlink($file);
1.482     albertel 13840: 	    }
                   13841: 	    return -1;
                   13842: 	}
                   13843: 	if ($info < $fileinfo[9]) {
1.828     www      13844: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13845: 	    return 'ok';
1.828     www      13846: 	} else {
                   13847: # the file is outdated, get rid of it
                   13848: 	    unlink($file);
1.482     albertel 13849: 	}
1.828     www      13850:     }
                   13851: # one way or the other, at this point, we don't have the file
                   13852: # construct the correct path for the file
                   13853:     my @parts = ($cdom,$cnum); 
                   13854:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13855: 	push @parts, split(/\//,$1);
                   13856:     }
                   13857:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13858:     foreach my $part (@parts) {
                   13859: 	$path .= '/'.$part;
                   13860: 	if (!-e $path) {
                   13861: 	    mkdir($path,0770);
1.482     albertel 13862: 	}
                   13863:     }
1.828     www      13864: # now the path exists for sure
                   13865: # get a user agent
                   13866:     my $transferfile=$file.'.in.transfer';
                   13867: # FIXME: this should flock
                   13868:     if (-e $transferfile) { return 'ok'; }
                   13869:     my $request;
                   13870:     $uri=~s/^\///;
1.980     raeburn  13871:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  13872:     my $hostname = &hostname($homeserver);
1.980     raeburn  13873:     my $protocol = $protocol{$homeserver};
                   13874:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13875:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  13876:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13877: # did it work?
                   13878:     if ($response->is_error()) {
                   13879: 	unlink($transferfile);
                   13880: 	&logthis("Userfile repcopy failed for $uri");
                   13881: 	return -1;
                   13882:     }
                   13883: # worked, rename the transfer file
                   13884:     rename($transferfile,$file);
1.607     raeburn  13885:     return 'ok';
1.481     raeburn  13886: }
                   13887: 
1.517     albertel 13888: sub tokenwrapper {
                   13889:     my $uri=shift;
1.980     raeburn  13890:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13891:     $uri=~s|^/||;
1.620     albertel 13892:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13893:     my $token=$1;
1.552     albertel 13894:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13895:     if ($udom && $uname && $file) {
                   13896: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13897:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13898:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  13899:         my $hostname = &hostname($homeserver);
1.980     raeburn  13900:         my $protocol = $protocol{$homeserver};
                   13901:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13902:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13903:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13904:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13905:     } else {
                   13906:         return '/adm/notfound.html';
                   13907:     }
                   13908: }
                   13909: 
1.828     www      13910: # call with reqtype HEAD: get last modification time
                   13911: # call with reqtype GET: get the file contents
                   13912: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13913: #
1.481     raeburn  13914: sub getuploaded {
                   13915:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13916:     $uri=~s/^\///;
1.980     raeburn  13917:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  13918:     my $hostname = &hostname($homeserver);
1.980     raeburn  13919:     my $protocol = $protocol{$homeserver};
                   13920:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13921:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13922:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13923:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13924:     $$rtncode = $response->code;
1.482     albertel 13925:     if (! $response->is_success()) {
                   13926: 	return 'failed';
                   13927:     }      
                   13928:     if ($reqtype eq 'HEAD') {
1.486     www      13929: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13930:     } elsif ($reqtype eq 'GET') {
                   13931: 	$$info = $response->content;
1.472     albertel 13932:     }
1.482     albertel 13933:     return 'ok';
1.36      albertel 13934: }
                   13935: 
1.481     raeburn  13936: sub readfile {
                   13937:     my $file = shift;
                   13938:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13939:     my $fh;
1.1359    raeburn  13940:     open($fh,"<",$file);
1.481     raeburn  13941:     my $a='';
1.800     albertel 13942:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13943:     return $a;
                   13944: }
                   13945: 
1.36      albertel 13946: sub filelocation {
1.590     banghart 13947:     my ($dir,$file) = @_;
                   13948:     my $location;
                   13949:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13950: 
                   13951:     if ($file =~ m-^/adm/-) {
                   13952: 	$file=~s-^/adm/wrapper/-/-;
                   13953: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13954:     }
1.882     albertel 13955: 
1.1139    www      13956:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13957:         $location = $file;
1.609     banghart 13958:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13959:         my ($udom,$uname,$filename)=
1.811     albertel 13960:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13961:         my $home=&homeserver($uname,$udom);
                   13962:         my $is_me=0;
                   13963:         my @ids=&current_machine_ids();
                   13964:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13965:         if ($is_me) {
1.1117    foxr     13966:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13967:         } else {
                   13968:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13969:   	      $udom.'/'.$uname.'/'.$filename;
                   13970:         }
1.882     albertel 13971:     } elsif ($file =~ m-^/adm/-) {
                   13972: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13973:     } else {
                   13974:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13975:         $file=~s:^/(res|priv)/:/:;
                   13976:         my $space=$1;
1.590     banghart 13977:         if ( !( $file =~ m:^/:) ) {
                   13978:             $location = $dir. '/'.$file;
                   13979:         } else {
1.1142    raeburn  13980:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13981:         }
1.59      albertel 13982:     }
1.590     banghart 13983:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13984:     while ($location=~m{/\.\./}) {
                   13985: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13986: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13987: 	} else {
                   13988: 	    $location=~ s{/\.\./}{/}g;
                   13989: 	}
                   13990:     } #remove dir/..
1.590     banghart 13991:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13992:     return $location;
1.46      www      13993: }
1.36      albertel 13994: 
1.46      www      13995: sub hreflocation {
                   13996:     my ($dir,$file)=@_;
1.980     raeburn  13997:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13998: 	$file=filelocation($dir,$file);
1.700     albertel 13999:     } elsif ($file=~m-^/adm/-) {
                   14000: 	$file=~s-^/adm/wrapper/-/-;
                   14001: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14002:     }
                   14003:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14004: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14005:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14006: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14007: 	        {/uploaded/$1/$2/}x;
1.46      www      14008:     }
1.913     albertel 14009:     if ($file=~ m{^/userfiles/}) {
                   14010: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14011:     }
1.462     albertel 14012:     return $file;
1.465     albertel 14013: }
                   14014: 
1.1139    www      14015: 
                   14016: 
                   14017: 
                   14018: 
1.465     albertel 14019: sub current_machine_domains {
1.853     albertel 14020:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14021: }
                   14022: 
                   14023: sub machine_domains {
                   14024:     my ($hostname) = @_;
1.465     albertel 14025:     my @domains;
1.838     albertel 14026:     my %hostname = &all_hostnames();
1.465     albertel 14027:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14028: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14029: 	if ($hostname eq $name) {
1.844     albertel 14030: 	    push(@domains,&host_domain($id));
1.465     albertel 14031: 	}
                   14032:     }
                   14033:     return @domains;
                   14034: }
                   14035: 
                   14036: sub current_machine_ids {
1.853     albertel 14037:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14038: }
                   14039: 
                   14040: sub machine_ids {
                   14041:     my ($hostname) = @_;
                   14042:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14043:     my @ids;
1.888     albertel 14044:     my %name_to_host = &all_names();
1.889     albertel 14045:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14046: 	return @{ $name_to_host{$hostname} };
                   14047:     }
                   14048:     return;
1.31      www      14049: }
                   14050: 
1.824     raeburn  14051: sub additional_machine_domains {
                   14052:     my @domains;
1.1359    raeburn  14053:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  14054:     while( my $line = <$fh>) {
                   14055:         $line =~ s/\s//g;
                   14056:         push(@domains,$line);
                   14057:     }
                   14058:     return @domains;
                   14059: }
                   14060: 
                   14061: sub default_login_domain {
                   14062:     my $domain = $perlvar{'lonDefDomain'};
                   14063:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14064:     foreach my $posdom (&current_machine_domains(),
                   14065:                         &additional_machine_domains()) {
                   14066:         if (lc($posdom) eq lc($testdomain)) {
                   14067:             $domain=$posdom;
                   14068:             last;
                   14069:         }
                   14070:     }
                   14071:     return $domain;
                   14072: }
                   14073: 
1.1414    raeburn  14074: sub shared_institution {
                   14075:     my ($dom) = @_;
                   14076:     my $same_intdom;
                   14077:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   14078:     if ($hostintdom ne '') {
                   14079:         my %iphost = &get_iphost();
                   14080:         my $primary_id = &domain($dom,'primary');
                   14081:         my $primary_ip = &get_host_ip($primary_id);
                   14082:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14083:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14084:                 my $intdom = &internet_dom($id);
                   14085:                 if ($intdom eq $hostintdom) {
                   14086:                     $same_intdom = 1;
                   14087:                     last;
                   14088:                 }
                   14089:             }
                   14090:         }
                   14091:     }
                   14092:     return $same_intdom;
                   14093: }
                   14094: 
1.1398    raeburn  14095: sub uses_sts {
                   14096:     my ($ignore_cache) = @_;
                   14097:     my $lonhost = $perlvar{'lonHostID'};
                   14098:     my $hostname = &hostname($lonhost);
                   14099:     my $sts_on;
                   14100:     if ($protocol{$lonhost} eq 'https') {
                   14101:         my $cachetime = 12*3600;
                   14102:         if (!$ignore_cache) {
                   14103:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14104:             if (defined($cached)) {
                   14105:                 return $sts_on;
                   14106:             }
                   14107:         }
                   14108:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14109:         my $request=new HTTP::Request('HEAD',$url);
                   14110:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14111:         if ($response->is_success) {
                   14112:             my $has_sts = $response->header('Strict-Transport-Security');
                   14113:             if ($has_sts eq '') {
                   14114:                 $sts_on = 0;
                   14115:             } else {
                   14116:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14117:                     my $maxage = $1;
                   14118:                     if ($maxage) {
                   14119:                         $sts_on = 1;
                   14120:                     } else {
                   14121:                         $sts_on = 0;
                   14122:                     }
                   14123:                 } else {
                   14124:                     $sts_on = 0;
                   14125:                 }
                   14126:             }
                   14127:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14128:         }
                   14129:     }
                   14130:     return;
                   14131: }
                   14132: 
1.31      www      14133: # ------------------------------------------------------------- Declutters URLs
                   14134: 
                   14135: sub declutter {
                   14136:     my $thisfn=shift;
1.569     albertel 14137:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14138:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14139:         $thisfn=~s{^/home/httpd/html}{};
                   14140:     }
1.31      www      14141:     $thisfn=~s/^\///;
1.697     albertel 14142:     $thisfn=~s|^adm/wrapper/||;
                   14143:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14144:     $thisfn=~s/^res\///;
1.1172    bisitz   14145:     $thisfn=~s/^priv\///;
1.1032    raeburn  14146:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14147:         $thisfn=~s/\?.+$//;
                   14148:     }
1.268     www      14149:     return $thisfn;
                   14150: }
                   14151: 
                   14152: # ------------------------------------------------------------- Clutter up URLs
                   14153: 
                   14154: sub clutter {
                   14155:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14156:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14157: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14158:        $thisfn='/res'.$thisfn; 
                   14159:     }
1.1031    raeburn  14160:     if ($thisfn !~m|^/adm|) {
                   14161: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14162: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14163: 	} else {
                   14164: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14165: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14166: 	    if ($embstyle eq 'ssi'
                   14167: 		|| ($embstyle eq 'hdn')
                   14168: 		|| ($embstyle eq 'rat')
                   14169: 		|| ($embstyle eq 'prv')
                   14170: 		|| ($embstyle eq 'ign')) {
                   14171: 		#do nothing with these
                   14172: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14173: 		|| ($embstyle eq 'emb')
                   14174: 		|| ($embstyle eq 'wrp')) {
                   14175: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14176: 	    } elsif ($embstyle eq 'unk'
                   14177: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14178: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14179: 	    } else {
1.718     www      14180: #		&logthis("Got a blank emb style");
1.695     albertel 14181: 	    }
1.694     albertel 14182: 	}
1.1343    raeburn  14183:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14184:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14185:     }
1.31      www      14186:     return $thisfn;
1.12      www      14187: }
                   14188: 
1.787     albertel 14189: sub clutter_with_no_wrapper {
                   14190:     my $uri = &clutter(shift);
                   14191:     if ($uri =~ m-^/adm/-) {
                   14192: 	$uri =~ s-^/adm/wrapper/-/-;
                   14193: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14194:     }
                   14195:     return $uri;
                   14196: }
                   14197: 
1.557     albertel 14198: sub freeze_escape {
                   14199:     my ($value)=@_;
                   14200:     if (ref($value)) {
                   14201: 	$value=&nfreeze($value);
                   14202: 	return '__FROZEN__'.&escape($value);
                   14203:     }
                   14204:     return &escape($value);
                   14205: }
                   14206: 
1.11      www      14207: 
1.557     albertel 14208: sub thaw_unescape {
                   14209:     my ($value)=@_;
                   14210:     if ($value =~ /^__FROZEN__/) {
                   14211: 	substr($value,0,10,undef);
                   14212: 	$value=&unescape($value);
                   14213: 	return &thaw($value);
                   14214:     }
                   14215:     return &unescape($value);
                   14216: }
                   14217: 
1.436     albertel 14218: sub correct_line_ends {
                   14219:     my ($result)=@_;
                   14220:     $$result =~s/\r\n/\n/mg;
                   14221:     $$result =~s/\r/\n/mg;
1.415     albertel 14222: }
1.1       albertel 14223: # ================================================================ Main Program
                   14224: 
1.184     www      14225: sub goodbye {
1.204     albertel 14226:    &logthis("Starting Shut down");
1.443     albertel 14227: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14228:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14229: #converted
1.599     albertel 14230: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14231:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14232: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14233: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14234: #1.1 only
1.870     albertel 14235: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14236: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14237: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14238: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14239:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14240:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14241:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14242:    &flushcourselogs();
                   14243:    &logthis("Shutting down");
                   14244: }
                   14245: 
1.852     albertel 14246: sub get_dns {
1.1210    raeburn  14247:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14248:     if (!$ignore_cache) {
                   14249: 	my ($content,$cached)=
                   14250: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14251: 	if ($cached) {
1.1210    raeburn  14252: 	    &$func($content,$hashref);
1.869     albertel 14253: 	    return;
                   14254: 	}
                   14255:     }
                   14256: 
                   14257:     my %alldns;
1.1379    raeburn  14258:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14259:         foreach my $dns (<$config>) {
                   14260: 	    next if ($dns !~ /^\^(\S*)/x);
                   14261:             my $line = $1;
                   14262:             my ($host,$protocol) = split(/:/,$line);
                   14263:             if ($protocol ne 'https') {
                   14264:                 $protocol = 'http';
                   14265:             }
                   14266: 	    $alldns{$host} = $protocol;
1.979     raeburn  14267:         }
1.1379    raeburn  14268:         close($config);
1.869     albertel 14269:     }
                   14270:     while (%alldns) {
1.1263    raeburn  14271: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  14272: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  14273:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  14274:         delete($alldns{$dns});
1.852     albertel 14275: 	next if ($response->is_error());
1.1379    raeburn  14276:         if ($url eq '/adm/dns/loncapaCRL') {
                   14277:             return &$func($response);
                   14278:         } else {
                   14279: 	    my @content = split("\n",$response->content);
                   14280: 	    unless ($nocache) {
                   14281: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14282: 	    }
                   14283: 	    &$func(\@content,$hashref);
                   14284:             return;
                   14285:         }
                   14286:     }
                   14287:     my $which = (split('/',$url,4))[3];
                   14288:     if ($which eq 'loncapaCRL') {
                   14289:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14290:         if (-e $diskfile) {
                   14291:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14292:         } else {
                   14293:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14294:         }
                   14295:     } else {
                   14296:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14297:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14298:             my @content = <$config>;
                   14299:             close($config);
                   14300:             &$func(\@content,$hashref);
                   14301:         }
1.852     albertel 14302:     }
1.1210    raeburn  14303:     return;
                   14304: }
                   14305: 
                   14306: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14307: sub parse_dns_checksums_tab {
1.1210    raeburn  14308:     my ($lines,$hashref) = @_;
1.1264    raeburn  14309:     my $lonhost = $perlvar{'lonHostID'};
                   14310:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14311:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14312:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14313:     my $webconfdir = '/etc/httpd/conf';
                   14314:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14315:         $webconfdir = '/etc/apache2';
                   14316:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14317:         if ($1 >= 10) {
                   14318:             $webconfdir = '/etc/apache2';
                   14319:         }
                   14320:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14321:         if ($1 >= 10.0) {
                   14322:             $webconfdir = '/etc/apache2';
                   14323:         }
                   14324:     }
1.1210    raeburn  14325:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14326:     my (%chksum,%revnum);
                   14327:     if (ref($lines) eq 'ARRAY') {
                   14328:         chomp(@{$lines});
1.1238    raeburn  14329:         my $version = shift(@{$lines});
                   14330:         if ($version eq $release) {  
1.1210    raeburn  14331:             foreach my $line (@{$lines}) {
1.1238    raeburn  14332:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14333:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14334:                     if ($webconfdir eq '/etc/apache2') {
                   14335:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14336:                     }
                   14337:                 }
1.1238    raeburn  14338:                 $chksum{$file} = $shasum;
                   14339:                 $revnum{$file} = $version;
1.1210    raeburn  14340:             }
                   14341:             if (ref($hashref) eq 'HASH') {
                   14342:                 %{$hashref} = (
                   14343:                                 sums     => \%chksum,
                   14344:                                 versions => \%revnum,
                   14345:                               );
                   14346:             }
                   14347:         }
                   14348:     }
1.869     albertel 14349:     return;
1.852     albertel 14350: }
1.1210    raeburn  14351: 
                   14352: sub fetch_dns_checksums {
1.1238    raeburn  14353:     my %checksums;
                   14354:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14355:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14356:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14357:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14358:              \%checksums);
1.1210    raeburn  14359:     return \%checksums;
                   14360: }
                   14361: 
1.1379    raeburn  14362: sub fetch_crl_pemfile {
                   14363:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14364: }
                   14365: 
                   14366: sub save_crl_pem {
                   14367:     my ($response) = @_;
1.1380    raeburn  14368:     my ($msg,$hadchanges);
1.1379    raeburn  14369:     if (ref($response)) {
                   14370:         my $now = time;
                   14371:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14372:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14373:         if (open(my $fh,'>',"$tmpcrl")) {
                   14374:             print $fh $response->content;
                   14375:             close($fh);
                   14376:             if (-e $lonca) {
                   14377:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14378:                     my $check = <PIPE>;
                   14379:                     close(PIPE);
                   14380:                     chomp($check);
                   14381:                     if ($check eq 'verify OK') {
                   14382:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  14383:                         my $backup;
1.1379    raeburn  14384:                         if (-e $dest) {
1.1380    raeburn  14385:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   14386:                                 $backup = 'ok';
                   14387:                             }
1.1379    raeburn  14388:                         }
                   14389:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   14390:                             $msg = 'ok';
1.1380    raeburn  14391:                             if ($backup) {
                   14392:                                 my (%oldnums,%newnums);
                   14393:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   14394:                                     while (<PIPE>) {
                   14395:                                         $oldnums{(split(/:/))[1]} = 1;
                   14396:                                     }
                   14397:                                     close(PIPE);
                   14398:                                 }
                   14399:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   14400:                                     while(<PIPE>) {
                   14401:                                         $newnums{(split(/:/))[1]} = 1;
                   14402:                                     }
                   14403:                                     close(PIPE);
                   14404:                                 }
                   14405:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   14406:                                     unless (exists($oldnums{$key})) {
                   14407:                                         $hadchanges = 1;
                   14408:                                         last;
                   14409:                                     }
                   14410:                                 }
                   14411:                                 unless ($hadchanges) {
                   14412:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   14413:                                         unless (exists($newnums{$key})) {
                   14414:                                             $hadchanges = 1;
                   14415:                                             last;
                   14416:                                         }
                   14417:                                     }
                   14418:                                 }
                   14419:                             }
1.1379    raeburn  14420:                         }
                   14421:                     } else {
                   14422:                         unlink($tmpcrl);
                   14423:                     }
                   14424:                 } else {
                   14425:                     unlink($tmpcrl);
                   14426:                 }
                   14427:             } else {
                   14428:                 unlink($tmpcrl);
                   14429:             }
                   14430:         }
                   14431:     }
1.1380    raeburn  14432:     return ($msg,$hadchanges);
1.1379    raeburn  14433: }
                   14434: 
1.327     albertel 14435: # ------------------------------------------------------------ Read domain file
                   14436: {
1.852     albertel 14437:     my $loaded;
1.846     albertel 14438:     my %domain;
                   14439: 
1.852     albertel 14440:     sub parse_domain_tab {
                   14441: 	my ($lines) = @_;
                   14442: 	foreach my $line (@$lines) {
                   14443: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14444: 
1.846     albertel 14445: 	    chomp($line);
1.852     albertel 14446: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14447: 	    my %this_domain;
                   14448: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14449: 			       'lang_def', 'city', 'longi', 'lati',
                   14450: 			       'primary') {
                   14451: 		$this_domain{$field} = shift(@elements);
                   14452: 	    }
                   14453: 	    $domain{$name} = \%this_domain;
1.852     albertel 14454: 	}
                   14455:     }
1.864     albertel 14456: 
                   14457:     sub reset_domain_info {
                   14458: 	undef($loaded);
                   14459: 	undef(%domain);
                   14460:     }
                   14461: 
1.852     albertel 14462:     sub load_domain_tab {
1.1293    raeburn  14463: 	my ($ignore_cache,$nocache) = @_;
                   14464: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14465: 	my $fh;
1.1359    raeburn  14466: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14467: 	    my @lines = <$fh>;
                   14468: 	    &parse_domain_tab(\@lines);
1.448     albertel 14469: 	}
1.852     albertel 14470: 	close($fh);
                   14471: 	$loaded = 1;
1.327     albertel 14472:     }
1.846     albertel 14473: 
                   14474:     sub domain {
1.852     albertel 14475: 	&load_domain_tab() if (!$loaded);
                   14476: 
1.846     albertel 14477: 	my ($name,$what) = @_;
                   14478: 	return if ( !exists($domain{$name}) );
                   14479: 
                   14480: 	if (!$what) {
                   14481: 	    return $domain{$name}{'description'};
                   14482: 	}
                   14483: 	return $domain{$name}{$what};
                   14484:     }
1.974     raeburn  14485: 
                   14486:     sub domain_info {
                   14487:         &load_domain_tab() if (!$loaded);
                   14488:         return %domain;
                   14489:     }
                   14490: 
1.327     albertel 14491: }
                   14492: 
                   14493: 
1.1       albertel 14494: # ------------------------------------------------------------- Read hosts file
                   14495: {
1.838     albertel 14496:     my %hostname;
1.844     albertel 14497:     my %hostdom;
1.845     albertel 14498:     my %libserv;
1.852     albertel 14499:     my $loaded;
1.888     albertel 14500:     my %name_to_host;
1.1074    raeburn  14501:     my %internetdom;
1.1107    raeburn  14502:     my %LC_dns_serv;
1.852     albertel 14503: 
                   14504:     sub parse_hosts_tab {
                   14505: 	my ($file) = @_;
                   14506: 	foreach my $configline (@$file) {
                   14507: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14508:             chomp($configline);
                   14509: 	    if ($configline =~ /^\^/) {
                   14510:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14511:                     $LC_dns_serv{$1} = 1;
                   14512:                 }
                   14513:                 next;
                   14514:             }
1.1074    raeburn  14515: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14516: 	    $name=~s/\s//g;
                   14517: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  14518:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14519:                     my $curr = $hostname{$id};
                   14520:                     my $skip;
                   14521:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14522:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14523:                             $skip = 1;
                   14524:                         } else {
                   14525:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14526:                         }
                   14527:                     }
                   14528:                     unless ($skip) {
                   14529:                         push(@{$name_to_host{$name}},$id);
                   14530:                     }
                   14531:                 } else {
                   14532:                     push(@{$name_to_host{$name}},$id);
                   14533:                 }
1.852     albertel 14534: 		$hostname{$id}=$name;
                   14535: 		$hostdom{$id}=$domain;
                   14536: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14537:                 if (defined($protocol)) {
                   14538:                     if ($protocol eq 'https') {
                   14539:                         $protocol{$id} = $protocol;
                   14540:                     } else {
                   14541:                         $protocol{$id} = 'http'; 
                   14542:                     }
1.968     raeburn  14543:                 } else {
1.969     raeburn  14544:                     $protocol{$id} = 'http';
1.968     raeburn  14545:                 }
1.1074    raeburn  14546:                 if (defined($intdom)) {
                   14547:                     $internetdom{$id} = $intdom;
                   14548:                 }
1.852     albertel 14549: 	    }
                   14550: 	}
                   14551:     }
1.864     albertel 14552:     
                   14553:     sub reset_hosts_info {
1.897     albertel 14554: 	&purge_remembered();
1.864     albertel 14555: 	&reset_domain_info();
                   14556: 	&reset_hosts_ip_info();
1.1339    raeburn  14557:         undef(%internetdom);
1.892     albertel 14558: 	undef(%name_to_host);
1.864     albertel 14559: 	undef(%hostname);
                   14560: 	undef(%hostdom);
                   14561: 	undef(%libserv);
                   14562: 	undef($loaded);
                   14563:     }
1.1       albertel 14564: 
1.852     albertel 14565:     sub load_hosts_tab {
1.1293    raeburn  14566: 	my ($ignore_cache,$nocache) = @_;
                   14567: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  14568: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14569: 	my @config = <$config>;
                   14570: 	&parse_hosts_tab(\@config);
                   14571: 	close($config);
                   14572: 	$loaded=1;
1.1       albertel 14573:     }
1.852     albertel 14574: 
1.838     albertel 14575:     sub hostname {
1.852     albertel 14576: 	&load_hosts_tab() if (!$loaded);
                   14577: 
1.838     albertel 14578: 	my ($lonid) = @_;
                   14579: 	return $hostname{$lonid};
                   14580:     }
1.845     albertel 14581: 
1.838     albertel 14582:     sub all_hostnames {
1.852     albertel 14583: 	&load_hosts_tab() if (!$loaded);
                   14584: 
1.838     albertel 14585: 	return %hostname;
                   14586:     }
1.845     albertel 14587: 
1.888     albertel 14588:     sub all_names {
1.1293    raeburn  14589:         my ($ignore_cache,$nocache) = @_;
                   14590: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14591: 
                   14592: 	return %name_to_host;
                   14593:     }
                   14594: 
1.974     raeburn  14595:     sub all_host_domain {
                   14596:         &load_hosts_tab() if (!$loaded);
                   14597:         return %hostdom;
                   14598:     }
                   14599: 
1.1339    raeburn  14600:     sub all_host_intdom {
                   14601:         &load_hosts_tab() if (!$loaded);
                   14602:         return %internetdom;
                   14603:     }
                   14604: 
1.845     albertel 14605:     sub is_library {
1.852     albertel 14606: 	&load_hosts_tab() if (!$loaded);
                   14607: 
1.845     albertel 14608: 	return exists($libserv{$_[0]});
                   14609:     }
                   14610: 
                   14611:     sub all_library {
1.852     albertel 14612: 	&load_hosts_tab() if (!$loaded);
                   14613: 
1.845     albertel 14614: 	return %libserv;
                   14615:     }
                   14616: 
1.1062    droeschl 14617:     sub unique_library {
                   14618: 	#2x reverse removes all hostnames that appear more than once
                   14619:         my %unique = reverse &all_library();
                   14620:         return reverse %unique;
                   14621:     }
                   14622: 
1.841     albertel 14623:     sub get_servers {
1.852     albertel 14624: 	&load_hosts_tab() if (!$loaded);
                   14625: 
1.841     albertel 14626: 	my ($domain,$type) = @_;
                   14627: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14628: 	                                          : %hostname;
                   14629: 	my %result;
1.842     albertel 14630: 	if (ref($domain) eq 'ARRAY') {
                   14631: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14632: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14633: 		    $result{$host} = $hostname;
                   14634: 		}
                   14635: 	    }
                   14636: 	} else {
                   14637: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14638: 		if ($hostdom{$host} eq $domain) {
                   14639: 		    $result{$host} = $hostname;
                   14640: 		}
1.841     albertel 14641: 	    }
                   14642: 	}
                   14643: 	return %result;
                   14644:     }
1.845     albertel 14645: 
1.1062    droeschl 14646:     sub get_unique_servers {
                   14647:         my %unique = reverse &get_servers(@_);
                   14648: 	return reverse %unique;
                   14649:     }
                   14650: 
1.844     albertel 14651:     sub host_domain {
1.852     albertel 14652: 	&load_hosts_tab() if (!$loaded);
                   14653: 
1.844     albertel 14654: 	my ($lonid) = @_;
                   14655: 	return $hostdom{$lonid};
                   14656:     }
                   14657: 
1.841     albertel 14658:     sub all_domains {
1.852     albertel 14659: 	&load_hosts_tab() if (!$loaded);
                   14660: 
1.841     albertel 14661: 	my %seen;
                   14662: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14663: 	return @uniq;
                   14664:     }
1.1074    raeburn  14665: 
                   14666:     sub internet_dom {
                   14667:         &load_hosts_tab() if (!$loaded);
                   14668: 
                   14669:         my ($lonid) = @_;
                   14670:         return $internetdom{$lonid};
                   14671:     }
1.1107    raeburn  14672: 
                   14673:     sub is_LC_dns {
                   14674:         &load_hosts_tab() if (!$loaded);
                   14675: 
                   14676:         my ($hostname) = @_;
                   14677:         return exists($LC_dns_serv{$hostname});
                   14678:     }
                   14679: 
1.1       albertel 14680: }
                   14681: 
1.847     albertel 14682: { 
                   14683:     my %iphost;
1.856     albertel 14684:     my %name_to_ip;
                   14685:     my %lonid_to_ip;
1.869     albertel 14686: 
1.847     albertel 14687:     sub get_hosts_from_ip {
                   14688: 	my ($ip) = @_;
                   14689: 	my %iphosts = &get_iphost();
                   14690: 	if (ref($iphosts{$ip})) {
                   14691: 	    return @{$iphosts{$ip}};
                   14692: 	}
                   14693: 	return;
1.839     albertel 14694:     }
1.864     albertel 14695:     
                   14696:     sub reset_hosts_ip_info {
                   14697: 	undef(%iphost);
                   14698: 	undef(%name_to_ip);
                   14699: 	undef(%lonid_to_ip);
                   14700:     }
1.856     albertel 14701: 
                   14702:     sub get_host_ip {
                   14703: 	my ($lonid) = @_;
                   14704: 	if (exists($lonid_to_ip{$lonid})) {
                   14705: 	    return $lonid_to_ip{$lonid};
                   14706: 	}
                   14707: 	my $name=&hostname($lonid);
                   14708:    	my $ip = gethostbyname($name);
                   14709: 	return if (!$ip || length($ip) ne 4);
                   14710: 	$ip=inet_ntoa($ip);
                   14711: 	$name_to_ip{$name}   = $ip;
                   14712: 	$lonid_to_ip{$lonid} = $ip;
                   14713: 	return $ip;
                   14714:     }
1.847     albertel 14715:     
                   14716:     sub get_iphost {
1.1293    raeburn  14717: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14718: 
1.869     albertel 14719: 	if (!$ignore_cache) {
                   14720: 	    if (%iphost) {
                   14721: 		return %iphost;
                   14722: 	    }
                   14723: 	    my ($ip_info,$cached)=
                   14724: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14725: 	    if ($cached) {
                   14726: 		%iphost      = %{$ip_info->[0]};
                   14727: 		%name_to_ip  = %{$ip_info->[1]};
                   14728: 		%lonid_to_ip = %{$ip_info->[2]};
                   14729: 		return %iphost;
                   14730: 	    }
                   14731: 	}
1.894     albertel 14732: 
                   14733: 	# get yesterday's info for fallback
                   14734: 	my %old_name_to_ip;
                   14735: 	my ($ip_info,$cached)=
                   14736: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14737: 	if ($cached) {
                   14738: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14739: 	}
                   14740: 
1.1293    raeburn  14741: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14742: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14743: 	    my $ip;
                   14744: 	    if (!exists($name_to_ip{$name})) {
                   14745: 		$ip = gethostbyname($name);
                   14746: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14747: 		    if (defined($old_name_to_ip{$name})) {
                   14748: 			$ip = $old_name_to_ip{$name};
                   14749: 			&logthis("Can't find $name defaulting to old $ip");
                   14750: 		    } else {
                   14751: 			&logthis("Name $name no IP found");
                   14752: 			next;
                   14753: 		    }
                   14754: 		} else {
                   14755: 		    $ip=inet_ntoa($ip);
1.847     albertel 14756: 		}
                   14757: 		$name_to_ip{$name} = $ip;
                   14758: 	    } else {
                   14759: 		$ip = $name_to_ip{$name};
1.653     albertel 14760: 	    }
1.888     albertel 14761: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14762: 		$lonid_to_ip{$id} = $ip;
                   14763: 	    }
                   14764: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14765: 	}
1.1293    raeburn  14766:         unless ($nocache) {
                   14767: 	    &do_cache_new('iphost','iphost',
                   14768: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14769: 		          48*60*60);
                   14770:         }
1.869     albertel 14771: 
1.847     albertel 14772: 	return %iphost;
1.598     albertel 14773:     }
                   14774: 
1.992     raeburn  14775:     #
                   14776:     #  Given a DNS returns the loncapa host name for that DNS 
                   14777:     # 
                   14778:     sub host_from_dns {
                   14779:         my ($dns) = @_;
                   14780:         my @hosts;
                   14781:         my $ip;
                   14782: 
1.993     raeburn  14783:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14784:             $ip = $name_to_ip{$dns};
                   14785:         }
                   14786:         if (!$ip) {
                   14787:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14788:             if (length($ip) == 4) { 
                   14789: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14790:             }
                   14791:         }
                   14792:         if ($ip) {
                   14793: 	    @hosts = get_hosts_from_ip($ip);
                   14794: 	    return $hosts[0];
                   14795:         }
                   14796:         return undef;
1.986     foxr     14797:     }
1.992     raeburn  14798: 
1.1074    raeburn  14799:     sub get_internet_names {
                   14800:         my ($lonid) = @_;
                   14801:         return if ($lonid eq '');
                   14802:         my ($idnref,$cached)=
                   14803:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14804:         if ($cached) {
                   14805:             return $idnref;
                   14806:         }
                   14807:         my $ip = &get_host_ip($lonid);
                   14808:         my @hosts = &get_hosts_from_ip($ip);
                   14809:         my %iphost = &get_iphost();
                   14810:         my (@idns,%seen);
                   14811:         foreach my $id (@hosts) {
                   14812:             my $dom = &host_domain($id);
                   14813:             my $prim_id = &domain($dom,'primary');
                   14814:             my $prim_ip = &get_host_ip($prim_id);
                   14815:             next if ($seen{$prim_ip});
                   14816:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14817:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14818:                     my $intdom = &internet_dom($id);
                   14819:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14820:                         push(@idns,$intdom);
                   14821:                     }
                   14822:                 }
                   14823:             }
                   14824:             $seen{$prim_ip} = 1;
                   14825:         }
1.1219    raeburn  14826:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14827:     }
                   14828: 
1.986     foxr     14829: }
                   14830: 
1.1079    raeburn  14831: sub all_loncaparevs {
1.1249    raeburn  14832:     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  14833: }
                   14834: 
1.1227    raeburn  14835: # ---------------------------------------------------------- Read loncaparev table
                   14836: {
                   14837:     sub load_loncaparevs { 
                   14838:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14839:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14840:                 while (my $configline=<$config>) {
                   14841:                     chomp($configline);
                   14842:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14843:                     $loncaparevs{$hostid}=$loncaparev;
                   14844:                 }
                   14845:                 close($config);
                   14846:             }
                   14847:         }
                   14848:     }
                   14849: }
                   14850: 
                   14851: # ---------------------------------------------------------- Read serverhostID table
                   14852: {
                   14853:     sub load_serverhomeIDs {
                   14854:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14855:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14856:                 while (my $configline=<$config>) {
                   14857:                     chomp($configline);
                   14858:                     my ($name,$id)=split(/:/,$configline);
                   14859:                     $serverhomeIDs{$name}=$id;
                   14860:                 }
                   14861:                 close($config);
                   14862:             }
                   14863:         }
                   14864:     }
                   14865: }
                   14866: 
                   14867: 
1.862     albertel 14868: BEGIN {
                   14869: 
                   14870: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14871:     unless ($readit) {
                   14872: {
                   14873:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14874:     %perlvar = (%perlvar,%{$configvars});
                   14875: }
                   14876: 
                   14877: 
1.1       albertel 14878: # ------------------------------------------------------ Read spare server file
                   14879: {
1.1359    raeburn  14880:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14881: 
                   14882:     while (my $configline=<$config>) {
                   14883:        chomp($configline);
1.284     matthew  14884:        if ($configline) {
1.784     albertel 14885: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14886: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14887: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14888:        }
                   14889:     }
1.448     albertel 14890:     close($config);
1.1       albertel 14891: }
1.11      www      14892: # ------------------------------------------------------------ Read permissions
                   14893: {
1.1359    raeburn  14894:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14895: 
                   14896:     while (my $configline=<$config>) {
1.448     albertel 14897: 	chomp($configline);
                   14898: 	if ($configline) {
                   14899: 	    my ($role,$perm)=split(/ /,$configline);
                   14900: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14901: 	}
1.11      www      14902:     }
1.448     albertel 14903:     close($config);
1.11      www      14904: }
                   14905: 
                   14906: # -------------------------------------------- Read plain texts for permissions
                   14907: {
1.1359    raeburn  14908:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14909: 
                   14910:     while (my $configline=<$config>) {
1.448     albertel 14911: 	chomp($configline);
                   14912: 	if ($configline) {
1.742     raeburn  14913: 	    my ($short,@plain)=split(/:/,$configline);
                   14914:             %{$prp{$short}} = ();
                   14915: 	    if (@plain > 0) {
                   14916:                 $prp{$short}{'std'} = $plain[0];
                   14917:                 for (my $i=1; $i<@plain; $i++) {
                   14918:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14919:                 }
                   14920:             }
1.448     albertel 14921: 	}
1.135     www      14922:     }
1.448     albertel 14923:     close($config);
1.135     www      14924: }
                   14925: 
                   14926: # ---------------------------------------------------------- Read package table
                   14927: {
1.1359    raeburn  14928:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14929: 
                   14930:     while (my $configline=<$config>) {
1.483     albertel 14931: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14932: 	chomp($configline);
                   14933: 	my ($short,$plain)=split(/:/,$configline);
                   14934: 	my ($pack,$name)=split(/\&/,$short);
                   14935: 	if ($plain ne '') {
                   14936: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14937: 	    $packagetab{$short}=$plain; 
                   14938: 	}
1.11      www      14939:     }
1.448     albertel 14940:     close($config);
1.329     matthew  14941: }
                   14942: 
1.1073    raeburn  14943: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14944: 
                   14945: &load_loncaparevs();
1.1073    raeburn  14946: 
1.1074    raeburn  14947: # ---------------------------------------------------------- Read serverhostID table
                   14948: 
1.1227    raeburn  14949: &load_serverhomeIDs();
                   14950: 
                   14951: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14952: {
                   14953:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14954:     if (-e $file) {
                   14955:         my $parser = HTML::LCParser->new($file);
                   14956:         while (my $token = $parser->get_token()) {
                   14957:             if ($token->[0] eq 'S') {
                   14958:                 my $item = $token->[1];
                   14959:                 my $name = $token->[2]{'name'};
                   14960:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14961:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14962:                 my $namematch = $token->[2]{'namematch'};
                   14963:                 if ($item eq 'parameter') {
                   14964:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14965:                         my $release = $parser->get_text();
                   14966:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14967:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14968:                     }
                   14969:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14970:                     my $release = $parser->get_text();
                   14971:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14972:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14973:                 }
                   14974:             }
                   14975:         }
                   14976:     }
1.1073    raeburn  14977: }
                   14978: 
1.1138    raeburn  14979: # ---------------------------------------------------------- Read managers table
                   14980: {
                   14981:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14982:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14983:             while (my $configline=<$config>) {
                   14984:                 chomp($configline);
                   14985:                 next if ($configline =~ /^\#/);
                   14986:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14987:                     $managerstab{$configline} = 1;
                   14988:                 }
                   14989:             }
                   14990:             close($config);
                   14991:         }
                   14992:     }
                   14993: }
                   14994: 
1.329     matthew  14995: # ------------- set up temporary directory
                   14996: {
1.1117    foxr     14997:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14998: 
1.11      www      14999: }
                   15000: 
1.1405    raeburn  15001: # ------------- set default texengine (domain default overrides this)
                   15002: {
                   15003:     $deftex = LONCAPA::texengine();
                   15004: }
                   15005: 
1.794     albertel 15006: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15007: 				'compress_threshold'=> 20_000,
                   15008:  			        });
1.185     www      15009: 
1.281     www      15010: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15011: $dumpcount=0;
1.958     www      15012: $locknum=0;
1.22      www      15013: 
1.163     harris41 15014: &logtouch();
1.672     albertel 15015: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15016: $readit=1;
1.564     albertel 15017:     {
                   15018: 	use integer;
                   15019: 	my $test=(2**32)+1;
1.568     albertel 15020: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15021: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15022:     }
1.195     www      15023: }
1.1       albertel 15024: }
1.179     www      15025: 
1.1       albertel 15026: 1;
1.191     harris41 15027: __END__
                   15028: 
1.243     albertel 15029: =pod
                   15030: 
1.191     harris41 15031: =head1 NAME
                   15032: 
1.243     albertel 15033: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15034: 
                   15035: =head1 SYNOPSIS
                   15036: 
1.243     albertel 15037: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15038: 
                   15039:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15040: 
1.243     albertel 15041: Common parameters:
                   15042: 
                   15043: =over 4
                   15044: 
                   15045: =item *
                   15046: 
                   15047: $uname : an internal username (if $cname expecting a course Id specifically)
                   15048: 
                   15049: =item *
                   15050: 
                   15051: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15052: 
                   15053: =item *
                   15054: 
                   15055: $symb : a resource instance identifier
                   15056: 
                   15057: =item *
                   15058: 
                   15059: $namespace : the name of a .db file that contains the data needed or
                   15060: being set.
                   15061: 
                   15062: =back
                   15063: 
1.394     bowersj2 15064: =head1 OVERVIEW
1.191     harris41 15065: 
1.394     bowersj2 15066: lonnet provides subroutines which interact with the
                   15067: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15068: about classes, users, and resources.
1.243     albertel 15069: 
                   15070: For many of these objects you can also use this to store data about
                   15071: them or modify them in various ways.
1.191     harris41 15072: 
1.394     bowersj2 15073: =head2 Symbs
1.191     harris41 15074: 
1.394     bowersj2 15075: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15076: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15077: map, the resource number of the resource in the map, and the URL of
                   15078: the resource itself. The latter is somewhat redundant, but might help
                   15079: if maps change.
                   15080: 
                   15081: An example is
                   15082: 
                   15083:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15084: 
                   15085: The respective map entry is
                   15086: 
                   15087:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15088:   title="Problem 2">
                   15089:  </resource>
                   15090: 
                   15091: Symbs are used by the random number generator, as well as to store and
                   15092: restore data specific to a certain instance of for example a problem.
                   15093: 
                   15094: =head2 Storing And Retrieving Data
                   15095: 
                   15096: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15097: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15098: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15099: is is the non-critical message twin of cstore. These functions are for
                   15100: handlers to store a perl hash to a user's permanent data space in an
                   15101: easy manner, and to retrieve it again on another call. It is expected
                   15102: that a handler would use this once at the beginning to retrieve data,
                   15103: and then again once at the end to send only the new data back.
                   15104: 
                   15105: The data is stored in the user's data directory on the user's
                   15106: homeserver under the ID of the course.
                   15107: 
                   15108: The hash that is returned by restore will have all of the previous
                   15109: value for all of the elements of the hash.
                   15110: 
                   15111: Example:
                   15112: 
                   15113:  #creating a hash
                   15114:  my %hash;
                   15115:  $hash{'foo'}='bar';
                   15116: 
                   15117:  #storing it
                   15118:  &Apache::lonnet::cstore(\%hash);
                   15119: 
                   15120:  #changing a value
                   15121:  $hash{'foo'}='notbar';
                   15122: 
                   15123:  #adding a new value
                   15124:  $hash{'bar'}='foo';
                   15125:  &Apache::lonnet::cstore(\%hash);
                   15126: 
                   15127:  #retrieving the hash
                   15128:  my %history=&Apache::lonnet::restore();
                   15129: 
                   15130:  #print the hash
                   15131:  foreach my $key (sort(keys(%history))) {
                   15132:    print("\%history{$key} = $history{$key}");
                   15133:  }
                   15134: 
                   15135: Will print out:
1.191     harris41 15136: 
1.394     bowersj2 15137:  %history{1:foo} = bar
                   15138:  %history{1:keys} = foo:timestamp
                   15139:  %history{1:timestamp} = 990455579
                   15140:  %history{2:bar} = foo
                   15141:  %history{2:foo} = notbar
                   15142:  %history{2:keys} = foo:bar:timestamp
                   15143:  %history{2:timestamp} = 990455580
                   15144:  %history{bar} = foo
                   15145:  %history{foo} = notbar
                   15146:  %history{timestamp} = 990455580
                   15147:  %history{version} = 2
                   15148: 
                   15149: Note that the special hash entries C<keys>, C<version> and
                   15150: C<timestamp> were added to the hash. C<version> will be equal to the
                   15151: total number of versions of the data that have been stored. The
                   15152: C<timestamp> attribute will be the UNIX time the hash was
                   15153: stored. C<keys> is available in every historical section to list which
                   15154: keys were added or changed at a specific historical revision of a
                   15155: hash.
                   15156: 
                   15157: B<Warning>: do not store the hash that restore returns directly. This
                   15158: will cause a mess since it will restore the historical keys as if the
                   15159: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15160: 
1.394     bowersj2 15161: Calling convention:
1.191     harris41 15162: 
1.1225    raeburn  15163:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15164:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15165: 
1.394     bowersj2 15166: For more detailed information, see lonnet specific documentation.
1.191     harris41 15167: 
1.394     bowersj2 15168: =head1 RETURN MESSAGES
1.191     harris41 15169: 
1.394     bowersj2 15170: =over 4
1.191     harris41 15171: 
1.394     bowersj2 15172: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15173: 
1.394     bowersj2 15174: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15175: when the connection is brought back up
1.191     harris41 15176: 
1.394     bowersj2 15177: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15178: for later delivery
1.191     harris41 15179: 
1.967     bisitz   15180: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15181: 
1.394     bowersj2 15182: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15183: that was requested
1.191     harris41 15184: 
1.243     albertel 15185: =back
1.191     harris41 15186: 
1.243     albertel 15187: =head1 PUBLIC SUBROUTINES
1.191     harris41 15188: 
1.243     albertel 15189: =head2 Session Environment Functions
1.191     harris41 15190: 
1.243     albertel 15191: =over 4
1.191     harris41 15192: 
1.394     bowersj2 15193: =item * 
                   15194: X<appenv()>
1.949     raeburn  15195: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15196: the user envirnoment file, and will be restored for each access this
1.620     albertel 15197: user makes during this session, also modifies the %env for the current
1.949     raeburn  15198: process. Optional rolesarrayref - if defined contains a reference to an array
                   15199: of roles which are exempt from the restriction on modifying user.role entries 
                   15200: in the user's environment.db and in %env.    
1.191     harris41 15201: 
                   15202: =item *
1.394     bowersj2 15203: X<delenv()>
1.987     raeburn  15204: B<delenv($delthis,$regexp)>: removes all items from the session
                   15205: environment file that begin with $delthis. If the 
                   15206: optional second arg - $regexp - is true, $delthis is treated as a 
                   15207: regular expression, otherwise \Q$delthis\E is used. 
                   15208: The values are also deleted from the current processes %env.
1.191     harris41 15209: 
1.795     albertel 15210: =item * get_env_multiple($name) 
                   15211: 
                   15212: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15213: values may be defined and end up as an array ref.
                   15214: 
                   15215: returns an array of values
                   15216: 
1.243     albertel 15217: =back
                   15218: 
                   15219: =head2 User Information
1.191     harris41 15220: 
1.243     albertel 15221: =over 4
1.191     harris41 15222: 
                   15223: =item *
1.394     bowersj2 15224: X<queryauthenticate()>
                   15225: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15226: authentication scheme
                   15227: 
                   15228: =item *
1.394     bowersj2 15229: X<authenticate()>
1.1073    raeburn  15230: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15231: authenticate user from domain's lib servers (first use the current
                   15232: one). C<$upass> should be the users password.
1.1073    raeburn  15233: $checkdefauth is optional (value is 1 if a check should be made to
                   15234:    authenticate user using default authentication method, and allow
                   15235:    account creation if username does not have account in the domain).
                   15236: $clientcancheckhost is optional (value is 1 if checking whether the
                   15237:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15238: 
                   15239: =item *
1.394     bowersj2 15240: X<homeserver()>
                   15241: B<homeserver($uname,$udom)>: find the server which has
                   15242: the user's directory and files (there must be only one), this caches
                   15243: the answer, and also caches if there is a borken connection.
1.191     harris41 15244: 
                   15245: =item *
1.394     bowersj2 15246: X<idget()>
1.1300    raeburn  15247: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   15248: a list of student/employee IDs or clicker IDs
                   15249: (student/employee IDs are a unique resource in a domain, there must be 
                   15250: only 1 ID per username, and only 1 username per ID in a specific domain).
                   15251: clickerIDs are not necessarily unique, as students might share clickers.
                   15252: (returns hash: id=>name,id=>name)
1.191     harris41 15253: 
                   15254: =item *
1.394     bowersj2 15255: X<idrget()>
                   15256: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15257: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15258: 
                   15259: =item *
1.394     bowersj2 15260: X<idput()>
1.1300    raeburn  15261: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   15262: names and associated student/employee IDs or clicker IDs.
                   15263: 
                   15264: =item *
                   15265: X<iddel()>
                   15266: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15267: student/employee ID or clicker ID username look-ups from domain.
                   15268: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15269: If no $uhome is provided, it will be determined usig &homeserver()
                   15270: for each user.  If no $namespace is provided, the default is ids.
                   15271: 
                   15272: =item *
                   15273: X<updateclickers()>
                   15274: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15275: clicker ID-to-username look-ups in clickers.db on library server.
                   15276: Permitted actions are add or del (i.e., add or delete). The 
                   15277: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15278: value is an escaped comma-separated list of usernames (for whom the
                   15279: library server is the homeserver), who registered that particular ID.
                   15280: If $critical is true, the update will be sent via &critical, otherwise
                   15281: &reply() will be used.
1.191     harris41 15282: 
                   15283: =item *
1.394     bowersj2 15284: X<rolesinit()>
1.1169    droeschl 15285: B<rolesinit($udom,$username)>: get user privileges.
                   15286: returns user role, first access and timer interval hashes
1.243     albertel 15287: 
                   15288: =item *
1.1171    droeschl 15289: X<privileged()>
                   15290: B<privileged($username,$domain)>: returns a true if user has a
                   15291: privileged and active role (i.e. su or dc), false otherwise.
                   15292: 
                   15293: =item *
1.551     albertel 15294: X<getsection()>
                   15295: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15296: course $cname, return section name/number or '' for "not in course"
                   15297: and '-1' for "no section"
                   15298: 
                   15299: =item *
1.394     bowersj2 15300: X<userenvironment()>
                   15301: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15302: passed in @what from the requested user's environment, returns a hash
                   15303: 
1.858     raeburn  15304: =item * 
                   15305: X<userlog_query()>
1.859     albertel 15306: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15307: activity.log file. %filters defines filters applied when parsing the
                   15308: log file. These can be start or end timestamps, or the type of action
                   15309: - log to look for Login or Logout events, check for Checkin or
                   15310: Checkout, role for role selection. The response is in the form
                   15311: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15312: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15313: 
1.243     albertel 15314: =back
                   15315: 
                   15316: =head2 User Roles
                   15317: 
                   15318: =over 4
                   15319: 
                   15320: =item *
                   15321: 
1.1284    raeburn  15322: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15323: returns codes for allowed actions.
                   15324: 
                   15325: The first argument is required, all others are optional.
                   15326: 
                   15327: $priv is the privilege being checked.
                   15328: $uri contains additional information about what is being checked for access (e.g.,
                   15329: URL, course ID etc.). 
                   15330: $symb is the unique resource instance identifier in a course; if needed,
                   15331: but not provided, it will be retrieved via a call to &symbread(). 
                   15332: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15333: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15334: files).
                   15335: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15336: prevents recursive calls to &allowed.
                   15337: 
1.243     albertel 15338:  F: full access
                   15339:  U,I,K: authentication modes (cxx only)
                   15340:  '': forbidden
                   15341:  1: user needs to choose course
                   15342:  2: browse allowed
1.766     albertel 15343:  A: passphrase authentication needed
1.1284    raeburn  15344:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  15345:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15346: 
                   15347: =item *
                   15348: 
1.1192    raeburn  15349: constructaccess($url,$setpriv) : check for access to construction space URL
                   15350: 
                   15351: See if the owner domain and name in the URL match those in the
                   15352: expected environment.  If so, return three element list
                   15353: ($ownername,$ownerdomain,$ownerhome).
                   15354: 
                   15355: Otherwise return the null string.
                   15356: 
                   15357: If second argument 'setpriv' is true, it assigns the privileges,
                   15358: and returns the same three element list, unless the owner has
                   15359: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15360: in which case the null string is returned.
                   15361: 
                   15362: =item *
                   15363: 
1.1326    raeburn  15364: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15365: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15366: for system, domain, and course level. $uname and $udom are optional (current
                   15367: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15368: 
                   15369: =item *
                   15370: 
1.988     raeburn  15371: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15372: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15373: $type is Course (default) or Community.
1.988     raeburn  15374: If $forcedefault evaluates to true, text returned will be default 
                   15375: text for $type. Otherwise, if this is a course, the text returned 
                   15376: will be a custom name for the role (if defined in the course's 
                   15377: environment).  If no custom name is defined the default is returned.
                   15378:    
1.832     raeburn  15379: =item *
                   15380: 
1.1219    raeburn  15381: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15382: All arguments are optional. Returns a hash of a roles, either for
                   15383: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15384: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15385: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15386: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15387: For each key, value is set to colon-separated start and end times for
                   15388: the role.  If no username and domain are specified, will default to
1.934     raeburn  15389: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15390: of role statuses (active, future or previous), roles 
                   15391: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15392: to restrict the list of roles reported. If no array ref is 
                   15393: provided for types, will default to return only active roles.
1.834     albertel 15394: 
1.1195    raeburn  15395: =item *
                   15396: 
                   15397: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  15398: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   15399: 
                   15400: Additional optional arguments are: $type (if role checking is to be restricted 
                   15401: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  15402: available roles) or future (roles available in the future), and
                   15403: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  15404: have active Domain Coordinator role in course's domain or in additional
                   15405: domains (specified in 'Domains to check for privileged users' in course
                   15406: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15407: 
                   15408: =item *
                   15409: 
                   15410: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15411: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15412: $possdomains and $possroles are optional array refs -- to domains to check and
                   15413: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15414: users' roles.db to check for a dc or su role in any domain. This can be
                   15415: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15416: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15417: this then allows &privileged_by_domain() to be used, which caches the identity
                   15418: of privileged users, eliminating the need for repeated calls to &dump().
                   15419: 
                   15420: =item *
                   15421: 
                   15422: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15423: where the outer hash keys are domains specified in the $possdomains array ref,
                   15424: next inner hash keys are privileged roles specified in the $roles array ref,
                   15425: and the innermost hash contains key = value pairs for username:domain = end:start
                   15426: for active or future "privileged" users with that role in that domain. To avoid
                   15427: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15428: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  15429: 
1.243     albertel 15430: =back
                   15431: 
                   15432: =head2 User Modification
                   15433: 
                   15434: =over 4
                   15435: 
                   15436: =item *
                   15437: 
1.957     raeburn  15438: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15439: user for the level given by URL.  Optional start and end dates (leave empty
                   15440: string or zero for "no date")
1.191     harris41 15441: 
                   15442: =item *
                   15443: 
1.243     albertel 15444: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15445: change a users, password, possible return values are: ok,
                   15446: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15447: refused
1.191     harris41 15448: 
                   15449: =item *
                   15450: 
1.243     albertel 15451: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15452: 
                   15453: =item *
                   15454: 
1.1058    raeburn  15455: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15456:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15457: 
                   15458: will update user information (firstname,middlename,lastname,generation,
                   15459: permanentemail), and if forceid is true, student/employee ID also.
                   15460: A user's institutional affiliation(s) can also be updated.
                   15461: User information fields will not be overwritten with empty entries 
                   15462: unless the field is included in the $candelete array reference.
                   15463: This array is included when a single user is modified via "Manage Users",
                   15464: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15465: 
                   15466: =item *
                   15467: 
1.286     matthew  15468: modifystudent
                   15469: 
1.957     raeburn  15470: modify a student's enrollment and identification information.
1.1235    raeburn  15471: The course id is resolved based on the current user's environment.  
                   15472: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15473: associated with a course.
                   15474: 
1.297     matthew  15475: This call is essentially a wrapper for lonnet::modifyuser and
                   15476: lonnet::modify_student_enrollment
1.286     matthew  15477: 
                   15478: Inputs: 
                   15479: 
                   15480: =over 4
                   15481: 
1.957     raeburn  15482: =item B<$udom> Student's loncapa domain
1.286     matthew  15483: 
1.957     raeburn  15484: =item B<$uname> Student's loncapa login name
1.286     matthew  15485: 
1.964     bisitz   15486: =item B<$uid> Student/Employee ID
1.286     matthew  15487: 
1.957     raeburn  15488: =item B<$umode> Student's authentication mode
1.286     matthew  15489: 
1.957     raeburn  15490: =item B<$upass> Student's password
1.286     matthew  15491: 
1.957     raeburn  15492: =item B<$first> Student's first name
1.286     matthew  15493: 
1.957     raeburn  15494: =item B<$middle> Student's middle name
1.286     matthew  15495: 
1.957     raeburn  15496: =item B<$last> Student's last name
1.286     matthew  15497: 
1.957     raeburn  15498: =item B<$gene> Student's generation
1.286     matthew  15499: 
1.957     raeburn  15500: =item B<$usec> Student's section in course
1.286     matthew  15501: 
                   15502: =item B<$end> Unix time of the roles expiration
                   15503: 
                   15504: =item B<$start> Unix time of the roles start date
                   15505: 
                   15506: =item B<$forceid> If defined, allow $uid to be changed
                   15507: 
                   15508: =item B<$desiredhome> server to use as home server for student
                   15509: 
1.957     raeburn  15510: =item B<$email> Student's permanent e-mail address
                   15511: 
                   15512: =item B<$type> Type of enrollment (auto or manual)
                   15513: 
1.963     raeburn  15514: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15515: 
                   15516: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15517: 
1.963     raeburn  15518: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15519: 
1.963     raeburn  15520: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15521: 
1.1216    raeburn  15522: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15523: 
                   15524: =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  15525: 
1.286     matthew  15526: =back
1.297     matthew  15527: 
                   15528: =item *
                   15529: 
                   15530: modify_student_enrollment
                   15531: 
1.1235    raeburn  15532: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15533: 'role.request.course' must be defined for this function to proceed.
                   15534: 
                   15535: Inputs:
                   15536: 
                   15537: =over 4
                   15538: 
1.1235    raeburn  15539: =item $udom, student's domain
1.297     matthew  15540: 
1.1235    raeburn  15541: =item $uname, student's name
1.297     matthew  15542: 
1.1235    raeburn  15543: =item $uid, student's user id
1.297     matthew  15544: 
1.1235    raeburn  15545: =item $first, student's first name
1.297     matthew  15546: 
                   15547: =item $middle
                   15548: 
                   15549: =item $last
                   15550: 
                   15551: =item $gene
                   15552: 
                   15553: =item $usec
                   15554: 
                   15555: =item $end
                   15556: 
                   15557: =item $start
                   15558: 
1.957     raeburn  15559: =item $type
                   15560: 
                   15561: =item $locktype
                   15562: 
                   15563: =item $cid
                   15564: 
                   15565: =item $selfenroll
                   15566: 
                   15567: =item $context
                   15568: 
1.1216    raeburn  15569: =item $credits, number of credits student will earn from this class
                   15570: 
1.1314    raeburn  15571: =item $instsec, institutional course section code for student
                   15572: 
1.297     matthew  15573: =back
                   15574: 
1.191     harris41 15575: 
                   15576: =item *
                   15577: 
1.243     albertel 15578: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15579: custom role; give a custom role to a user for the level given by URL.  Specify
                   15580: name and domain of role author, and role name
1.191     harris41 15581: 
                   15582: =item *
                   15583: 
1.243     albertel 15584: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15585: 
                   15586: =item *
                   15587: 
1.243     albertel 15588: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15589: 
                   15590: =back
                   15591: 
                   15592: =head2 Course Infomation
                   15593: 
                   15594: =over 4
1.191     harris41 15595: 
                   15596: =item *
                   15597: 
1.1118    foxr     15598: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15599: specified course id, including all environment settings for the
                   15600: course, the description of the course will be in the hash under the
                   15601: key 'description'
1.191     harris41 15602: 
1.1118    foxr     15603: $options is an optional parameter that if supplied is a hash reference that controls
                   15604: what how this function works.  It has the following key/values:
                   15605: 
                   15606: =over 4
                   15607: 
                   15608: =item freshen_cache
                   15609: 
                   15610: If defined, and the environment cache for the course is valid, it is 
                   15611: returned in the returned hash.
                   15612: 
                   15613: =item one_time
                   15614: 
                   15615: If defined, the last cache time is set to _now_
                   15616: 
                   15617: =item user
                   15618: 
                   15619: If defined, the supplied username is used instead of the current user.
                   15620: 
                   15621: 
                   15622: =back
                   15623: 
1.191     harris41 15624: =item *
                   15625: 
1.624     albertel 15626: resdata($name,$domain,$type,@which) : request for current parameter
                   15627: setting for a specific $type, where $type is either 'course' or 'user',
                   15628: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15629: answers for 10 minutes.
1.243     albertel 15630: 
1.877     foxr     15631: =item *
                   15632: 
                   15633: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15634: data base, returning a hash that is keyed by the resource name and has
                   15635: values that are the resource value.  I believe that the timestamps and
                   15636: versions are also returned.
                   15637: 
1.1236    raeburn  15638: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15639: supplemental content area. This routine caches the number of files for 
                   15640: 10 minutes.
                   15641: 
1.243     albertel 15642: =back
                   15643: 
                   15644: =head2 Course Modification
                   15645: 
                   15646: =over 4
1.191     harris41 15647: 
                   15648: =item *
                   15649: 
1.243     albertel 15650: writecoursepref($courseid,%prefs) : write preferences (environment
                   15651: database) for a course
1.191     harris41 15652: 
                   15653: =item *
                   15654: 
1.1011    raeburn  15655: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15656: 
                   15657: =item *
                   15658: 
1.1038    raeburn  15659: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15660: 
1.1167    droeschl 15661: =item *
                   15662: 
                   15663: is_course($courseid), is_course($cdom, $cnum)
                   15664: 
                   15665: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15666: two component version $cdom, $cnum. It checks if the specified course exists.
                   15667: 
                   15668: Returns:
                   15669:     undef if the course doesn't exist, otherwise
                   15670:     in scalar context the combined courseid.
                   15671:     in list context the two components of the course identifier, domain and 
                   15672:     courseid.    
                   15673: 
1.243     albertel 15674: =back
                   15675: 
1.1401    raeburn  15676: =head2 Bubblesheet Configuration
                   15677: 
                   15678: =over 4
                   15679: 
                   15680: =item *
                   15681: 
                   15682: get_scantron_config($which)
                   15683: 
                   15684: $which - the name of the configuration to parse from the file.
                   15685: 
                   15686: Parses and returns the bubblesheet configuration line selected as a
                   15687: hash of configuration file fields.
                   15688: 
                   15689: 
                   15690: Returns:
                   15691:     If the named configuration is not in the file, an empty
                   15692:     hash is returned.
                   15693: 
                   15694:     a hash with the fields
                   15695:       name         - internal name for the this configuration setup
                   15696:       description  - text to display to operator that describes this config
                   15697:       CODElocation - if 0 or the string 'none'
                   15698:                           - no CODE exists for this config
                   15699:                      if -1 || the string 'letter'
                   15700:                           - a CODE exists for this config and is
                   15701:                             a string of letters
                   15702:                      Unsupported value (but planned for future support)
                   15703:                           if a positive integer
                   15704:                                - The CODE exists as the first n items from
                   15705:                                  the question section of the form
                   15706:                           if the string 'number'
                   15707:                                - The CODE exists for this config and is
                   15708:                                  a string of numbers
                   15709:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15710:                      the CODE starts
                   15711:       CODElength  - length of the CODE
                   15712:       IDstart     - column where the student/employee ID starts
                   15713:       IDlength    - length of the student/employee ID info
                   15714:       Qstart      - column where the information from the bubbled
                   15715:                     'questions' start
                   15716:       Qlength     - number of columns comprising a single bubble line from
                   15717:                     the sheet. (usually either 1 or 10)
                   15718:       Qon         - either a single character representing the character used
                   15719:                     to signal a bubble was chosen in the positional setup, or
                   15720:                     the string 'letter' if the letter of the chosen bubble is
                   15721:                     in the final, or 'number' if a number representing the
                   15722:                     chosen bubble is in the file (1->A 0->J)
                   15723:       Qoff        - the character used to represent that a bubble was
                   15724:                     left blank
                   15725:       PaperID     - if the scanning process generates a unique number for each
                   15726:                     sheet scanned the column that this ID number starts in
                   15727:       PaperIDlength - number of columns that comprise the unique ID number
                   15728:                       for the sheet of paper
                   15729:       FirstName   - column that the first name starts in
                   15730:       FirstNameLength - number of columns that the first name spans
                   15731:       LastName    - column that the last name starts in
                   15732:       LastNameLength - number of columns that the last name spans
                   15733:       BubblesPerRow - number of bubbles available in each row used to
                   15734:                       bubble an answer. (If not specified, 10 assumed).
                   15735: 
                   15736: 
                   15737: =item *
                   15738: 
                   15739: get_scantronformat_file($cdom)
                   15740: 
                   15741: $cdom - the course's domain (optional); if not supplied, uses
                   15742: domain for current $env{'request.course.id'}.
                   15743: 
                   15744: Returns an array containing lines from the scantron format file for
                   15745: the domain of the course.
                   15746: 
                   15747: If a url for a custom.tab file is listed in domain's configuration.db,
                   15748: lines are from this file.
                   15749: 
                   15750: Otherwise, if a default.tab has been published in RES space by the
                   15751: domainconfig user, lines are from this file.
                   15752: 
                   15753: Otherwise, fall back to getting lines from the legacy file on the
                   15754: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15755: 
                   15756: =back
                   15757: 
1.243     albertel 15758: =head2 Resource Subroutines
                   15759: 
                   15760: =over 4
1.191     harris41 15761: 
                   15762: =item *
                   15763: 
1.243     albertel 15764: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15765: 
                   15766: =item *
                   15767: 
1.243     albertel 15768: repcopy($filename) : subscribes to the requested file, and attempts to
                   15769: replicate from the owning library server, Might return
1.607     raeburn  15770: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15771: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15772: resource. Expects the local filesystem pathname
                   15773: (/home/httpd/html/res/....)
                   15774: 
                   15775: =back
                   15776: 
                   15777: =head2 Resource Information
                   15778: 
                   15779: =over 4
1.191     harris41 15780: 
                   15781: =item *
                   15782: 
1.1228    raeburn  15783: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15784: and returns the value of a variety of different possible values,
                   15785: $varname should be a request string, and the other parameters can be
                   15786: used to specify who and what one is asking about. Ordinarily, $cid 
                   15787: does not need to be specified, as it is retrived from 
                   15788: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15789: within lonuserstate::loadmap() when initializing a course, before
                   15790: $env{'request.course.id'} has been set, so it needs to be provided
                   15791: in that one case.
1.243     albertel 15792: 
                   15793: Possible values for $varname are environment.lastname (or other item
                   15794: from the envirnment hash), user.name (or someother aspect about the
                   15795: user), resource.0.maxtries (or some other part and parameter of a
                   15796: resource)
1.204     albertel 15797: 
                   15798: =item *
                   15799: 
1.243     albertel 15800: directcondval($number) : get current value of a condition; reads from a state
                   15801: string
1.204     albertel 15802: 
                   15803: =item *
                   15804: 
1.243     albertel 15805: condval($condidx) : value of condition index based on state
1.204     albertel 15806: 
                   15807: =item *
                   15808: 
1.1362    raeburn  15809: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15810: resource's metadata, $what should be either a specific key, or either
                   15811: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15812: packages that this resource currently uses, the last 3 arguments are 
                   15813: only used internally for recursive metadata.
                   15814: 
                   15815: the toolsymb is only used where the uri is for an external tool (for which
                   15816: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15817: 
1.1371    raeburn  15818: this function automatically caches all requests except any made recursively
                   15819: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15820: defined).
1.191     harris41 15821: 
                   15822: =item *
                   15823: 
1.243     albertel 15824: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15825: network of library servers; returns file handle of where SQL and regex results
                   15826: will be stored for query
1.191     harris41 15827: 
                   15828: =item *
                   15829: 
1.1282    raeburn  15830: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15831: return symbolic list entry (all arguments optional). 
                   15832: 
                   15833: Args: filename is the filename (including path) for the file for which a symb 
                   15834: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15835: to check access status if more than one resource was found in the bighash 
                   15836: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15837: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15838: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15839: cause possible symbs to be checked to determine if they are subject to content
                   15840: blocking, if so they will not be included as possible symbs; possibles is a
                   15841: ref to a hash, which, as a side effect, will be populated with all possible 
                   15842: symbs (content blocking not tested).
                   15843:  
1.243     albertel 15844: returns the data handle
1.191     harris41 15845: 
                   15846: =item *
                   15847: 
1.1190    raeburn  15848: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15849: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15850: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15851: on failure, user must be in a course, as it assumes the existence of
                   15852: the course initial hash, and uses $env('request.course.id'}.  The third
                   15853: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15854: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15855: encrypted; otherwise it will be null.  
1.191     harris41 15856: 
                   15857: =item *
                   15858: 
1.243     albertel 15859: symbclean($symb) : removes versions numbers from a symb, returns the
                   15860: cleaned symb
1.191     harris41 15861: 
                   15862: =item *
                   15863: 
1.243     albertel 15864: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15865: course map, user must be in a course for it to work.
1.191     harris41 15866: 
                   15867: =item *
                   15868: 
1.243     albertel 15869: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15870: 
                   15871: =item *
                   15872: 
1.243     albertel 15873: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15874: a random seed, all arguments are optional, if they aren't sent it uses the
                   15875: environment to derive them. Note: if symb isn't sent and it can't get one
                   15876: from &symbread it will use the current time as its return value
1.191     harris41 15877: 
                   15878: =item *
                   15879: 
1.243     albertel 15880: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15881: unfakeable, receipt
1.191     harris41 15882: 
                   15883: =item *
                   15884: 
1.620     albertel 15885: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15886: 
                   15887: =item *
                   15888: 
1.243     albertel 15889: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15890: 
                   15891: =item *
                   15892: 
1.243     albertel 15893: 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 15894: 
                   15895: =item *
                   15896: 
1.243     albertel 15897: 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 15898: 
                   15899: =item *
                   15900: 
1.243     albertel 15901: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15902: 
                   15903: =item *
                   15904: 
1.243     albertel 15905: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15906: forcing spreadsheet to reevaluate the resource scores next time.
                   15907: 
1.1195    raeburn  15908: =item * 
                   15909: 
1.1196    raeburn  15910: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15911: when viewing in course context.
1.1195    raeburn  15912: 
1.1196    raeburn  15913:  input: six args -- filename (decluttered), course number, course domain,
                   15914:                     url, symb (if registered) and group (if this is a 
                   15915:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15916: 
1.1196    raeburn  15917:  output: array of five scalars --
1.1195    raeburn  15918:          $cfile -- url for file editing if editable on current server
                   15919:          $home -- homeserver of resource (i.e., for author if published,
                   15920:                                           or course if uploaded.).
                   15921:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15922:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15923:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15924: 
                   15925: =item *
                   15926: 
                   15927: is_course_upload($file,$cnum,$cdom)
                   15928: 
                   15929: Used in course context to determine if current file was uploaded to 
                   15930: the course (i.e., would be found in /userfiles/docs on the course's 
                   15931: homeserver.
                   15932: 
                   15933:   input: 3 args -- filename (decluttered), course number and course domain.
                   15934:   output: boolean -- 1 if file was uploaded.
                   15935: 
1.243     albertel 15936: =back
                   15937: 
                   15938: =head2 Storing/Retreiving Data
                   15939: 
                   15940: =over 4
1.191     harris41 15941: 
                   15942: =item *
                   15943: 
1.1269    raeburn  15944: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15945: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15946: the remaining args aren't required and if they aren't passed or are '' they will
                   15947: be derived from the env (with the exception of $laststore, which is an 
                   15948: optional arg used when a user's submission is stored in grading).
                   15949: $laststore is $version=$timestamp, where $version is the most recent version
                   15950: number retrieved for the corresponding $symb in the $namespace db file, and
                   15951: $timestamp is the timestamp for that transaction (UNIX time).
                   15952: $laststore is currently only passed when cstore() is called by 
                   15953: structuretags::finalize_storage().
1.191     harris41 15954: 
                   15955: =item *
                   15956: 
1.1269    raeburn  15957: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15958: but uses critical subroutine
1.191     harris41 15959: 
                   15960: =item *
                   15961: 
1.243     albertel 15962: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15963: all args are optional
1.191     harris41 15964: 
                   15965: =item *
                   15966: 
1.717     albertel 15967: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15968: dumps the complete (or key matching regexp) namespace into a hash
                   15969: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15970: normally &store()ed into
                   15971: 
                   15972: $range should be either an integer '100' (give me the first 100
                   15973:                                            matching records)
                   15974:               or be  two integers sperated by a - with no spaces
                   15975:                  '30-50' (give me the 30th through the 50th matching
                   15976:                           records)
                   15977: 
                   15978: 
                   15979: =item *
                   15980: 
1.1269    raeburn  15981: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15982: replaces a &store() version of data with a replacement set of data
                   15983: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15984: reference. If $tolog is true, the transaction is logged in the courselog
                   15985: with an action=PUTSTORE.
1.717     albertel 15986: 
                   15987: =item *
                   15988: 
1.243     albertel 15989: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15990: works very similar to store/cstore, but all data is stored in a
                   15991: temporary location and can be reset using tmpreset, $storehash should
                   15992: be a hash reference, returns nothing on success
1.191     harris41 15993: 
                   15994: =item *
                   15995: 
1.243     albertel 15996: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15997: similar to restore, but all data is stored in a temporary location and
                   15998: can be reset using tmpreset. Returns a hash of values on success,
                   15999: error string otherwise.
1.191     harris41 16000: 
                   16001: =item *
                   16002: 
1.243     albertel 16003: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16004: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16005: 
                   16006: =item *
                   16007: 
1.243     albertel 16008: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16009: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16010: 
                   16011: =item *
                   16012: 
1.243     albertel 16013: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16014: namesp ($udom and $uname are optional)
1.191     harris41 16015: 
                   16016: =item *
                   16017: 
1.702     albertel 16018: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16019: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16020: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16021: 
1.702     albertel 16022: $range should be either an integer '100' (give me the first 100
                   16023:                                            matching records)
                   16024:               or be  two integers sperated by a - with no spaces
                   16025:                  '30-50' (give me the 30th through the 50th matching
                   16026:                           records)
1.449     matthew  16027: =item *
                   16028: 
                   16029: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16030: $store can be a scalar, an array reference, or if the amount to be 
                   16031: incremented is > 1, a hash reference.
                   16032: 
                   16033: ($udom and $uname are optional)
1.191     harris41 16034: 
                   16035: =item *
                   16036: 
1.243     albertel 16037: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16038: ($udom and $uname are optional)
1.191     harris41 16039: 
                   16040: =item *
                   16041: 
1.243     albertel 16042: cput($namespace,$storehash,$udom,$uname) : critical put
                   16043: ($udom and $uname are optional)
1.191     harris41 16044: 
                   16045: =item *
                   16046: 
1.748     albertel 16047: newput($namespace,$storehash,$udom,$uname) :
                   16048: 
                   16049: Attempts to store the items in the $storehash, but only if they don't
                   16050: currently exist, if this succeeds you can be certain that you have 
                   16051: successfully created a new key value pair in the $namespace db.
                   16052: 
                   16053: 
                   16054: Args:
                   16055:  $namespace: name of database to store values to
                   16056:  $storehash: hashref to store to the db
                   16057:  $udom: (optional) domain of user containing the db
                   16058:  $uname: (optional) name of user caontaining the db
                   16059: 
                   16060: Returns:
                   16061:  'ok' -> succeeded in storing all keys of $storehash
                   16062:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16063:                         least <key> already existed in the db (other
                   16064:                         requested keys may also already exist)
1.967     bisitz   16065:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16066:  'con_lost' -> unable to contact request server
                   16067:  'refused' -> action was not allowed by remote machine
                   16068: 
                   16069: 
                   16070: =item *
                   16071: 
1.243     albertel 16072: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16073: reference filled in from namesp (encrypts the return communication)
                   16074: ($udom and $uname are optional)
1.191     harris41 16075: 
                   16076: =item *
                   16077: 
1.243     albertel 16078: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16079: critical subroutine
                   16080: 
1.806     raeburn  16081: =item *
                   16082: 
1.860     raeburn  16083: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16084: array reference filled in from namespace found in domain level on either
                   16085: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16086: 
                   16087: =item *
                   16088: 
1.860     raeburn  16089: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16090: domain level either on specified domain server ($uhome) or primary domain 
                   16091: server ($udom and $uhome are optional)
1.806     raeburn  16092: 
1.943     raeburn  16093: =item * 
                   16094: 
1.1240    raeburn  16095: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16096: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16097: the target domain.
                   16098: 
                   16099: May also include additional key => value pairs for the following groups:
                   16100: 
                   16101: =over
                   16102: 
                   16103: =item
                   16104: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16105: 
                   16106: =over
                   16107: 
                   16108: =item defaultquota, authorquota
                   16109: 
                   16110: =back
                   16111: 
                   16112: =item
                   16113: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16114: portfolio for users).
                   16115: 
                   16116: =over
                   16117: 
                   16118: =item
                   16119: aboutme, blog, webdav, portfolio
                   16120: 
                   16121: =back
                   16122: 
                   16123: =item
                   16124: requestcourses: ability to request courses, and how requests are processed.
                   16125: 
                   16126: =over
                   16127: 
                   16128: =item
1.1305    raeburn  16129: official, unofficial, community, textbook, placement
1.1240    raeburn  16130: 
                   16131: =back
                   16132: 
                   16133: =item
                   16134: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16135: 
                   16136: =over
                   16137: 
                   16138: =item
1.1256    raeburn  16139: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16140: 
                   16141: =back
                   16142: 
                   16143: =item
                   16144: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16145: for course's uploaded content.
                   16146: 
                   16147: =over
                   16148: 
                   16149: =item
1.1246    raeburn  16150: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16151: communityquota, textbookquota, placementquota
1.1240    raeburn  16152: 
                   16153: =back
                   16154: 
                   16155: =item
                   16156: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16157: on your servers.
                   16158: 
                   16159: =over
                   16160: 
                   16161: =item 
                   16162: remotesessions, hostedsessions
                   16163: 
                   16164: =back
                   16165: 
                   16166: =back
                   16167: 
                   16168: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16169: utility to create a configuration.db file on a domain's primary library server 
                   16170: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16171: -- corresponding values are authentication type (internal, krb4, krb5,
                   16172: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16173: will be available. Values are retrieved from cache (if current), unless the
                   16174: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16175: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16176: 
                   16177: Typical usage:
1.943     raeburn  16178: 
1.1240    raeburn  16179: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16180: 
1.243     albertel 16181: =back
                   16182: 
                   16183: =head2 Network Status Functions
                   16184: 
                   16185: =over 4
1.191     harris41 16186: 
                   16187: =item *
                   16188: 
1.1137    raeburn  16189: dirlist() : return directory list based on URI (first arg).
                   16190: 
                   16191: Inputs: 1 required, 5 optional.
                   16192: 
                   16193: =over
                   16194: 
                   16195: =item 
                   16196: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16197: 
                   16198: =item
                   16199: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16200: 
                   16201: =item
                   16202: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16203: 
                   16204: =item
                   16205: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16206: 
                   16207: =item
                   16208: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16209: 
                   16210: =item 
                   16211: $alternateRoot - path to prepend in place of path from $uri.
                   16212: 
                   16213: =back
                   16214: 
                   16215: Returns: Array of up to two items.
                   16216: 
                   16217: =over
                   16218: 
                   16219: a reference to an array of files/subdirectories
                   16220: 
                   16221: =over
                   16222: 
                   16223: Each element in the array of files/subdirectories is a & separated list of
                   16224: item name and the result of running stat on the item.  If dirlist was requested
                   16225: for a file instead of a directory, the item name will be ''. For a directory 
                   16226: listing, if the item is a metadata file, the element will end &N&M 
                   16227: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16228: default copyright set (1).  
                   16229: 
                   16230: =back
                   16231: 
                   16232: a scalar containing error condition (if encountered).
                   16233: 
                   16234: =over
                   16235: 
                   16236: =item 
                   16237: no_host (no homeserver identified for $username:$domain).
                   16238: 
                   16239: =item 
                   16240: no_such_host (server contacted for listing not identified as valid host).
                   16241: 
                   16242: =item 
                   16243: con_lost (connection to remote server failed).
                   16244: 
                   16245: =item 
                   16246: refused (invalid $username:$domain received on lond side).
                   16247: 
                   16248: =item 
                   16249: no_such_dir (directory at specified path on lond side does not exist). 
                   16250: 
                   16251: =item 
                   16252: empty (directory at specified path on lond side is empty).
                   16253: 
                   16254: =over
                   16255: 
                   16256: This is currently not encountered because the &ls3, &ls2, 
                   16257: &ls (_handler) routines on the lond side do not filter out
                   16258: . and .. from a directory listing. 
                   16259: 
                   16260: =back
                   16261: 
                   16262: =back
                   16263: 
                   16264: =back
1.191     harris41 16265: 
                   16266: =item *
                   16267: 
1.243     albertel 16268: spareserver() : find server with least workload from spare.tab
                   16269: 
1.986     foxr     16270: 
                   16271: =item *
                   16272: 
                   16273: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16274: if there is no corresponding loncapa host.
                   16275: 
1.243     albertel 16276: =back
                   16277: 
1.986     foxr     16278: 
1.243     albertel 16279: =head2 Apache Request
                   16280: 
                   16281: =over 4
1.191     harris41 16282: 
                   16283: =item *
                   16284: 
1.243     albertel 16285: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16286: localhost, posts hash
                   16287: 
                   16288: =back
                   16289: 
                   16290: =head2 Data to String to Data
                   16291: 
                   16292: =over 4
1.191     harris41 16293: 
                   16294: =item *
                   16295: 
1.243     albertel 16296: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16297: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16298: 
                   16299: =item *
                   16300: 
1.243     albertel 16301: hashref2str($hashref) : convert a hashref into a string complete with
                   16302: escaping and '=' and '&' separators, supports elements that are
                   16303: arrayrefs and hashrefs
1.191     harris41 16304: 
                   16305: =item *
                   16306: 
1.243     albertel 16307: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16308: with escaping and '&' separators, supports elements that are arrayrefs
                   16309: and hashrefs
1.191     harris41 16310: 
                   16311: =item *
                   16312: 
1.243     albertel 16313: str2hash($string) : convert string to hash using unescaping and
                   16314: splitting on '=' and '&', supports elements that are arrayrefs and
                   16315: hashrefs
1.191     harris41 16316: 
                   16317: =item *
                   16318: 
1.243     albertel 16319: str2array($string) : convert string to hash using unescaping and
                   16320: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16321: 
                   16322: =back
                   16323: 
                   16324: =head2 Logging Routines
                   16325: 
                   16326: 
                   16327: These routines allow one to make log messages in the lonnet.log and
                   16328: lonnet.perm logfiles.
1.191     harris41 16329: 
1.1119    foxr     16330: =over 4
                   16331: 
1.191     harris41 16332: =item *
                   16333: 
1.243     albertel 16334: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16335: 
                   16336: =item *
                   16337: 
1.243     albertel 16338: logthis() : append message to the normal lonnet.log file, it gets
                   16339: preiodically rolled over and deleted.
1.191     harris41 16340: 
                   16341: =item *
                   16342: 
1.243     albertel 16343: logperm() : append a permanent message to lonnet.perm.log, this log
                   16344: file never gets deleted by any automated portion of the system, only
                   16345: messages of critical importance should go in here.
                   16346: 
1.1119    foxr     16347: 
1.243     albertel 16348: =back
                   16349: 
                   16350: =head2 General File Helper Routines
                   16351: 
                   16352: =over 4
1.191     harris41 16353: 
                   16354: =item *
                   16355: 
1.481     raeburn  16356: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16357: (a) files in /uploaded
                   16358:   (i) If a local copy of the file exists - 
                   16359:       compares modification date of local copy with last-modified date for 
                   16360:       definitive version stored on home server for course. If local copy is 
                   16361:       stale, requests a new version from the home server and stores it. 
                   16362:       If the original has been removed from the home server, then local copy 
                   16363:       is unlinked.
                   16364:   (ii) If local copy does not exist -
                   16365:       requests the file from the home server and stores it. 
                   16366:   
                   16367:   If $caller is 'uploadrep':  
                   16368:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16369:     for request for files originally uploaded via DOCS. 
                   16370:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16371:   
                   16372:   Otherwise:
                   16373:      This indicates a call from the content generation phase of the request.
                   16374:      -  returns the entire contents of the file or -1.
                   16375:      
                   16376: (b) files in /res
                   16377:    - returns the entire contents of a file or -1; 
                   16378:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16379: 
1.712     albertel 16380: 
                   16381: =item *
                   16382: 
                   16383: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16384:                   reference
                   16385: 
                   16386: returns either a stat() list of data about the file or an empty list
                   16387: if the file doesn't exist or couldn't find out about it (connection
                   16388: problems or user unknown)
                   16389: 
1.191     harris41 16390: =item *
                   16391: 
1.243     albertel 16392: filelocation($dir,$file) : returns file system location of a file
                   16393: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16394: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16395: and a file of ../bob will become /a/bob)
1.191     harris41 16396: 
                   16397: =item *
                   16398: 
                   16399: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16400: filelocation except for hrefs
                   16401: 
                   16402: =item *
                   16403: 
1.1261    raeburn  16404: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16405: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16406: 
1.243     albertel 16407: =back
                   16408: 
1.608     albertel 16409: =head2 Usererfile file routines (/uploaded*)
                   16410: 
                   16411: =over 4
                   16412: 
                   16413: =item *
                   16414: 
                   16415: userfileupload(): main rotine for putting a file in a user or course's
                   16416:                   filespace, arguments are,
                   16417: 
1.620     albertel 16418:  formname - required - this is the name of the element in $env where the
1.608     albertel 16419:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16420:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16421:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16422:  context - if coursedoc, store the file in the course of the active role
                   16423:              of the current user; 
                   16424:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16425:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16426:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16427:          if undefined, it will be placed in "unknown"
                   16428: 
                   16429:  (This routine calls clean_filename() to remove any dangerous
                   16430:  characters from the filename, and then calls finuserfileupload() to
                   16431:  complete the transaction)
                   16432: 
                   16433:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16434:  and /adm/notfound.html if unsuccessful
                   16435: 
                   16436: =item *
                   16437: 
                   16438: clean_filename(): routine for cleaing a filename up for storage in
                   16439:                  userfile space, argument is:
                   16440: 
                   16441:  filename - proposed filename
                   16442: 
                   16443: returns: the new clean filename
                   16444: 
                   16445: =item *
                   16446: 
1.1090    raeburn  16447: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16448: userspace, probably shouldn't be called directly
                   16449: 
                   16450:   docuname: username or courseid of destination for the file
                   16451:   docudom: domain of user/course of destination for the file
                   16452:   formname: same as for userfileupload()
1.1090    raeburn  16453:   fname: filename (including subdirectories) for the file
                   16454:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  16455:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16456:   allfiles: reference to hash used to store objects found by parser
                   16457:   codebase: reference to hash used for codebases of java objects found by parser
                   16458:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16459:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16460:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16461:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16462:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16463:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16464:   mimetype: reference to scalar to accommodate mime type determined
                   16465:             from File::MMagic if $parser = parse.
1.608     albertel 16466: 
                   16467:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16468:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16469:  was 'overwrite').
                   16470:  
1.608     albertel 16471: 
                   16472: =item *
                   16473: 
                   16474: renameuserfile(): renames an existing userfile to a new name
                   16475: 
                   16476:   Args:
                   16477:    docuname: username or courseid of destination for the file
                   16478:    docudom: domain of user/course of destination for the file
                   16479:    old: current file name (including any subdirs under userfiles)
                   16480:    new: desired file name (including any subdirs under userfiles)
                   16481: 
                   16482: =item *
                   16483: 
                   16484: mkdiruserfile(): creates a directory is a userfiles dir
                   16485: 
                   16486:   Args:
                   16487:    docuname: username or courseid of destination for the file
                   16488:    docudom: domain of user/course of destination for the file
                   16489:    dir: dir to create (including any subdirs under userfiles)
                   16490: 
                   16491: =item *
                   16492: 
                   16493: removeuserfile(): removes a file that exists in userfiles
                   16494: 
                   16495:   Args:
                   16496:    docuname: username or courseid of destination for the file
                   16497:    docudom: domain of user/course of destination for the file
                   16498:    fname: filname to delete (including any subdirs under userfiles)
                   16499: 
                   16500: =item *
                   16501: 
                   16502: removeuploadedurl(): convience function for removeuserfile()
                   16503: 
                   16504:   Args:
                   16505:    url:  a full /uploaded/... url to delete
                   16506: 
1.747     albertel 16507: =item * 
                   16508: 
                   16509: get_portfile_permissions():
                   16510:   Args:
                   16511:     domain: domain of user or course contain the portfolio files
                   16512:     user: name of user or num of course contain the portfolio files
                   16513:   Returns:
                   16514:     hashref of a dump of the proper file_permissions.db
                   16515:    
                   16516: 
                   16517: =item * 
                   16518: 
                   16519: get_access_controls():
                   16520: 
                   16521: Args:
                   16522:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16523:   group: (optional) the group you want the files associated with
                   16524:   file: (optional) the file you want access info on
                   16525: 
                   16526: Returns:
1.749     raeburn  16527:     a hash (keys are file names) of hashes containing
                   16528:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16529:         values are XML containing access control settings (see below) 
1.747     albertel 16530: 
                   16531: Internal notes:
                   16532: 
1.749     raeburn  16533:  access controls are stored in file_permissions.db as key=value pairs.
                   16534:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16535:         where scope -> public,guest,course,group,domains or users.
                   16536:               end -> UNIX time for end of access (0 -> no end date)
                   16537:               start -> UNIX time for start of access
                   16538: 
                   16539:     value -> XML description of access control
                   16540:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16541:             <start></start>
                   16542:             <end></end>
                   16543: 
                   16544:             <password></password>  for scope type = guest
                   16545: 
                   16546:             <domain></domain>     for scope type = course or group
                   16547:             <number></number>
                   16548:             <roles id="">
                   16549:              <role></role>
                   16550:              <access></access>
                   16551:              <section></section>
                   16552:              <group></group>
                   16553:             </roles>
                   16554: 
                   16555:             <dom></dom>         for scope type = domains
                   16556: 
                   16557:             <users>             for scope type = users
                   16558:              <user>
                   16559:               <uname></uname>
                   16560:               <udom></udom>
                   16561:              </user>
                   16562:             </users>
                   16563:            </scope> 
                   16564:               
                   16565:  Access data is also aggregated for each file in an additional key=value pair:
                   16566:  key -> path to file/file_name\0accesscontrol 
                   16567:  value -> reference to hash
                   16568:           hash contains key = value pairs
                   16569:           where key = uniqueID:scope_end_start
                   16570:                 value = UNIX time record was last updated
                   16571: 
                   16572:           Used to improve speed of look-ups of access controls for each file.  
                   16573:  
                   16574:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16575: 
1.1198    raeburn  16576: =item *
                   16577: 
1.749     raeburn  16578: modify_access_controls():
                   16579: 
                   16580: Modifies access controls for a portfolio file
                   16581: Args
                   16582: 1. file name
                   16583: 2. reference to hash of required changes,
                   16584: 3. domain
                   16585: 4. username
                   16586:   where domain,username are the domain of the portfolio owner 
                   16587:   (either a user or a course) 
                   16588: 
                   16589: Returns:
                   16590: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16591: 2. result of deletions ('ok' or 'error', with error message).
                   16592: 3. reference to hash of any new or updated access controls.
                   16593: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16594:    key = integer (inbound ID)
1.1198    raeburn  16595:    value = uniqueID
                   16596: 
                   16597: =item *
                   16598: 
                   16599: get_timebased_id():
                   16600: 
                   16601: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   16602: course via the Course Editor (e.g., folders, composite pages, 
                   16603: group bulletin boards).
                   16604: 
                   16605: Args: (first three required; six others optional)
                   16606: 
                   16607: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16608:    docssequence, or name of group
                   16609: 
                   16610: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16611:    e.g., num, boardids
                   16612: 
                   16613: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   16614:    file will be named nohist_namespace.db
                   16615: 
                   16616: 4. cdom: domain of course; default is current course domain from %env
                   16617: 
                   16618: 5. cnum: course number; default is current course number from %env
                   16619: 
                   16620: 6. idtype: set to concat if an additional digit is to be appended to the 
                   16621:    unix timestamp to form the suffix, if the plain timestamp is already
                   16622:    in use.  Default is to not do this, but simply increment the unix 
                   16623:    timestamp by 1 until a unique key is obtained.
                   16624: 
                   16625: 7. who: holder of locking key; defaults to user:domain for user.
                   16626: 
                   16627: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   16628:    retrying); default is 3.
                   16629: 
                   16630: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   16631: 
                   16632: Returns:
                   16633: 
                   16634: 1. suffix obtained (numeric)
                   16635: 
                   16636: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16637: 
                   16638: 3. error: contains (localized) error message if an error occurred.
                   16639: 
1.747     albertel 16640: 
1.608     albertel 16641: =back
                   16642: 
1.243     albertel 16643: =head2 HTTP Helper Routines
                   16644: 
                   16645: =over 4
                   16646: 
1.191     harris41 16647: =item *
                   16648: 
                   16649: escape() : unpack non-word characters into CGI-compatible hex codes
                   16650: 
                   16651: =item *
                   16652: 
                   16653: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16654: 
1.243     albertel 16655: =back
                   16656: 
                   16657: =head1 PRIVATE SUBROUTINES
                   16658: 
                   16659: =head2 Underlying communication routines (Shouldn't call)
                   16660: 
                   16661: =over 4
                   16662: 
                   16663: =item *
                   16664: 
                   16665: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16666: 
                   16667: =item *
                   16668: 
                   16669: reply() : uses subreply to send a message to remote machine, logs all failures
                   16670: 
                   16671: =item *
                   16672: 
                   16673: critical() : passes a critical message to another server; if cannot
                   16674: get through then place message in connection buffer directory and
                   16675: returns con_delayed, if incapable of saving message, returns
                   16676: con_failed
                   16677: 
                   16678: =item *
                   16679: 
                   16680: reconlonc() : tries to reconnect lonc client processes.
                   16681: 
                   16682: =back
                   16683: 
                   16684: =head2 Resource Access Logging
                   16685: 
                   16686: =over 4
                   16687: 
                   16688: =item *
                   16689: 
                   16690: flushcourselogs() : flush (save) buffer logs and access logs
                   16691: 
                   16692: =item *
                   16693: 
                   16694: courselog($what) : save message for course in hash
                   16695: 
                   16696: =item *
                   16697: 
                   16698: courseacclog($what) : save message for course using &courselog().  Perform
                   16699: special processing for specific resource types (problems, exams, quizzes, etc).
                   16700: 
1.191     harris41 16701: =item *
                   16702: 
                   16703: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16704: as a PerlChildExitHandler
1.243     albertel 16705: 
                   16706: =back
                   16707: 
                   16708: =head2 Other
                   16709: 
                   16710: =over 4
                   16711: 
                   16712: =item *
                   16713: 
                   16714: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16715: 
                   16716: =back
                   16717: 
                   16718: =cut
1.877     foxr     16719: 

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