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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .14(raeb    4:-21): # $Id: lonnet.pm,v 1.1172.2.118.2.13 2021/01/03 01:47: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.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1172.2.110  raeburn   102: use LONCAPA::transliterate;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.1172.2.79  raeburn   107: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.1172.2.9  raeburn   114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       115: {
                    116:     my $logid;
1.1172.2.9  raeburn   117:     sub write_log {
                    118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    119:         if ($context eq 'course') {
                    120:             if (($cnum eq '') || ($cdom eq '')) {
                    121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:             }
1.957     raeburn   124:         }
1.1172.2.13  raeburn   125: 	$logid ++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.118.  .14(raeb  128:-21):         my $ip = &get_requestor_ip();
1.1172.2.9  raeburn   129:         my $logentry = {
                    130:                          $id => {
                    131:                                   'exe_uname' => $env{'user.name'},
                    132:                                   'exe_udom'  => $env{'user.domain'},
                    133:                                   'exe_time'  => $now,
1.1172.2.118.  .14(raeb  134:-21):                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   135:                                   'delflag'   => $delflag,
                    136:                                   'logentry'  => $storehash,
                    137:                                   'uname'     => $uname,
                    138:                                   'udom'      => $udom,
                    139:                                 }
                    140:                        };
                    141:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       142:     }
                    143: }
1.1       albertel  144: 
1.163     harris41  145: sub logtouch {
                    146:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  147:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   148: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  149: 	close $fh;
                    150:     }
                    151:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    152:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    153: }
                    154: 
1.1       albertel  155: sub logthis {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.1172.2.96  raeburn   160:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      161: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    162: 	print $fh $logstring;
1.448     albertel  163: 	close($fh);
                    164:     }
1.1       albertel  165:     return 1;
                    166: }
                    167: 
                    168: sub logperm {
                    169:     my $message=shift;
                    170:     my $execdir=$perlvar{'lonDaemons'};
                    171:     my $now=time;
                    172:     my $local=localtime($now);
1.1172.2.96  raeburn   173:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  174: 	print $fh "$now:$message:$local\n";
                    175: 	close($fh);
                    176:     }
1.1       albertel  177:     return 1;
                    178: }
                    179: 
1.850     albertel  180: sub create_connection {
1.853     albertel  181:     my ($hostname,$lonid) = @_;
1.851     albertel  182:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  183: 				     Type    => SOCK_STREAM,
                    184: 				     Timeout => 10);
                    185:     return 0 if (!$client);
1.890     albertel  186:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  187:     my $result = <$client>;
                    188:     chomp($result);
                    189:     return 1 if ($result eq 'done');
                    190:     return 0;
                    191: }
                    192: 
1.983     raeburn   193: sub get_server_timezone {
                    194:     my ($cnum,$cdom) = @_;
                    195:     my $home=&homeserver($cnum,$cdom);
                    196:     if ($home ne 'no_host') {
                    197:         my $cachetime = 24*3600;
                    198:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    199:         if (defined($cached)) {
                    200:             return $timezone;
                    201:         } else {
                    202:             my $timezone = &reply('servertimezone',$home);
                    203:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    204:         }
                    205:     }
                    206: }
1.850     albertel  207: 
1.1106    raeburn   208: sub get_server_distarch {
                    209:     my ($lonhost,$ignore_cache) = @_;
                    210:     if (defined($lonhost)) {
                    211:         if (!defined(&hostname($lonhost))) {
                    212:             return;
                    213:         }
                    214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $distarch;
                    219:             }
                    220:         }
                    221:         my $rep = &reply('serverdistarch',$lonhost);
                    222:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    223:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    224:                 $rep eq '') {
                    225:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    226:         }
                    227:     }
                    228:     return;
                    229: }
                    230: 
1.993     raeburn   231: sub get_server_loncaparev {
1.1073    raeburn   232:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   233:     if (defined($lonhost)) {
                    234:         if (!defined(&hostname($lonhost))) {
                    235:             undef($lonhost);
                    236:         }
                    237:     }
                    238:     if (!defined($lonhost)) {
                    239:         if (defined(&domain($dom,'primary'))) {
                    240:             $lonhost=&domain($dom,'primary');
                    241:             if ($lonhost eq 'no_host') {
                    242:                 undef($lonhost);
                    243:             }
                    244:         }
                    245:     }
                    246:     if (defined($lonhost)) {
1.1073    raeburn   247:         my $cachetime = 12*3600;
                    248:         if (!$ignore_cache) {
                    249:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    250:             if (defined($cached)) {
                    251:                 return $loncaparev;
                    252:             }
                    253:         }
                    254:         my ($answer,$loncaparev);
                    255:         my @ids=&current_machine_ids();
                    256:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    257:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   258:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   259:                 $loncaparev = $1;
                    260:             }
                    261:         } else {
                    262:             $answer = &reply('serverloncaparev',$lonhost);
                    263:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    264:                 if ($caller eq 'loncron') {
                    265:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   266:                     $ua->timeout(4);
1.1172.2.118.  .3(raebu  267:20):                     my $hostname = &hostname($lonhost);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu  270:20):                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1172.2.35  raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364: }
                    365: 
1.1       albertel  366: # -------------------------------------------------- Non-critical communication
                    367: sub subreply {
                    368:     my ($cmd,$server)=@_;
1.838     albertel  369:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      370:     #
                    371:     #  With loncnew process trimming, there's a timing hole between lonc server
                    372:     #  process exit and the master server picking up the listen on the AF_UNIX
                    373:     #  socket.  In that time interval, a lock file will exist:
                    374: 
                    375:     my $lockfile=$peerfile.".lock";
                    376:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   377: 	sleep(0.1);
1.549     foxr      378:     }
                    379:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      380:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      381:     #
1.550     foxr      382:     #   We'll give the connection a few tries before abandoning it.  If
                    383:     #   connection is not possible, we'll con_lost back to the client.
                    384:     #   
                    385:     my $client;
                    386:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    387: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    388: 				      Type    => SOCK_STREAM,
                    389: 				      Timeout => 10);
1.869     albertel  390: 	if ($client) {
1.550     foxr      391: 	    last;		# Connected!
1.850     albertel  392: 	} else {
1.853     albertel  393: 	    &create_connection(&hostname($server),$server);
1.550     foxr      394: 	}
1.1172.2.79  raeburn   395:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      396:     }
                    397:     my $answer;
                    398:     if ($client) {
1.704     albertel  399: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      400: 	$answer=<$client>;
                    401: 	if (!$answer) { $answer="con_lost"; }
                    402: 	chomp($answer);
                    403:     } else {
                    404: 	$answer = 'con_lost';	# Failed connection.
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: sub reply {
                    410:     my ($cmd,$server)=@_;
1.838     albertel  411:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  412:     my $answer=subreply($cmd,$server);
1.65      www       413:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   414:         my $logged = $cmd;
                    415:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    416:             my $subcmd = $1;
                    417:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    418:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    419:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    420:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    421:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    422:                     splice(@rest,2,1,'Hidden');
                    423:                 } elsif ($subcmd eq 'passwd') {
                    424:                     splice(@rest,2,2,('Hidden','Hidden'));
                    425:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    426:                          ($subcmd eq 'autoexportgrades')) {
                    427:                     splice(@rest,3,1,'Hidden');
                    428:                 }
                    429:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    430:             }
                    431:         }
                    432:         &logthis("<font color=\"blue\">WARNING:".
                    433:                  " $logged to $server returned $answer</font>");
1.12      www       434:     }
1.1       albertel  435:     return $answer;
                    436: }
                    437: 
                    438: # ----------------------------------------------------------- Send USR1 to lonc
                    439: 
                    440: sub reconlonc {
1.891     albertel  441:     my ($lonid) = @_;
                    442:     if ($lonid) {
1.1172.2.72  raeburn   443:         my $hostname = &hostname($lonid);
1.891     albertel  444: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    445: 	if ($hostname && -e $peerfile) {
                    446: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    447: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    448: 					     Type    => SOCK_STREAM,
                    449: 					     Timeout => 10);
                    450: 	    if ($client) {
                    451: 		print $client ("reset_retries\n");
                    452: 		my $answer=<$client>;
                    453: 		#reset just this one.
                    454: 	    }
                    455: 	}
                    456: 	return;
                    457:     }
                    458: 
1.836     www       459:     &logthis("Trying to reconnect lonc");
1.1       albertel  460:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   461:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  462: 	my $loncpid=<$fh>;
                    463:         chomp($loncpid);
                    464:         if (kill 0 => $loncpid) {
                    465: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    466:             kill USR1 => $loncpid;
                    467:             sleep 1;
1.836     www       468:          } else {
1.12      www       469: 	    &logthis(
1.672     albertel  470:                "<font color=\"blue\">WARNING:".
1.12      www       471:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  472:         }
                    473:     } else {
1.836     www       474: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  475:     }
                    476: }
                    477: 
                    478: # ------------------------------------------------------ Critical communication
1.12      www       479: 
1.1       albertel  480: sub critical {
                    481:     my ($cmd,$server)=@_;
1.838     albertel  482:     unless (&hostname($server)) {
1.672     albertel  483:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       484:                " Critical message to unknown server ($server)</font>");
                    485:         return 'no_such_host';
                    486:     }
1.1       albertel  487:     my $answer=reply($cmd,$server);
                    488:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   489: 	&reconlonc($server);
1.589     albertel  490: 	my $answer=reply($cmd,$server);
1.1       albertel  491:         if ($answer eq 'con_lost') {
                    492:             my $now=time;
                    493:             my $middlename=$cmd;
1.5       www       494:             $middlename=substr($middlename,0,16);
1.1       albertel  495:             $middlename=~s/\W//g;
                    496:             my $dfilename=
1.305     www       497:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    498:             $dumpcount++;
1.1       albertel  499:             {
1.448     albertel  500: 		my $dfh;
1.1172.2.96  raeburn   501: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  502: 		    print $dfh "$cmd\n"; 
                    503: 		    close($dfh);
                    504: 		}
1.1       albertel  505:             }
1.1172.2.79  raeburn   506:             sleep 1;
1.1       albertel  507:             my $wcmd='';
                    508:             {
1.448     albertel  509: 		my $dfh;
1.1172.2.96  raeburn   510: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  511: 		    $wcmd=<$dfh>; 
                    512: 		    close($dfh);
                    513: 		}
1.1       albertel  514:             }
                    515:             chomp($wcmd);
1.7       www       516:             if ($wcmd eq $cmd) {
1.672     albertel  517: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       518:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  519:                 &logperm("D:$server:$cmd");
                    520: 	        return 'con_delayed';
                    521:             } else {
1.672     albertel  522:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       523:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  524:                 &logperm("F:$server:$cmd");
                    525:                 return 'con_failed';
                    526:             }
                    527:         }
                    528:     }
                    529:     return $answer;
1.405     albertel  530: }
                    531: 
1.755     albertel  532: # ------------------------------------------- check if return value is an error
                    533: 
                    534: sub error {
                    535:     my ($result) = @_;
1.756     albertel  536:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  537: 	if ($2 == 2) { return undef; }
                    538: 	return $1;
                    539:     }
                    540:     return undef;
                    541: }
                    542: 
1.783     albertel  543: sub convert_and_load_session_env {
                    544:     my ($lonidsdir,$handle)=@_;
                    545:     my @profile;
                    546:     {
1.917     albertel  547: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    548: 	if (!$opened) {
1.915     albertel  549: 	    return 0;
                    550: 	}
1.783     albertel  551: 	flock($idf,LOCK_SH);
                    552: 	@profile=<$idf>;
                    553: 	close($idf);
                    554:     }
                    555:     my %temp_env;
                    556:     foreach my $line (@profile) {
1.786     albertel  557: 	if ($line !~ m/=/) {
                    558: 	    return 0;
                    559: 	}
1.783     albertel  560: 	chomp($line);
                    561: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    562: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    563:     }
                    564:     unlink("$lonidsdir/$handle.id");
                    565:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    566: 	    0640)) {
                    567: 	%disk_env = %temp_env;
                    568: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    569: 	untie(%disk_env);
                    570:     }
1.786     albertel  571:     return 1;
1.783     albertel  572: }
                    573: 
1.374     www       574: # ------------------------------------------- Transfer profile into environment
1.780     albertel  575: my $env_loaded;
                    576: sub transfer_profile_to_env {
1.788     albertel  577:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    578:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       579: 
1.720     albertel  580:     if (!defined($lonidsdir)) {
                    581: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    582:     }
                    583:     if (!defined($handle)) {
                    584:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    585:     }
                    586: 
1.786     albertel  587:     my $convert;
                    588:     {
1.917     albertel  589:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    590: 	if (!$opened) {
1.915     albertel  591: 	    return;
                    592: 	}
1.786     albertel  593: 	flock($idf,LOCK_SH);
                    594: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    595: 		&GDBM_READER(),0640)) {
                    596: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    597: 	    untie(%disk_env);
                    598: 	} else {
                    599: 	    $convert = 1;
                    600: 	}
                    601:     }
                    602:     if ($convert) {
                    603: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    604: 	    &logthis("Failed to load session, or convert session.");
                    605: 	}
1.374     www       606:     }
1.783     albertel  607: 
1.786     albertel  608:     my %remove;
1.783     albertel  609:     while ( my $envname = each(%env) ) {
1.433     matthew   610:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    611:             if ($time < time-300) {
1.783     albertel  612:                 $remove{$key}++;
1.433     matthew   613:             }
                    614:         }
                    615:     }
1.783     albertel  616: 
1.619     albertel  617:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  618:     $env_loaded=1;
1.783     albertel  619:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   620:         &delenv($expired_key);
1.374     www       621:     }
1.1       albertel  622: }
                    623: 
1.916     albertel  624: # ---------------------------------------------------- Check for valid session 
                    625: sub check_for_valid_session {
1.1172.2.96  raeburn   626:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  627:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   628:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   629:     if ($name eq 'lonDAV') {
                    630:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    631:     } else {
                    632:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   633:         if ($name eq '') {
                    634:             $name = 'lonID';
                    635:         }
                    636:     }
                    637:     if ($name eq 'lonID') {
                    638:         $secure = 'lonSID';
                    639:         $linkname = 'lonLinkID';
                    640:         $pubname = 'lonPubID';
                    641:         if (exists($cookies{$secure})) {
                    642:             $lonid=$cookies{$secure};
                    643:         } elsif (exists($cookies{$name})) {
                    644:             $lonid=$cookies{$name};
                    645:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    646:             $lonid=$cookies{$linkname};
                    647:         } elsif (exists($cookies{$pubname})) {
                    648:             $lonid=$cookies{$pubname};
                    649:         }
                    650:     } else {
                    651:         $lonid=$cookies{$name};
                    652:     }
                    653:     return undef if (!$lonid);
                    654: 
                    655:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    656:     if (-l "$lonidsdir/$handle.id") {
                    657:         my $link = readlink("$lonidsdir/$handle.id");
                    658:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    659:             $handle = $1;
                    660:         }
1.1155    raeburn   661:     }
1.1172.2.96  raeburn   662:     if (!-e "$lonidsdir/$handle.id") {
                    663:         if ((ref($domref)) && ($name eq 'lonID') &&
                    664:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    665:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    666:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    667:                 $$domref = $possudom;
                    668:             }
                    669:         }
                    670:         return undef;
                    671:     }
1.916     albertel  672: 
1.917     albertel  673:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    674:     return undef if (!$opened);
1.916     albertel  675: 
                    676:     flock($idf,LOCK_SH);
                    677:     my %disk_env;
                    678:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    679: 	    &GDBM_READER(),0640)) {
                    680: 	return undef;	
                    681:     }
                    682: 
                    683:     if (!defined($disk_env{'user.name'})
                    684: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   685:         untie(%disk_env);
1.916     albertel  686: 	return undef;
                    687:     }
1.1172.2.18  raeburn   688: 
1.1172.2.36  raeburn   689:     if (ref($userhashref) eq 'HASH') {
                    690:         $userhashref->{'name'} = $disk_env{'user.name'};
                    691:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   692:     }
1.1172.2.107  raeburn   693:     untie(%disk_env);
1.1172.2.18  raeburn   694: 
1.916     albertel  695:     return $handle;
                    696: }
                    697: 
1.830     albertel  698: sub timed_flock {
                    699:     my ($file,$lock_type) = @_;
                    700:     my $failed=0;
                    701:     eval {
                    702: 	local $SIG{__DIE__}='DEFAULT';
                    703: 	local $SIG{ALRM}=sub {
                    704: 	    $failed=1;
                    705: 	    die("failed lock");
                    706: 	};
                    707: 	alarm(13);
                    708: 	flock($file,$lock_type);
                    709: 	alarm(0);
                    710:     };
                    711:     if ($failed) {
                    712: 	return undef;
                    713:     } else {
                    714: 	return 1;
                    715:     }
                    716: }
                    717: 
1.1172.2.107  raeburn   718: sub get_sessionfile_vars {
                    719:     my ($handle,$lonidsdir,$storearr) = @_;
                    720:     my %returnhash;
                    721:     unless (ref($storearr) eq 'ARRAY') {
                    722:         return %returnhash;
                    723:     }
                    724:     if (-l "$lonidsdir/$handle.id") {
                    725:         my $link = readlink("$lonidsdir/$handle.id");
                    726:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    727:             $handle = $1;
                    728:         }
                    729:     }
                    730:     if ((-e "$lonidsdir/$handle.id") &&
                    731:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    732:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    733:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    734:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    735:                 flock($idf,LOCK_SH);
                    736:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    737:                         &GDBM_READER(),0640)) {
                    738:                     foreach my $item (@{$storearr}) {
                    739:                         $returnhash{$item} = $disk_env{$item};
                    740:                     }
                    741:                     untie(%disk_env);
                    742:                 }
                    743:             }
                    744:         }
                    745:     }
                    746:     return %returnhash;
                    747: }
                    748: 
1.5       www       749: # ---------------------------------------------------------- Append Environment
                    750: 
                    751: sub appenv {
1.949     raeburn   752:     my ($newenv,$roles) = @_;
                    753:     if (ref($newenv) eq 'HASH') {
                    754:         foreach my $key (keys(%{$newenv})) {
                    755:             my $refused = 0;
                    756: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    757:                 $refused = 1;
                    758:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   759:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   760:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    761:                         $refused = 0;
                    762:                     }
                    763:                 }
                    764:             }
                    765:             if ($refused) {
                    766:                 &logthis("<font color=\"blue\">WARNING: ".
                    767:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    768:                          .'</font>');
                    769: 	        delete($newenv->{$key});
                    770:             } else {
                    771:                 $env{$key}=$newenv->{$key};
                    772:             }
                    773:         }
1.1172.2.96  raeburn   774:         my $lonids = $perlvar{'lonIDsDir'};
                    775:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    776:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    777:             if ($opened
                    778: 	        && &timed_flock($env_file,LOCK_EX)
                    779: 	        &&
                    780: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    781: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    782: 	        while (my ($key,$value) = each(%{$newenv})) {
                    783: 	            $disk_env{$key} = $value;
                    784: 	        }
                    785: 	        untie(%disk_env);
                    786:             }
1.35      www       787:         }
1.191     harris41  788:     }
1.56      www       789:     return 'ok';
                    790: }
                    791: # ----------------------------------------------------- Delete from Environment
                    792: 
                    793: sub delenv {
1.1104    raeburn   794:     my ($delthis,$regexp,$roles) = @_;
                    795:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    796:         my $refused = 1;
                    797:         if (ref($roles) eq 'ARRAY') {
                    798:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    799:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    800:                 $refused = 0;
                    801:             }
                    802:         }
                    803:         if ($refused) {
                    804:             &logthis("<font color=\"blue\">WARNING: ".
                    805:                      "Attempt to delete from environment ".$delthis);
                    806:             return 'error';
                    807:         }
1.56      www       808:     }
1.917     albertel  809:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    810:     if ($opened
1.915     albertel  811: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  812: 	&&
                    813: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    814: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  815: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   816: 	    if ($regexp) {
                    817:                 if ($key=~/^$delthis/) {
                    818:                     delete($env{$key});
                    819:                     delete($disk_env{$key});
                    820:                 } 
                    821:             } else {
                    822:                 if ($key=~/^\Q$delthis\E/) {
                    823: 		    delete($env{$key});
                    824: 		    delete($disk_env{$key});
                    825: 	        }
                    826:             }
1.448     albertel  827: 	}
1.783     albertel  828: 	untie(%disk_env);
1.5       www       829:     }
                    830:     return 'ok';
1.369     albertel  831: }
                    832: 
1.790     albertel  833: sub get_env_multiple {
                    834:     my ($name) = @_;
                    835:     my @values;
                    836:     if (defined($env{$name})) {
                    837:         # exists is it an array
                    838:         if (ref($env{$name})) {
                    839:             @values=@{ $env{$name} };
                    840:         } else {
                    841:             $values[0]=$env{$name};
                    842:         }
                    843:     }
                    844:     return(@values);
                    845: }
                    846: 
1.958     www       847: # ------------------------------------------------------------------- Locking
                    848: 
                    849: sub set_lock {
                    850:     my ($text)=@_;
                    851:     $locknum++;
                    852:     my $id=$$.'-'.$locknum;
                    853:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    854:              'session.lock.'.$id => $text});
                    855:     return $id;
                    856: }
                    857: 
                    858: sub get_locks {
                    859:     my $num=0;
                    860:     my %texts=();
                    861:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    862:        if ($lock=~/\w/) {
                    863:           $num++;
                    864:           $texts{$lock}=$env{'session.lock.'.$lock};
                    865:        }
                    866:    }
                    867:    return ($num,%texts);
                    868: }
                    869: 
                    870: sub remove_lock {
                    871:     my ($id)=@_;
                    872:     my $newlocks='';
                    873:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    874:        if (($lock=~/\w/) && ($lock ne $id)) {
                    875:           $newlocks.=','.$lock;
                    876:        }
                    877:     }
                    878:     &appenv({'session.locks' => $newlocks});
                    879:     &delenv('session.lock.'.$id);
                    880: }
                    881: 
                    882: sub remove_all_locks {
                    883:     my $activelocks=$env{'session.locks'};
                    884:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    885:        if ($lock=~/\w/) {
                    886:           &remove_lock($lock);
                    887:        }
                    888:     }
                    889: }
                    890: 
                    891: 
1.369     albertel  892: # ------------------------------------------ Find out current server userload
                    893: sub userload {
                    894:     my $numusers=0;
                    895:     {
                    896: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    897: 	my $filename;
                    898: 	my $curtime=time;
                    899: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  900: 	    next if ($filename eq '.' || $filename eq '..');
                    901: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   902:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  905: 	}
                    906: 	closedir(LONIDS);
                    907:     }
                    908:     my $userloadpercent=0;
                    909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    910:     if ($maxuserload) {
1.371     albertel  911: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  912:     }
1.372     albertel  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  914:     return $userloadpercent;
1.283     www       915: }
                    916: 
1.1       albertel  917: # ------------------------------ Find server with least workload from spare.tab
1.11      www       918: 
1.1       albertel  919: sub spareserver {
1.1083    raeburn   920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  921:     my $spare_server;
1.370     albertel  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    924:                                                      :  $userloadpercent;
1.1083    raeburn   925:     my ($uint_dom,$remotesessions);
                    926:     if (($udom ne '') && (&domain($udom) ne '')) {
                    927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    930:         $remotesessions = $udomdefaults{'remotesessions'};
                    931:     }
1.1123    raeburn   932:     my $spareshash = &this_host_spares($udom);
                    933:     if (ref($spareshash) eq 'HASH') {
                    934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    937:                                              $try_server));
1.1123    raeburn   938: 	        ($spare_server, $lowest_load) =
                    939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    940:             }
1.1083    raeburn   941:         }
1.784     albertel  942: 
1.1123    raeburn   943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    944: 
                    945:         if (!$found_server) {
                    946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   948:                     next unless (&spare_can_host($udom,$uint_dom,
                    949:                                                  $remotesessions,$try_server));
1.1123    raeburn   950: 	            ($spare_server, $lowest_load) =
                    951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    952:                 }
                    953: 	    }
                    954:         }
1.784     albertel  955:     }
                    956: 
                    957:     if (!$want_server_name) {
1.1001    raeburn   958:         if (defined($spare_server)) {
                    959:             my $hostname = &hostname($spare_server);
1.1083    raeburn   960:             if (defined($hostname)) {
1.1172.2.118.  .3(raebu  961:20):                 my $protocol = 'http';
                    962:20):                 if ($protocol{$spare_server} eq 'https') {
                    963:20):                     $protocol = $protocol{$spare_server};
                    964:20):                 }
1.1001    raeburn   965: 	        $spare_server = $protocol.'://'.$hostname;
                    966:             }
                    967:         }
1.784     albertel  968:     }
                    969:     return $spare_server;
                    970: }
                    971: 
                    972: sub compare_server_load {
1.1172.2.41  raeburn   973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    974: 
                    975:     if ($required) {
                    976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    979:         if (($major eq '' && $minor eq '') ||
                    980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    981:             return ($spare_server,$lowest_load);
                    982:         }
                    983:     }
1.784     albertel  984: 
                    985:     my $loadans     = &reply('load',    $try_server);
                    986:     my $userloadans = &reply('userload',$try_server);
                    987: 
                    988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  990:     }
                    991: 
                    992:     my $load;
                    993:     if ($loadans =~ /\d/) {
                    994: 	if ($userloadans =~ /\d/) {
                    995: 	    #both are numbers, pick the bigger one
                    996: 	    $load = ($loadans > $userloadans) ? $loadans 
                    997: 		                              : $userloadans;
1.411     albertel  998: 	} else {
1.784     albertel  999: 	    $load = $loadans;
1.411     albertel 1000: 	}
1.784     albertel 1001:     } else {
                   1002: 	$load = $userloadans;
                   1003:     }
                   1004: 
                   1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1006: 	$spare_server = $try_server;
                   1007: 	$lowest_load  = $load;
1.370     albertel 1008:     }
1.784     albertel 1009:     return ($spare_server,$lowest_load);
1.202     matthew  1010: }
1.914     albertel 1011: 
                   1012: # --------------------------- ask offload servers if user already has a session
                   1013: sub find_existing_session {
                   1014:     my ($udom,$uname) = @_;
1.1123    raeburn  1015:     my $spareshash = &this_host_spares($udom);
                   1016:     if (ref($spareshash) eq 'HASH') {
                   1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1020:             }
                   1021:         }
                   1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1025:             }
                   1026:         }
1.914     albertel 1027:     }
                   1028:     return;
                   1029: }
                   1030: 
1.1172.2.107  raeburn  1031: # check if user's browser sent load balancer cookie and server still has session
                   1032: # and is not overloaded.
                   1033: sub check_for_balancer_cookie {
                   1034:     my ($r,$update_mtime) = @_;
                   1035:     my ($otherserver,$cookie);
                   1036:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1037:     if (exists($cookies{'balanceID'})) {
                   1038:         my $balid = $cookies{'balanceID'};
                   1039:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1040:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1041:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1042:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1043:                 my ($possudom,$possuname) = ($1,$2);
                   1044:                 my $has_session = 0;
                   1045:                 if ((&domain($possudom) ne '') &&
                   1046:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1047:                     my $try_server;
                   1048:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1049:                     if ($opened) {
                   1050:                         flock($idf,LOCK_SH);
                   1051:                         while (my $line = <$idf>) {
                   1052:                             chomp($line);
                   1053:                             if (&hostname($line) ne '') {
                   1054:                                 $try_server = $line;
                   1055:                                 last;
                   1056:                             }
                   1057:                         }
                   1058:                         close($idf);
                   1059:                         if (($try_server) &&
                   1060:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1061:                             my $lowest_load = 30000;
                   1062:                             ($otherserver,$lowest_load) =
                   1063:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1064:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1065:                                 $has_session = 1;
                   1066:                             } else {
                   1067:                                 undef($otherserver);
                   1068:                             }
                   1069:                         }
                   1070:                     }
                   1071:                 }
                   1072:                 if ($has_session) {
                   1073:                     if ($update_mtime) {
                   1074:                         my $atime = my $mtime = time;
                   1075:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1076:                     }
                   1077:                 } else {
                   1078:                     unlink("$balancedir/$cookie.id");
                   1079:                 }
                   1080:             }
                   1081:         }
                   1082:     }
                   1083:     return ($otherserver,$cookie);
                   1084: }
                   1085: 
1.1172.2.118.  .11(raeb 1086:-20): sub updatebalcookie {
                   1087:-20):     my ($cookie,$balancer,$lastentry)=@_;
                   1088:-20):     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1089:-20):         my ($udom,$uname) = ($1,$2);
                   1090:-20):         my $uprimary_id = &domain($udom,'primary');
                   1091:-20):         my $uintdom = &internet_dom($uprimary_id);
                   1092:-20):         my $intdom = &internet_dom($balancer);
                   1093:-20):         my $serverhomedom = &host_domain($balancer);
                   1094:-20):         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1095:-20):             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1096:-20):         }
                   1097:-20):     }
                   1098:-20):     return;
                   1099:-20): }
                   1100:-20): 
1.1172.2.107  raeburn  1101: sub delbalcookie {
                   1102:     my ($cookie,$balancer) =@_;
                   1103:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1104:         my ($udom,$uname) = ($1,$2);
                   1105:         my $uprimary_id = &domain($udom,'primary');
                   1106:         my $uintdom = &internet_dom($uprimary_id);
                   1107:         my $intdom = &internet_dom($balancer);
                   1108:         my $serverhomedom = &host_domain($balancer);
                   1109:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.118.  .11(raeb 1110:-20):             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1111:         }
                   1112:     }
                   1113: }
                   1114: 
1.914     albertel 1115: # -------------------------------- ask if server already has a session for user
                   1116: sub has_user_session {
                   1117:     my ($lonid,$udom,$uname) = @_;
                   1118:     my $result = &reply(join(':','userhassession',
                   1119: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1120:     return 1 if ($result eq 'ok');
                   1121: 
                   1122:     return 0;
                   1123: }
                   1124: 
1.1076    raeburn  1125: # --------- determine least loaded server in a user's domain which allows login
                   1126: 
                   1127: sub choose_server {
1.1172.2.47  raeburn  1128:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1129:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1130:     my %servers = &get_servers($udom);
1.1076    raeburn  1131:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1132:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1133:     if ($skiploadbal) {
                   1134:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1135:         unless (defined($cached)) {
                   1136:             my $cachetime = 60*60*24;
                   1137:             my %domconfig =
                   1138:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1139:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1140:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1141:                                            $cachetime);
                   1142:             }
                   1143:         }
                   1144:     }
1.1076    raeburn  1145:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1146:         my $loginvia;
1.1172.2.47  raeburn  1147:         if ($skiploadbal) {
                   1148:             if (ref($balancers) eq 'HASH') {
                   1149:                 next if (exists($balancers->{$lonhost}));
                   1150:             }
                   1151:         }
1.1115    raeburn  1152:         if ($checkloginvia) {
                   1153:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1154:             if ($loginvia) {
                   1155:                 my ($server,$path) = split(/:/,$loginvia);
                   1156:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1157:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1158:                 if ($login_host eq $server) {
                   1159:                     $portal_path = $path;
1.1151    raeburn  1160:                     $isredirect = 1;
1.1116    raeburn  1161:                 }
                   1162:             } else {
                   1163:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1164:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1165:                 if ($login_host eq $lonhost) {
                   1166:                     $portal_path = '';
1.1151    raeburn  1167:                     $isredirect = ''; 
1.1116    raeburn  1168:                 }
                   1169:             }
                   1170:         } else {
1.1076    raeburn  1171:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1172:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1173:         }
                   1174:     }
                   1175:     if ($login_host ne '') {
1.1116    raeburn  1176:         $hostname = &hostname($login_host);
1.1076    raeburn  1177:     }
1.1172.2.88  raeburn  1178:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1179: }
                   1180: 
1.1172.2.118.  .5(raebu 1181:20): sub get_course_sessions {
                   1182:20):     my ($cnum,$cdom,$lastactivity) = @_;
                   1183:20):     my %servers = &internet_dom_servers($cdom);
                   1184:20):     my %returnhash;
                   1185:20):     foreach my $server (sort(keys(%servers))) {
                   1186:20):         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1187:20):         my @pairs=split(/\&/,$rep);
                   1188:20):         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1189:20):             foreach my $item (@pairs) {
                   1190:20):                 my ($key,$value)=split(/=/,$item,2);
                   1191:20):                 $key = &unescape($key);
                   1192:20):                 next if ($key =~ /^error: 2 /);
                   1193:20):                 if (exists($returnhash{$key})) {
                   1194:20):                     next if ($value < $returnhash{$key});
                   1195:20):                 }
                   1196:20):                 $returnhash{$key}=$value;
                   1197:20):             }
                   1198:20):         }
                   1199:20):     }
                   1200:20):     return %returnhash;
                   1201:20): }
                   1202:20): 
1.202     matthew  1203: # --------------------------------------------- Try to change a user's password
                   1204: 
                   1205: sub changepass {
1.799     raeburn  1206:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1207:     $currentpass = &escape($currentpass);
                   1208:     $newpass     = &escape($newpass);
1.1030    raeburn  1209:     my $lonhost = $perlvar{'lonHostID'};
                   1210:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1211: 		       $server);
                   1212:     if (! $answer) {
                   1213: 	&logthis("No reply on password change request to $server ".
                   1214: 		 "by $uname in domain $udom.");
                   1215:     } elsif ($answer =~ "^ok") {
                   1216:         &logthis("$uname in $udom successfully changed their password ".
                   1217: 		 "on $server.");
                   1218:     } elsif ($answer =~ "^pwchange_failure") {
                   1219: 	&logthis("$uname in $udom was unable to change their password ".
                   1220: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1221: 		 "or pwchange");
                   1222:     } elsif ($answer =~ "^non_authorized") {
                   1223:         &logthis("$uname in $udom did not get their password correct when ".
                   1224: 		 "attempting to change it on $server.");
                   1225:     } elsif ($answer =~ "^auth_mode_error") {
                   1226:         &logthis("$uname in $udom attempted to change their password despite ".
                   1227: 		 "not being locally or internally authenticated on $server.");
                   1228:     } elsif ($answer =~ "^unknown_user") {
                   1229:         &logthis("$uname in $udom attempted to change their password ".
                   1230: 		 "on $server but were unable to because $server is not ".
                   1231: 		 "their home server.");
                   1232:     } elsif ($answer =~ "^refused") {
                   1233: 	&logthis("$server refused to change $uname in $udom password because ".
                   1234: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1235:     } elsif ($answer =~ "invalid_client") {
                   1236:         &logthis("$server refused to change $uname in $udom password because ".
                   1237:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1238:     } elsif ($answer =~ "^prioruse") {
                   1239:        &logthis("$server refused to change $uname in $udom password because ".
                   1240:                 "the password had been used before");
1.202     matthew  1241:     }
                   1242:     return $answer;
1.1       albertel 1243: }
                   1244: 
1.169     harris41 1245: # ----------------------- Try to determine user's current authentication scheme
                   1246: 
                   1247: sub queryauthenticate {
                   1248:     my ($uname,$udom)=@_;
1.456     albertel 1249:     my $uhome=&homeserver($uname,$udom);
                   1250:     if (!$uhome) {
                   1251: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1252: 	return 'no_host';
                   1253:     }
                   1254:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1255:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1256: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1257:     }
1.456     albertel 1258:     return $answer;
1.169     harris41 1259: }
                   1260: 
1.1       albertel 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1262: 
1.1       albertel 1263: sub authenticate {
1.1073    raeburn  1264:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1265:     $upass=&escape($upass);
                   1266:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1267:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1268:     my $newhome;
1.836     www      1269:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1270: # Maybe the machine was offline and only re-appeared again recently?
                   1271:         &reconlonc();
                   1272: # One more
1.952     raeburn  1273: 	$uhome=&homeserver($uname,$udom,1);
                   1274:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1275:             if (defined(&domain($udom,'primary'))) {
                   1276:                 $newhome=&domain($udom,'primary');
                   1277:             }
                   1278:             if ($newhome ne '') {
                   1279:                 $uhome = $newhome;
                   1280:             }
                   1281:         }
1.836     www      1282: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1283: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1284: 	    return 'no_host';
                   1285:         }
1.1       albertel 1286:     }
1.1073    raeburn  1287:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1288:     if ($answer eq 'authorized') {
1.952     raeburn  1289:         if ($newhome) {
                   1290:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1291:             return 'no_account_on_host'; 
                   1292:         } else {
                   1293:             &logthis("User $uname at $udom authorized by $uhome");
                   1294:             return $uhome;
                   1295:         }
1.471     albertel 1296:     }
                   1297:     if ($answer eq 'non_authorized') {
                   1298: 	&logthis("User $uname at $udom rejected by $uhome");
                   1299: 	return 'no_host'; 
1.9       www      1300:     }
1.471     albertel 1301:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1302:     return 'no_host';
                   1303: }
                   1304: 
1.1073    raeburn  1305: sub can_host_session {
1.1074    raeburn  1306:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1307:     my $canhost = 1;
1.1074    raeburn  1308:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1309:     if (ref($remotesessions) eq 'HASH') {
                   1310:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1311:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1312:                 $canhost = 0;
                   1313:             } else {
                   1314:                 $canhost = 1;
                   1315:             }
                   1316:         }
                   1317:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1319:                 $canhost = 1;
                   1320:             } else {
                   1321:                 $canhost = 0;
                   1322:             }
                   1323:         }
                   1324:         if ($canhost) {
                   1325:             if ($remotesessions->{'version'} ne '') {
                   1326:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1327:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1328:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1329:                         my $major = $1;
                   1330:                         my $minor = $2;
                   1331:                         if (($major < $reqmajor ) ||
                   1332:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1333:                             $canhost = 0;
                   1334:                         }
                   1335:                     } else {
                   1336:                         $canhost = 0;
                   1337:                     }
                   1338:                 }
                   1339:             }
                   1340:         }
                   1341:     }
                   1342:     if ($canhost) {
                   1343:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1344:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1345:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1346:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1347:                 if (($uint_dom ne '') && 
                   1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1349:                     $canhost = 0;
                   1350:                 } else {
                   1351:                     $canhost = 1;
                   1352:                 }
                   1353:             }
                   1354:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1355:                 if (($uint_dom ne '') && 
                   1356:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1357:                     $canhost = 1;
                   1358:                 } else {
                   1359:                     $canhost = 0;
                   1360:                 }
                   1361:             }
                   1362:         }
                   1363:     }
                   1364:     return $canhost;
                   1365: }
                   1366: 
1.1083    raeburn  1367: sub spare_can_host {
                   1368:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1369:     my $canhost=1;
1.1172.2.62  raeburn  1370:     my $try_server_hostname = &hostname($try_server);
                   1371:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1372:     my $serverhomedom = &host_domain($serverhomeID);
                   1373:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1374:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1375:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1376:             $canhost = 0;
                   1377:         }
                   1378:     }
                   1379:     if (($canhost) && ($uint_dom)) {
                   1380:         my @intdoms;
                   1381:         my $internet_names = &get_internet_names($try_server);
                   1382:         if (ref($internet_names) eq 'ARRAY') {
                   1383:             @intdoms = @{$internet_names};
                   1384:         }
                   1385:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1386:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1387:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1388:                                          $remotesessions,
                   1389:                                          $defdomdefaults{'hostedsessions'});
                   1390:         }
1.1083    raeburn  1391:     }
                   1392:     return $canhost;
                   1393: }
                   1394: 
1.1123    raeburn  1395: sub this_host_spares {
                   1396:     my ($dom) = @_;
1.1126    raeburn  1397:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1398:     my @hosts = &current_machine_ids();
                   1399:     foreach my $lonhost (@hosts) {
                   1400:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1401:             $dom_in_use = $dom;
                   1402:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1403:             last;
                   1404:         }
                   1405:     }
1.1126    raeburn  1406:     if ($dom_in_use ne '') {
                   1407:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1408:     }
                   1409:     if (ref($result) ne 'HASH') {
                   1410:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1411:         $dom_in_use = &host_domain($lonhost_in_use);
                   1412:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1413:         if (ref($result) ne 'HASH') {
                   1414:             $result = \%spareid;
                   1415:         }
                   1416:     }
                   1417:     return $result;
                   1418: }
                   1419: 
                   1420: sub spares_for_offload  {
                   1421:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1422:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1423:     if (defined($cached)) {
                   1424:         return $result;
                   1425:     } else {
1.1126    raeburn  1426:         my $cachetime = 60*60*24;
                   1427:         my %domconfig =
                   1428:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1429:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1430:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1431:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1432:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1433:                 }
                   1434:             }
                   1435:         }
                   1436:     }
1.1126    raeburn  1437:     return;
1.1123    raeburn  1438: }
                   1439: 
1.1129    raeburn  1440: sub get_lonbalancer_config {
                   1441:     my ($servers) = @_;
                   1442:     my ($currbalancer,$currtargets);
                   1443:     if (ref($servers) eq 'HASH') {
                   1444:         foreach my $server (keys(%{$servers})) {
                   1445:             my %what = (
                   1446:                          spareid => 1,
                   1447:                          perlvar => 1,
                   1448:                        );
                   1449:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1450:             if ($result eq 'ok') {
                   1451:                 if (ref($returnhash) eq 'HASH') {
                   1452:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1453:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1454:                             $currbalancer = $server;
                   1455:                             $currtargets = {};
                   1456:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1457:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1458:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1459:                                 }
                   1460:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1461:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1462:                                 }
                   1463:                             }
                   1464:                             last;
                   1465:                         }
                   1466:                     }
                   1467:                 }
                   1468:             }
                   1469:         }
                   1470:     }
                   1471:     return ($currbalancer,$currtargets);
                   1472: }
                   1473: 
                   1474: sub check_loadbalancing {
1.1172.2.88  raeburn  1475:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1476:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1477:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1478:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1479:     my @hosts = &current_machine_ids();
1.1129    raeburn  1480:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1481:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1482:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1483:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1484:     my $domneedscache; 
1.1129    raeburn  1485:     my $cachetime = 60*60*24;
                   1486: 
                   1487:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1488:         $dom_in_use = $udom;
                   1489:         $homeintdom = 1;
                   1490:     } else {
                   1491:         $dom_in_use = $serverhomedom;
                   1492:     }
                   1493:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1494:     unless (defined($cached)) {
                   1495:         my %domconfig =
                   1496:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1497:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1498:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1499:         } else {
                   1500:             $domneedscache = $dom_in_use;
1.1129    raeburn  1501:         }
                   1502:     }
                   1503:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1504:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1505:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1506:         if ($is_balancer) {
                   1507:             if (ref($currrules) eq 'HASH') {
                   1508:                 if ($homeintdom) {
                   1509:                     if ($uname ne '') {
                   1510:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1511:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1512:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1513:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1514:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1515:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1516:                             }
                   1517:                         }
                   1518:                         if ($rule_in_effect eq '') {
                   1519:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1520:                             if ($userenv{'inststatus'} ne '') {
                   1521:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1522:                                 my ($othertitle,$usertypes,$types) =
                   1523:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1524:                                 if (ref($types) eq 'ARRAY') {
                   1525:                                     foreach my $type (@{$types}) {
                   1526:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1527:                                             if (exists($currrules->{$type})) {
                   1528:                                                 $rule_in_effect = $currrules->{$type};
                   1529:                                             }
                   1530:                                         }
                   1531:                                     }
                   1532:                                 }
                   1533:                             } else {
                   1534:                                 if (exists($currrules->{'default'})) {
                   1535:                                     $rule_in_effect = $currrules->{'default'};
                   1536:                                 }
                   1537:                             }
                   1538:                         }
                   1539:                     } else {
                   1540:                         if (exists($currrules->{'default'})) {
                   1541:                             $rule_in_effect = $currrules->{'default'};
                   1542:                         }
                   1543:                     }
                   1544:                 } else {
                   1545:                     if ($currrules->{'_LC_external'} ne '') {
                   1546:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1547:                     }
                   1548:                 }
                   1549:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1550:                                                        $uname,$udom);
                   1551:             }
                   1552:         }
                   1553:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1554:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1555:         unless (defined($cached)) {
                   1556:             my %domconfig =
                   1557:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1558:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1559:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1560:             } else {
                   1561:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1562:             }
                   1563:         }
                   1564:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1565:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1566:                 &check_balancer_result($result,@hosts);
                   1567:             if ($is_balancer) {
1.1129    raeburn  1568:                 if (ref($currrules) eq 'HASH') {
                   1569:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1570:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1571:                     }
                   1572:                 }
                   1573:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1574:                                                        $uname,$udom);
                   1575:             }
                   1576:         } else {
                   1577:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1578:                 $is_balancer = 1;
                   1579:                 $offloadto = &this_host_spares($dom_in_use);
                   1580:             }
1.1172.2.75  raeburn  1581:             unless (defined($cached)) {
                   1582:                 $domneedscache = $serverhomedom;
                   1583:             }
1.1129    raeburn  1584:         }
                   1585:     } else {
                   1586:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1587:             $is_balancer = 1;
                   1588:             $offloadto = &this_host_spares($dom_in_use);
                   1589:         }
1.1172.2.75  raeburn  1590:         unless (defined($cached)) {
                   1591:             $domneedscache = $serverhomedom;
                   1592:         }
                   1593:     }
                   1594:     if ($domneedscache) {
                   1595:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1596:     }
1.1172.2.118.  .11(raeb 1597:-20):     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1598:         my $lowest_load = 30000;
                   1599:         if (ref($offloadto) eq 'HASH') {
                   1600:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1601:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1602:                     ($otherserver,$lowest_load) =
                   1603:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1604:                 }
1.1129    raeburn  1605:             }
1.1172.2.5  raeburn  1606:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1607: 
1.1172.2.5  raeburn  1608:             if (!$found_server) {
                   1609:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1610:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1611:                         ($otherserver,$lowest_load) =
                   1612:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1613:                     }
                   1614:                 }
                   1615:             }
                   1616:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1617:             if (@{$offloadto} == 1) {
                   1618:                 $otherserver = $offloadto->[0];
                   1619:             } elsif (@{$offloadto} > 1) {
                   1620:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1621:                     ($otherserver,$lowest_load) =
                   1622:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1623:                 }
                   1624:             }
                   1625:         }
1.1172.2.88  raeburn  1626:         unless ($caller eq 'login') {
                   1627:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1628:                 $is_balancer = 0;
                   1629:                 if ($uname ne '' && $udom ne '') {
                   1630:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1631:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1632:                                  'user.loadbalcheck.time' => time});
                   1633:                     }
1.1172.2.5  raeburn  1634:                 }
1.1129    raeburn  1635:             }
                   1636:         }
1.1172.2.118.  .11(raeb 1637:-20):     }
                   1638:-20):     if (($is_balancer) && (!$homeintdom)) {
                   1639:-20):         undef($setcookie);
1.1129    raeburn  1640:     }
1.1172.2.107  raeburn  1641:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1642: }
                   1643: 
1.1172.2.12  raeburn  1644: sub check_balancer_result {
                   1645:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1646:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1647:     if (ref($result) eq 'HASH') {
                   1648:         if ($result->{'lonhost'} ne '') {
                   1649:             my $currbalancer = $result->{'lonhost'};
                   1650:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1651:                 $is_balancer = 1;
                   1652:                 $currtargets = $result->{'targets'};
                   1653:                 $currrules = $result->{'rules'};
                   1654:             }
                   1655:         } else {
                   1656:             foreach my $key (keys(%{$result})) {
                   1657:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1658:                     (ref($result->{$key}) eq 'HASH')) {
                   1659:                     $is_balancer = 1;
                   1660:                     $currrules = $result->{$key}{'rules'};
                   1661:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1662:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1663:                     last;
                   1664:                 }
                   1665:             }
                   1666:         }
                   1667:     }
1.1172.2.107  raeburn  1668:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1669: }
                   1670: 
1.1129    raeburn  1671: sub get_loadbalancer_targets {
                   1672:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1673:     my $offloadto;
1.1172.2.4  raeburn  1674:     if ($rule_in_effect eq 'none') {
                   1675:         return [$perlvar{'lonHostID'}];
                   1676:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1677:         $offloadto = $currtargets;
                   1678:     } else {
                   1679:         if ($rule_in_effect eq 'homeserver') {
                   1680:             my $homeserver = &homeserver($uname,$udom);
                   1681:             if ($homeserver ne 'no_host') {
                   1682:                 $offloadto = [$homeserver];
                   1683:             }
                   1684:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1685:             my %domconfig =
                   1686:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1687:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1688:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1689:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1690:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1691:                     }
                   1692:                 }
                   1693:             } else {
1.1172.2.7  raeburn  1694:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1695:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1696:                 if (&hostname($remotebalancer) ne '') {
                   1697:                     $offloadto = [$remotebalancer];
                   1698:                 }
                   1699:             }
                   1700:         } elsif (&hostname($rule_in_effect) ne '') {
                   1701:             $offloadto = [$rule_in_effect];
                   1702:         }
                   1703:     }
                   1704:     return $offloadto;
                   1705: }
                   1706: 
1.1127    raeburn  1707: sub internet_dom_servers {
                   1708:     my ($dom) = @_;
                   1709:     my (%uniqservers,%servers);
                   1710:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1711:     my @machinedoms = &machine_domains($primaryserver);
                   1712:     foreach my $mdom (@machinedoms) {
                   1713:         my %currservers = %servers;
                   1714:         my %server = &get_servers($mdom);
                   1715:         %servers = (%currservers,%server);
                   1716:     }
                   1717:     my %by_hostname;
                   1718:     foreach my $id (keys(%servers)) {
                   1719:         push(@{$by_hostname{$servers{$id}}},$id);
                   1720:     }
                   1721:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1722:         if (@{$by_hostname{$hostname}} > 1) {
                   1723:             my $match = 0;
                   1724:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1725:                 if (&host_domain($id) eq $dom) {
                   1726:                     $uniqservers{$id} = $hostname;
                   1727:                     $match = 1;
                   1728:                 }
                   1729:             }
                   1730:             unless ($match) {
                   1731:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1732:             }
                   1733:         } else {
                   1734:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1735:         }
                   1736:     }
                   1737:     return %uniqservers;
                   1738: }
                   1739: 
1.1       albertel 1740: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1741: 
1.599     albertel 1742: my %homecache;
1.1       albertel 1743: sub homeserver {
1.230     stredwic 1744:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1745:     my $index="$uname:$udom";
1.426     albertel 1746: 
1.599     albertel 1747:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1748: 
                   1749:     my %servers = &get_servers($udom,'library');
                   1750:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1751:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1752: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1753: 
                   1754: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1755: 	if ($answer eq 'found') {
                   1756: 	    delete($badServerCache{$tryserver}); 
                   1757: 	    return $homecache{$index}=$tryserver;
                   1758: 	} elsif ($answer eq 'no_host') {
                   1759: 	    $badServerCache{$tryserver}=1;
                   1760: 	}
1.1       albertel 1761:     }    
                   1762:     return 'no_host';
1.70      www      1763: }
                   1764: 
                   1765: # ------------------------------------- Find the usernames behind a list of IDs
                   1766: 
                   1767: sub idget {
                   1768:     my ($udom,@ids)=@_;
                   1769:     my %returnhash=();
                   1770:     
1.841     albertel 1771:     my %servers = &get_servers($udom,'library');
                   1772:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1773: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1774: 	$idlist=~tr/A-Z/a-z/; 
                   1775: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1776: 	my @answer=();
                   1777: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1778: 	    @answer=split(/\&/,$reply);
                   1779: 	}                    ;
                   1780: 	my $i;
                   1781: 	for ($i=0;$i<=$#ids;$i++) {
                   1782: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1783: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1784: 	    } 
                   1785: 	}
                   1786:     } 
1.70      www      1787:     return %returnhash;
                   1788: }
                   1789: 
                   1790: # ------------------------------------- Find the IDs behind a list of usernames
                   1791: 
                   1792: sub idrget {
                   1793:     my ($udom,@unames)=@_;
                   1794:     my %returnhash=();
1.800     albertel 1795:     foreach my $uname (@unames) {
                   1796:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1797:     }
1.70      www      1798:     return %returnhash;
                   1799: }
                   1800: 
                   1801: # ------------------------------- Store away a list of names and associated IDs
                   1802: 
                   1803: sub idput {
                   1804:     my ($udom,%ids)=@_;
                   1805:     my %servers=();
1.800     albertel 1806:     foreach my $uname (keys(%ids)) {
                   1807: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1808:         my $uhom=&homeserver($uname,$udom);
1.70      www      1809:         if ($uhom ne 'no_host') {
1.800     albertel 1810:             my $id=&escape($ids{$uname});
1.70      www      1811:             $id=~tr/A-Z/a-z/;
1.800     albertel 1812:             my $esc_unam=&escape($uname);
1.70      www      1813: 	    if ($servers{$uhom}) {
1.800     albertel 1814: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1815:             } else {
1.800     albertel 1816:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1817:             }
                   1818:         }
1.191     harris41 1819:     }
1.800     albertel 1820:     foreach my $server (keys(%servers)) {
                   1821:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1822:     }
1.344     www      1823: }
                   1824: 
1.1172.2.30  raeburn  1825: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1826: 
                   1827: sub iddel {
                   1828:     my ($udom,$idshashref,$uhome)=@_;
                   1829:     my %result=();
                   1830:     unless (ref($idshashref) eq 'HASH') {
                   1831:         return %result;
                   1832:     }
                   1833:     my %servers=();
                   1834:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1835:         my $uhom;
                   1836:         if ($uhome) {
                   1837:             $uhom = $uhome;
                   1838:         } else {
                   1839:             $uhom=&homeserver($uname,$udom);
                   1840:         }
                   1841:         if ($uhom ne 'no_host') {
                   1842:             if ($servers{$uhom}) {
                   1843:                 $servers{$uhom}.='&'.&escape($id);
                   1844:             } else {
                   1845:                 $servers{$uhom}=&escape($id);
                   1846:             }
                   1847:         }
                   1848:     }
                   1849:     foreach my $server (keys(%servers)) {
                   1850:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1851:     }
                   1852:     return %result;
                   1853: }
                   1854: 
1.1023    raeburn  1855: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1856: sub dump_dom {
1.1165    droeschl 1857:     my ($namespace, $udom, $regexp) = @_;
                   1858: 
                   1859:     $udom ||= $env{'user.domain'};
                   1860: 
                   1861:     return () unless $udom;
                   1862: 
                   1863:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1864: }
                   1865: 
1.1023    raeburn  1866: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1867: 
                   1868: sub get_dom {
1.860     raeburn  1869:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1870:     return if ($udom eq 'public');
1.806     raeburn  1871:     my $items='';
                   1872:     foreach my $item (@$storearr) {
                   1873:         $items.=&escape($item).'&';
                   1874:     }
                   1875:     $items=~s/\&$//;
1.860     raeburn  1876:     if (!$udom) {
                   1877:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1878:         return if ($udom eq 'public');
1.860     raeburn  1879:         if (defined(&domain($udom,'primary'))) {
                   1880:             $uhome=&domain($udom,'primary');
                   1881:         } else {
1.874     albertel 1882:             undef($uhome);
1.860     raeburn  1883:         }
                   1884:     } else {
                   1885:         if (!$uhome) {
                   1886:             if (defined(&domain($udom,'primary'))) {
                   1887:                 $uhome=&domain($udom,'primary');
                   1888:             }
                   1889:         }
                   1890:     }
                   1891:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.118.  .1(raebu 1892:20):         my $rep;
                   1893:20):         if ($namespace =~ /^enc/) {
                   1894:20):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1895:20):         } else {
                   1896:20):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1897:20):         }
1.866     raeburn  1898:         my %returnhash;
1.875     albertel 1899:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1900:             return %returnhash;
                   1901:         }
1.806     raeburn  1902:         my @pairs=split(/\&/,$rep);
                   1903:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1904:             return @pairs;
                   1905:         }
                   1906:         my $i=0;
                   1907:         foreach my $item (@$storearr) {
                   1908:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1909:             $i++;
                   1910:         }
                   1911:         return %returnhash;
                   1912:     } else {
1.880     banghart 1913:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1914:     }
                   1915: }
                   1916: 
                   1917: # -------------------------------------------- put items in domain db files 
                   1918: 
                   1919: sub put_dom {
1.860     raeburn  1920:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1921:     if (!$udom) {
                   1922:         $udom=$env{'user.domain'};
                   1923:         if (defined(&domain($udom,'primary'))) {
                   1924:             $uhome=&domain($udom,'primary');
                   1925:         } else {
1.874     albertel 1926:             undef($uhome);
1.860     raeburn  1927:         }
                   1928:     } else {
                   1929:         if (!$uhome) {
                   1930:             if (defined(&domain($udom,'primary'))) {
                   1931:                 $uhome=&domain($udom,'primary');
                   1932:             }
                   1933:         }
                   1934:     } 
                   1935:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1936:         my $items='';
                   1937:         foreach my $item (keys(%$storehash)) {
                   1938:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1939:         }
                   1940:         $items=~s/\&$//;
1.1172.2.118.  .1(raebu 1941:20):         if ($namespace =~ /^enc/) {
                   1942:20):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1943:20):         } else {
                   1944:20):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1945:20):         }
1.806     raeburn  1946:     } else {
1.860     raeburn  1947:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1948:     }
                   1949: }
                   1950: 
1.1023    raeburn  1951: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1952: sub newput_dom {
1.1023    raeburn  1953:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1954:     my $result;
                   1955:     if (!$udom) {
                   1956:         $udom=$env{'user.domain'};
                   1957:     }
1.1023    raeburn  1958:     if ($udom) {
                   1959:         my $uname = &get_domainconfiguser($udom);
                   1960:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1961:     }
                   1962:     return $result;
                   1963: }
                   1964: 
1.1023    raeburn  1965: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1966: sub del_dom {
1.1023    raeburn  1967:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1968:     if (ref($storearr) eq 'ARRAY') {
                   1969:         if (!$udom) {
                   1970:             $udom=$env{'user.domain'};
                   1971:         }
1.1023    raeburn  1972:         if ($udom) {
                   1973:             my $uname = &get_domainconfiguser($udom); 
                   1974:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1975:         }
                   1976:     }
                   1977: }
                   1978: 
1.1023    raeburn  1979: # ----------------------------------construct domainconfig user for a domain 
                   1980: sub get_domainconfiguser {
                   1981:     my ($udom) = @_;
                   1982:     return $udom.'-domainconfig';
                   1983: }
                   1984: 
1.837     raeburn  1985: sub retrieve_inst_usertypes {
                   1986:     my ($udom) = @_;
                   1987:     my (%returnhash,@order);
1.989     raeburn  1988:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1989:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1990:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1991:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1992:     } else {
                   1993:         if (defined(&domain($udom,'primary'))) {
                   1994:             my $uhome=&domain($udom,'primary');
                   1995:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1996:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1997:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1998:                 return (\%returnhash,\@order);
                   1999:             }
                   2000:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2001:             my @pairs=split(/\&/,$hashitems);
                   2002:             foreach my $item (@pairs) {
                   2003:                 my ($key,$value)=split(/=/,$item,2);
                   2004:                 $key = &unescape($key);
                   2005:                 next if ($key =~ /^error: 2 /);
                   2006:                 $returnhash{$key}=&thaw_unescape($value);
                   2007:             }
                   2008:             my @esc_order = split(/\&/,$orderitems);
                   2009:             foreach my $item (@esc_order) {
                   2010:                 push(@order,&unescape($item));
                   2011:             }
                   2012:         } else {
1.1172.2.44  raeburn  2013:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2014:         }
1.1172.2.44  raeburn  2015:         return (\%returnhash,\@order);
1.837     raeburn  2016:     }
                   2017: }
                   2018: 
1.868     raeburn  2019: sub is_domainimage {
                   2020:     my ($url) = @_;
1.1172.2.74  raeburn  2021:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2022:         if (&domain($1) ne '') {
                   2023:             return '1';
                   2024:         }
                   2025:     }
                   2026:     return;
                   2027: }
                   2028: 
1.899     raeburn  2029: sub inst_directory_query {
                   2030:     my ($srch) = @_;
                   2031:     my $udom = $srch->{'srchdomain'};
                   2032:     my %results;
                   2033:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2034:     my $outcome;
1.899     raeburn  2035:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2036:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2037:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2038:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2039:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2040:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2041:                     (($major == 2) && ($minor < 11)) ||
                   2042:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2043:                     return;
                   2044:                 }
                   2045:             }
                   2046:         }
1.904     albertel 2047: 	my $queryid=&reply("querysend:instdirsearch:".
                   2048: 			   &escape($srch->{'srchby'}).':'.
                   2049: 			   &escape($srch->{'srchterm'}).':'.
                   2050: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2051: 	my $host=&hostname($homeserver);
                   2052: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2053: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2054: 	    return;
                   2055: 	}
                   2056: 	my $response = &get_query_reply($queryid);
                   2057: 	my $maxtries = 5;
                   2058: 	my $tries = 1;
                   2059: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2060: 	    $response = &get_query_reply($queryid);
                   2061: 	    $tries ++;
                   2062: 	}
                   2063: 
                   2064:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2065:             if ($response eq 'unavailable') {
                   2066:                 $outcome = $response;
                   2067:             } else {
                   2068:                 $outcome = 'ok';
                   2069:                 my @matches = split(/\n/,$response);
                   2070:                 foreach my $match (@matches) {
                   2071:                     my ($key,$value) = split(/=/,$match);
                   2072:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2073:                 }
1.899     raeburn  2074:             }
                   2075:         }
                   2076:     }
1.909     raeburn  2077:     return ($outcome,%results);
1.899     raeburn  2078: }
                   2079: 
                   2080: sub usersearch {
                   2081:     my ($srch) = @_;
                   2082:     my $dom = $srch->{'srchdomain'};
                   2083:     my %results;
                   2084:     my %libserv = &all_library();
                   2085:     my $query = 'usersearch';
                   2086:     foreach my $tryserver (keys(%libserv)) {
                   2087:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2088:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2089:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2090:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118.  .2(raebu 2091:20):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2092:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2093:                              (($major == 2) && ($minor < 11)) ||
                   2094:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2095:                 }
                   2096:             }
1.899     raeburn  2097:             my $host=&hostname($tryserver);
                   2098:             my $queryid=
1.911     raeburn  2099:                 &reply("querysend:".&escape($query).':'.
                   2100:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2101:                        &escape($srch->{'srchtype'}).':'.
                   2102:                        &escape($srch->{'srchterm'}),$tryserver);
                   2103:             if ($queryid !~/^\Q$host\E\_/) {
                   2104:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2105:                 next;
1.899     raeburn  2106:             }
                   2107:             my $reply = &get_query_reply($queryid);
                   2108:             my $maxtries = 1;
                   2109:             my $tries = 1;
                   2110:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2111:                 $reply = &get_query_reply($queryid);
                   2112:                 $tries ++;
                   2113:             }
                   2114:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2115:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2116:             } else {
1.911     raeburn  2117:                 my @matches;
                   2118:                 if ($reply =~ /\n/) {
                   2119:                     @matches = split(/\n/,$reply);
                   2120:                 } else {
                   2121:                     @matches = split(/\&/,$reply);
                   2122:                 }
1.899     raeburn  2123:                 foreach my $match (@matches) {
                   2124:                     my ($uname,$udom,%userhash);
1.911     raeburn  2125:                     foreach my $entry (split(/:/,$match)) {
                   2126:                         my ($key,$value) =
                   2127:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2128:                         $userhash{$key} = $value;
                   2129:                         if ($key eq 'username') {
                   2130:                             $uname = $value;
                   2131:                         } elsif ($key eq 'domain') {
                   2132:                             $udom = $value;
1.911     raeburn  2133:                         }
1.899     raeburn  2134:                     }
                   2135:                     $results{$uname.':'.$udom} = \%userhash;
                   2136:                 }
                   2137:             }
                   2138:         }
                   2139:     }
                   2140:     return %results;
                   2141: }
                   2142: 
1.912     raeburn  2143: sub get_instuser {
                   2144:     my ($udom,$uname,$id) = @_;
                   2145:     my $homeserver = &domain($udom,'primary');
                   2146:     my ($outcome,%results);
                   2147:     if ($homeserver ne '') {
                   2148:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2149:                            &escape($id).':'.&escape($udom),$homeserver);
                   2150:         my $host=&hostname($homeserver);
                   2151:         if ($queryid !~/^\Q$host\E\_/) {
                   2152:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2153:             return;
                   2154:         }
                   2155:         my $response = &get_query_reply($queryid);
                   2156:         my $maxtries = 5;
                   2157:         my $tries = 1;
                   2158:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2159:             $response = &get_query_reply($queryid);
                   2160:             $tries ++;
                   2161:         }
                   2162:         if (!&error($response) && $response ne 'refused') {
                   2163:             if ($response eq 'unavailable') {
                   2164:                 $outcome = $response;
                   2165:             } else {
                   2166:                 $outcome = 'ok';
                   2167:                 my @matches = split(/\n/,$response);
                   2168:                 foreach my $match (@matches) {
                   2169:                     my ($key,$value) = split(/=/,$match);
                   2170:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2171:                 }
                   2172:             }
                   2173:         }
                   2174:     }
                   2175:     my %userinfo;
                   2176:     if (ref($results{$uname}) eq 'HASH') {
                   2177:         %userinfo = %{$results{$uname}};
                   2178:     } 
                   2179:     return ($outcome,%userinfo);
                   2180: }
                   2181: 
1.1172.2.69  raeburn  2182: sub get_multiple_instusers {
                   2183:     my ($udom,$users,$caller) = @_;
                   2184:     my ($outcome,$results);
                   2185:     if (ref($users) eq 'HASH') {
                   2186:         my $count = keys(%{$users});
                   2187:         my $requested = &freeze_escape($users);
                   2188:         my $homeserver = &domain($udom,'primary');
                   2189:         if ($homeserver ne '') {
                   2190:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2191:             my $host=&hostname($homeserver);
                   2192:             if ($queryid !~/^\Q$host\E\_/) {
                   2193:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2194:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2195:                 return ($outcome,$results);
                   2196:             }
                   2197:             my $response = &get_query_reply($queryid);
                   2198:             my $maxtries = 5;
                   2199:             if ($count > 100) {
                   2200:                 $maxtries = 1+int($count/20);
                   2201:             }
                   2202:             my $tries = 1;
                   2203:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2204:                 $response = &get_query_reply($queryid);
                   2205:                 $tries ++;
                   2206:             }
                   2207:             if ($response eq '') {
                   2208:                 $results = {};
                   2209:                 foreach my $key (keys(%{$users})) {
                   2210:                     my ($uname,$id);
                   2211:                     if ($caller eq 'id') {
                   2212:                         $id = $key;
                   2213:                     } else {
                   2214:                         $uname = $key;
                   2215:                     }
                   2216:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2217:                     $outcome = $resp;
                   2218:                     if ($resp eq 'ok') {
                   2219:                         %{$results} = (%{$results}, %info);
                   2220:                     } else {
                   2221:                         last;
                   2222:                     }
                   2223:                 }
                   2224:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2225:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2226:                     $outcome = $response;
                   2227:                 } else {
                   2228:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2229:                     if ($outcome eq 'ok') {
                   2230:                         $results = &thaw_unescape($userdata);
                   2231:                     }
                   2232:                 }
                   2233:             }
                   2234:         }
                   2235:     }
                   2236:     return ($outcome,$results);
                   2237: }
                   2238: 
1.912     raeburn  2239: sub inst_rulecheck {
1.923     raeburn  2240:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2241:     my %returnhash;
                   2242:     if ($udom ne '') {
                   2243:         if (ref($rules) eq 'ARRAY') {
                   2244:             @{$rules} = map {&escape($_);} (@{$rules});
                   2245:             my $rulestr = join(':',@{$rules});
                   2246:             my $homeserver=&domain($udom,'primary');
                   2247:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2248:                 my $response;
                   2249:                 if ($item eq 'username') {                
                   2250:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2251:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2252:                                               $homeserver));
1.923     raeburn  2253:                 } elsif ($item eq 'id') {
                   2254:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2255:                                               ':'.&escape($id).':'.$rulestr,
                   2256:                                               $homeserver));
1.945     raeburn  2257:                 } elsif ($item eq 'selfcreate') {
                   2258:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2259:                                                &escape($udom).':'.&escape($uname).
                   2260:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2261:                 }
1.912     raeburn  2262:                 if ($response ne 'refused') {
                   2263:                     my @pairs=split(/\&/,$response);
                   2264:                     foreach my $item (@pairs) {
                   2265:                         my ($key,$value)=split(/=/,$item,2);
                   2266:                         $key = &unescape($key);
                   2267:                         next if ($key =~ /^error: 2 /);
                   2268:                         $returnhash{$key}=&thaw_unescape($value);
                   2269:                     }
                   2270:                 }
                   2271:             }
                   2272:         }
                   2273:     }
                   2274:     return %returnhash;
                   2275: }
                   2276: 
                   2277: sub inst_userrules {
1.923     raeburn  2278:     my ($udom,$check) = @_;
1.912     raeburn  2279:     my (%ruleshash,@ruleorder);
                   2280:     if ($udom ne '') {
                   2281:         my $homeserver=&domain($udom,'primary');
                   2282:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2283:             my $response;
                   2284:             if ($check eq 'id') {
                   2285:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2286:                                  $homeserver);
1.943     raeburn  2287:             } elsif ($check eq 'email') {
                   2288:                 $response=&reply('instemailrules:'.&escape($udom),
                   2289:                                  $homeserver);
1.923     raeburn  2290:             } else {
                   2291:                 $response=&reply('instuserrules:'.&escape($udom),
                   2292:                                  $homeserver);
                   2293:             }
1.912     raeburn  2294:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2295:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2296:                 ($response ne 'no_such_host')) {
                   2297:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2298:                 my @pairs=split(/\&/,$hashitems);
                   2299:                 foreach my $item (@pairs) {
                   2300:                     my ($key,$value)=split(/=/,$item,2);
                   2301:                     $key = &unescape($key);
                   2302:                     next if ($key =~ /^error: 2 /);
                   2303:                     $ruleshash{$key}=&thaw_unescape($value);
                   2304:                 }
                   2305:                 my @esc_order = split(/\&/,$orderitems);
                   2306:                 foreach my $item (@esc_order) {
                   2307:                     push(@ruleorder,&unescape($item));
                   2308:                 }
                   2309:             }
                   2310:         }
                   2311:     }
                   2312:     return (\%ruleshash,\@ruleorder);
                   2313: }
                   2314: 
1.976     raeburn  2315: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2316: 
                   2317: sub get_domain_defaults {
1.1172.2.35  raeburn  2318:     my ($domain,$ignore_cache) = @_;
                   2319:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2320:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2321:     unless ($ignore_cache) {
                   2322:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2323:         if (defined($cached)) {
                   2324:             if (ref($result) eq 'HASH') {
                   2325:                 return %{$result};
                   2326:             }
1.943     raeburn  2327:         }
                   2328:     }
                   2329:     my %domdefaults;
                   2330:     my %domconfig =
1.989     raeburn  2331:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2332:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2333:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2334:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2335:                                   'coursecategories','autoenroll',
                   2336:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2337:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2338:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2339:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2340:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2341:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2342:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2343:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2344:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2345:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2346:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2347:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2348:     } else {
                   2349:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2350:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2351:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2352:     }
1.976     raeburn  2353:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2354:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2355:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2356:         } else {
                   2357:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2358:         }
1.1172.2.6  raeburn  2359:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2360:         foreach my $item (@usertools) {
                   2361:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2362:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2363:             }
                   2364:         }
1.1172.2.29  raeburn  2365:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2366:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2367:         }
1.976     raeburn  2368:     }
1.985     raeburn  2369:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2370:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2371:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2372:         }
                   2373:     }
1.1172.2.9  raeburn  2374:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2375:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2376:     }
1.989     raeburn  2377:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2378:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2379:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2380:         }
                   2381:     }
1.1047    raeburn  2382:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2383:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2384:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2385:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2386:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2387:         }
1.1172.2.41  raeburn  2388:         foreach my $type (@coursetypes) {
                   2389:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2390:                 unless ($type eq 'community') {
                   2391:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2392:                 }
                   2393:             }
                   2394:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2395:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2396:             }
1.1172.2.60  raeburn  2397:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2398:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2399:                     $domdefaults{$type.'postsubtimeout'} =
                   2400:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2401:                 }
                   2402:             }
1.1172.2.30  raeburn  2403:         }
1.1172.2.67  raeburn  2404:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2405:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2406:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2407:                 if (@clonecodes) {
                   2408:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2409:                 }
                   2410:             }
                   2411:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2412:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2413:         }
1.1172.2.103  raeburn  2414:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2415:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2416:         }
1.1047    raeburn  2417:     }
1.1073    raeburn  2418:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2419:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2420:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2421:         }
                   2422:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2423:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2424:         }
1.1172.2.62  raeburn  2425:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2426:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2427:         }
1.1073    raeburn  2428:     }
1.1172.2.41  raeburn  2429:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2430:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2431:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2432:                             'approval','limit');
                   2433:             foreach my $type (@coursetypes) {
                   2434:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2435:                     my @mgrdc = ();
                   2436:                     foreach my $item (@settings) {
                   2437:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2438:                             push(@mgrdc,$item);
                   2439:                         }
                   2440:                     }
                   2441:                     if (@mgrdc) {
                   2442:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2443:                     }
                   2444:                 }
                   2445:             }
                   2446:         }
                   2447:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2448:             foreach my $type (@coursetypes) {
                   2449:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2450:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2451:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2452:                     }
                   2453:                 }
                   2454:             }
                   2455:         }
                   2456:     }
1.1172.2.46  raeburn  2457:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2458:         $domdefaults{'catauth'} = 'std';
                   2459:         $domdefaults{'catunauth'} = 'std';
                   2460:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2461:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2462:         }
                   2463:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2464:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2465:         }
                   2466:     }
1.1172.2.76  raeburn  2467:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2468:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2469:     }
1.1172.2.89  raeburn  2470:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2471:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2472:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2473:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2474:         }
                   2475:     }
1.1172.2.23  raeburn  2476:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2477:     return %domdefaults;
                   2478: }
                   2479: 
1.1172.2.106  raeburn  2480: sub get_dom_cats {
                   2481:     my ($dom) = @_;
                   2482:     return unless (&domain($dom));
                   2483:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2484:     unless (defined($cached)) {
                   2485:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2486:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2487:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2488:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2489:             } else {
                   2490:                 $cats = {};
                   2491:             }
                   2492:         } else {
                   2493:             $cats = {};
                   2494:         }
                   2495:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2496:     }
                   2497:     return $cats;
                   2498: }
                   2499: 
                   2500: sub get_dom_instcats {
                   2501:     my ($dom) = @_;
                   2502:     return unless (&domain($dom));
                   2503:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2504:     unless (defined($cached)) {
                   2505:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2506:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2507:         if ($totcodes > 0) {
                   2508:             my $caller = 'global';
                   2509:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2510:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2511:                 $instcats = {
                   2512:                                 codes => \%codes,
                   2513:                                 codetitles => \@codetitles,
                   2514:                                 cat_titles => \%cat_titles,
                   2515:                                 cat_order => \%cat_order,
                   2516:                             };
                   2517:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2518:             }
                   2519:         }
                   2520:     }
                   2521:     return $instcats;
                   2522: }
                   2523: 
                   2524: sub retrieve_instcodes {
                   2525:     my ($coursecodes,$dom) = @_;
                   2526:     my $totcodes;
                   2527:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2528:     foreach my $course (keys(%courses)) {
                   2529:         if (ref($courses{$course}) eq 'HASH') {
                   2530:             if ($courses{$course}{'inst_code'} ne '') {
                   2531:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2532:                 $totcodes ++;
                   2533:             }
                   2534:         }
                   2535:     }
                   2536:     return $totcodes;
                   2537: }
                   2538: 
1.1172.2.113  raeburn  2539: # --------------------------------------------- Get domain config for passwords
                   2540: 
                   2541: sub get_passwdconf {
                   2542:     my ($dom) = @_;
                   2543:     my (%passwdconf,$gotconf,$lookup);
                   2544:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2545:     if (defined($cached)) {
                   2546:         if (ref($result) eq 'HASH') {
                   2547:             %passwdconf = %{$result};
                   2548:             $gotconf = 1;
                   2549:         }
                   2550:     }
                   2551:     unless ($gotconf) {
                   2552:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2553:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2554:             %passwdconf = %{$domconfig{'passwords'}};
                   2555:         }
                   2556:         my $cachetime = 24*60*60;
                   2557:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2558:     }
                   2559:     return %passwdconf;
                   2560: }
                   2561: 
1.1172.2.118.  .1(raebu 2562:20): sub course_portal_url {
                   2563:20):     my ($cnum,$cdom) = @_;
                   2564:20):     my $chome = &homeserver($cnum,$cdom);
                   2565:20):     my $hostname = &hostname($chome);
                   2566:20):     my $protocol = $protocol{$chome};
                   2567:20):     $protocol = 'http' if ($protocol ne 'https');
                   2568:20):     my %domdefaults = &get_domain_defaults($cdom);
                   2569:20):     my $firsturl;
                   2570:20):     if ($domdefaults{'portal_def'}) {
                   2571:20):         $firsturl = $domdefaults{'portal_def'};
                   2572:20):     } else {
                   2573:20):         $firsturl = $protocol.'://'.$hostname;
                   2574:20):     }
                   2575:20):     return $firsturl;
                   2576:20): }
                   2577:20): 
1.344     www      2578: # --------------------------------------------------- Assign a key to a student
                   2579: 
                   2580: sub assign_access_key {
1.364     www      2581: #
                   2582: # a valid key looks like uname:udom#comments
                   2583: # comments are being appended
                   2584: #
1.498     www      2585:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2586:     $kdom=
1.620     albertel 2587:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2588:     $knum=
1.620     albertel 2589:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2590:     $cdom=
1.620     albertel 2591:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2592:     $cnum=
1.620     albertel 2593:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2594:     $udom=$env{'user.name'} unless (defined($udom));
                   2595:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2596:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2597:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2598:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2599:                                                   # assigned to this person
                   2600:                                                   # - this should not happen,
1.345     www      2601:                                                   # unless something went wrong
                   2602:                                                   # the first time around
                   2603: # ready to assign
1.364     www      2604:         $logentry=$1.'; '.$logentry;
1.496     www      2605:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2606:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2607: # key now belongs to user
1.346     www      2608: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2609:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2610:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2611:                 return 'ok';
                   2612:             } else {
                   2613:                 return 
                   2614:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2615: 	    }
                   2616:         } else {
                   2617:             return 'error: Could not assign key, try again later.';
                   2618:         }
1.364     www      2619:     } elsif (!$existing{$ckey}) {
1.345     www      2620: # the key does not exist
                   2621: 	return 'error: The key does not exist';
                   2622:     } else {
                   2623: # the key is somebody else's
                   2624: 	return 'error: The key is already in use';
                   2625:     }
1.344     www      2626: }
                   2627: 
1.364     www      2628: # ------------------------------------------ put an additional comment on a key
                   2629: 
                   2630: sub comment_access_key {
                   2631: #
                   2632: # a valid key looks like uname:udom#comments
                   2633: # comments are being appended
                   2634: #
                   2635:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2636:     $cdom=
1.620     albertel 2637:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2638:     $cnum=
1.620     albertel 2639:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2640:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2641:     if ($existing{$ckey}) {
                   2642:         $existing{$ckey}.='; '.$logentry;
                   2643: # ready to assign
1.367     www      2644:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2645:                                                  $cdom,$cnum) eq 'ok') {
                   2646: 	    return 'ok';
                   2647:         } else {
                   2648: 	    return 'error: Count not store comment.';
                   2649:         }
                   2650:     } else {
                   2651: # the key does not exist
                   2652: 	return 'error: The key does not exist';
                   2653:     }
                   2654: }
                   2655: 
1.344     www      2656: # ------------------------------------------------------ Generate a set of keys
                   2657: 
                   2658: sub generate_access_keys {
1.364     www      2659:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2660:     $cdom=
1.620     albertel 2661:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2662:     $cnum=
1.620     albertel 2663:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2664:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2665:     unless (($cdom) && ($cnum)) { return 0; }
                   2666:     if ($number>10000) { return 0; }
                   2667:     sleep(2); # make sure don't get same seed twice
                   2668:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2669:     my $total=0;
                   2670:     for (my $i=1;$i<=$number;$i++) {
                   2671:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2672:                   sprintf("%lx",int(100000*rand)).'-'.
                   2673:                   sprintf("%lx",int(100000*rand));
                   2674:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2675:        $newkey=~s/0/h/g; # and also 0 and O
                   2676:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2677:        if ($existing{$newkey}) {
                   2678:            $i--;
                   2679:        } else {
1.364     www      2680: 	  if (&put('accesskeys',
                   2681:               { $newkey => '# generated '.localtime().
1.620     albertel 2682:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2683:                            '; '.$logentry },
                   2684: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2685:               $total++;
                   2686: 	  }
                   2687:        }
                   2688:     }
1.620     albertel 2689:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2690:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2691:     return $total;
                   2692: }
                   2693: 
                   2694: # ------------------------------------------------------- Validate an accesskey
                   2695: 
                   2696: sub validate_access_key {
                   2697:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2698:     $cdom=
1.620     albertel 2699:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2700:     $cnum=
1.620     albertel 2701:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2702:     $udom=$env{'user.domain'} unless (defined($udom));
                   2703:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2704:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2705:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2706: }
                   2707: 
                   2708: # ------------------------------------- Find the section of student in a course
1.652     albertel 2709: sub devalidate_getsection_cache {
                   2710:     my ($udom,$unam,$courseid)=@_;
                   2711:     my $hashid="$udom:$unam:$courseid";
                   2712:     &devalidate_cache_new('getsection',$hashid);
                   2713: }
1.298     matthew  2714: 
1.815     albertel 2715: sub courseid_to_courseurl {
                   2716:     my ($courseid) = @_;
                   2717:     #already url style courseid
                   2718:     return $courseid if ($courseid =~ m{^/});
                   2719: 
                   2720:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2721: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2722: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2723: 	return "/$cdom/$cnum";
                   2724:     }
                   2725: 
                   2726:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2727:     if (exists($courseinfo{'num'})) {
                   2728: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2729:     }
                   2730: 
                   2731:     return undef;
                   2732: }
                   2733: 
1.298     matthew  2734: sub getsection {
                   2735:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2736:     my $cachetime=1800;
1.551     albertel 2737: 
                   2738:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2739:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2740:     if (defined($cached)) { return $result; }
                   2741: 
1.298     matthew  2742:     my %Pending; 
                   2743:     my %Expired;
                   2744:     #
                   2745:     # Each role can either have not started yet (pending), be active, 
                   2746:     #    or have expired.
                   2747:     #
                   2748:     # If there is an active role, we are done.
                   2749:     #
                   2750:     # If there is more than one role which has not started yet, 
                   2751:     #     choose the one which will start sooner
                   2752:     # If there is one role which has not started yet, return it.
                   2753:     #
                   2754:     # If there is more than one expired role, choose the one which ended last.
                   2755:     # If there is a role which has expired, return it.
                   2756:     #
1.815     albertel 2757:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2758:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2759:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2760:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2761:         my $section=$1;
                   2762:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2763:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2764:         my $now=time;
1.548     albertel 2765:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2766:             $Expired{$end}=$section;
                   2767:             next;
                   2768:         }
1.548     albertel 2769:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2770:             $Pending{$start}=$section;
                   2771:             next;
                   2772:         }
1.599     albertel 2773:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2774:     }
                   2775:     #
                   2776:     # Presumedly there will be few matching roles from the above
                   2777:     # loop and the sorting time will be negligible.
                   2778:     if (scalar(keys(%Pending))) {
                   2779:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2780:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2781:     } 
                   2782:     if (scalar(keys(%Expired))) {
                   2783:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2784:         my $time = pop(@sorted);
1.599     albertel 2785:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2786:     }
1.599     albertel 2787:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2788: }
1.70      www      2789: 
1.599     albertel 2790: sub save_cache {
                   2791:     &purge_remembered();
1.722     albertel 2792:     #&Apache::loncommon::validate_page();
1.620     albertel 2793:     undef(%env);
1.780     albertel 2794:     undef($env_loaded);
1.599     albertel 2795: }
1.452     albertel 2796: 
1.599     albertel 2797: my $to_remember=-1;
                   2798: my %remembered;
                   2799: my %accessed;
                   2800: my $kicks=0;
                   2801: my $hits=0;
1.849     albertel 2802: sub make_key {
                   2803:     my ($name,$id) = @_;
1.872     albertel 2804:     if (length($id) > 65 
                   2805: 	&& length(&escape($id)) > 200) {
                   2806: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2807:     }
1.849     albertel 2808:     return &escape($name.':'.$id);
                   2809: }
                   2810: 
1.599     albertel 2811: sub devalidate_cache_new {
                   2812:     my ($name,$id,$debug) = @_;
                   2813:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2814:     my $remembered_id=$name.':'.$id;
1.849     albertel 2815:     $id=&make_key($name,$id);
1.599     albertel 2816:     $memcache->delete($id);
1.1172.2.81  raeburn  2817:     delete($remembered{$remembered_id});
                   2818:     delete($accessed{$remembered_id});
1.599     albertel 2819: }
                   2820: 
                   2821: sub is_cached_new {
                   2822:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2823:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2824:                                      # keys in %remembered hash, which persists for
                   2825:                                      # duration of request (no restriction on key length).
                   2826:     if (exists($remembered{$remembered_id})) {
                   2827: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2828: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2829: 	$hits++;
1.1172.2.81  raeburn  2830: 	return ($remembered{$remembered_id},1);
1.599     albertel 2831:     }
1.1172.2.81  raeburn  2832:     $id=&make_key($name,$id);
1.599     albertel 2833:     my $value = $memcache->get($id);
                   2834:     if (!(defined($value))) {
                   2835: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2836: 	return (undef,undef);
1.416     albertel 2837:     }
1.599     albertel 2838:     if ($value eq '__undef__') {
                   2839: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2840: 	$value=undef;
                   2841:     }
1.1172.2.81  raeburn  2842:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2843:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2844:     return ($value,1);
                   2845: }
                   2846: 
                   2847: sub do_cache_new {
                   2848:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2849:     my $remembered_id=$name.':'.$id;
1.849     albertel 2850:     $id=&make_key($name,$id);
1.599     albertel 2851:     my $setvalue=$value;
                   2852:     if (!defined($setvalue)) {
                   2853: 	$setvalue='__undef__';
                   2854:     }
1.623     albertel 2855:     if (!defined($time) ) {
                   2856: 	$time=600;
                   2857:     }
1.599     albertel 2858:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2859:     my $result = $memcache->set($id,$setvalue,$time);
                   2860:     if (! $result) {
1.872     albertel 2861: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2862: 	$memcache->disconnect_all();
1.872     albertel 2863:     }
1.600     albertel 2864:     # need to make a copy of $value
1.1172.2.81  raeburn  2865:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2866:     return $value;
                   2867: }
                   2868: 
                   2869: sub make_room {
1.1172.2.81  raeburn  2870:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2871: 
1.1172.2.81  raeburn  2872:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2873:                                     : $value;
1.599     albertel 2874:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2875:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2876:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2877:     my $to_kick;
                   2878:     my $max_time=0;
                   2879:     foreach my $other (keys(%accessed)) {
                   2880: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2881: 	    $to_kick=$other;
                   2882: 	    $max_time=&tv_interval($accessed{$other});
                   2883: 	}
                   2884:     }
                   2885:     delete($remembered{$to_kick});
                   2886:     delete($accessed{$to_kick});
                   2887:     $kicks++;
                   2888:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2889:     return;
                   2890: }
                   2891: 
1.599     albertel 2892: sub purge_remembered {
1.604     albertel 2893:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2894:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2895:     undef(%remembered);
                   2896:     undef(%accessed);
1.428     albertel 2897: }
1.70      www      2898: # ------------------------------------- Read an entry from a user's environment
                   2899: 
                   2900: sub userenvironment {
                   2901:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2902:     my $items;
                   2903:     foreach my $item (@what) {
                   2904:         $items.=&escape($item).'&';
                   2905:     }
                   2906:     $items=~s/\&$//;
1.70      www      2907:     my %returnhash=();
1.1009    raeburn  2908:     my $uhome = &homeserver($unam,$udom);
                   2909:     unless ($uhome eq 'no_host') {
                   2910:         my @answer=split(/\&/, 
                   2911:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2912:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2913:             return %returnhash;
                   2914:         }
1.1009    raeburn  2915:         my $i;
                   2916:         for ($i=0;$i<=$#what;$i++) {
                   2917: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2918:         }
1.70      www      2919:     }
                   2920:     return %returnhash;
1.1       albertel 2921: }
                   2922: 
1.617     albertel 2923: # ---------------------------------------------------------- Get a studentphoto
                   2924: sub studentphoto {
                   2925:     my ($udom,$unam,$ext) = @_;
                   2926:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2927:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2928:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2929:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2930:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2931:             } else {
                   2932:                 my ($result,$perm_reqd)=
1.707     albertel 2933: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2934:                 if ($result eq 'ok') {
                   2935:                     if (!($perm_reqd eq 'yes')) {
                   2936:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2937:                     }
                   2938:                 }
                   2939:             }
                   2940:         }
                   2941:     } else {
                   2942:         my ($result,$perm_reqd) = 
1.707     albertel 2943: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2944:         if ($result eq 'ok') {
                   2945:             if (!($perm_reqd eq 'yes')) {
                   2946:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2947:             }
                   2948:         }
                   2949:     }
                   2950:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2951: }
                   2952: 
                   2953: sub retrievestudentphoto {
                   2954:     my ($udom,$unam,$ext,$type) = @_;
                   2955:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2956:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2957:     if ($ret eq 'ok') {
                   2958:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2959:         if ($type eq 'thumbnail') {
                   2960:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2961:         }
                   2962:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2963:         return $tokenurl;
                   2964:     } else {
                   2965:         if ($type eq 'thumbnail') {
                   2966:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2967:         } else { 
                   2968:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2969:         }
1.617     albertel 2970:     }
                   2971: }
                   2972: 
1.263     www      2973: # -------------------------------------------------------------------- New chat
                   2974: 
                   2975: sub chatsend {
1.724     raeburn  2976:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2977:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2978:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2979:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2980:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2981: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2982: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2983: }
                   2984: 
                   2985: # ------------------------------------------ Find current version of a resource
                   2986: 
                   2987: sub getversion {
                   2988:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2989:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2990:     return &currentversion(&filelocation('',$fname));
                   2991: }
                   2992: 
                   2993: sub currentversion {
                   2994:     my $fname=shift;
                   2995:     my $author=$fname;
                   2996:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2997:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2998:     my $home=&homeserver($uname,$udom);
1.292     www      2999:     if ($home eq 'no_host') { 
                   3000:         return -1; 
                   3001:     }
1.1112    www      3002:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3003:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3004: 	return -1;
                   3005:     }
1.1112    www      3006:     return $answer;
1.263     www      3007: }
                   3008: 
1.1111    www      3009: #
                   3010: # Return special version number of resource if set by override, empty otherwise
                   3011: #
                   3012: sub usedversion {
                   3013:     my $fname=shift;
                   3014:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3015:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3016:     if ($urlversion) { return $urlversion; }
                   3017:     return '';
                   3018: }
                   3019: 
1.1       albertel 3020: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3021: 
1.1       albertel 3022: sub subscribe {
                   3023:     my $fname=shift;
1.761     raeburn  3024:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3025:     $fname=~s/[\n\r]//g;
1.1       albertel 3026:     my $author=$fname;
                   3027:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3028:     my ($udom,$uname)=split(/\//,$author);
                   3029:     my $home=homeserver($uname,$udom);
1.335     albertel 3030:     if ($home eq 'no_host') {
                   3031:         return 'not_found';
1.1       albertel 3032:     }
                   3033:     my $answer=reply("sub:$fname",$home);
1.64      www      3034:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3035: 	$answer.=' by '.$home;
                   3036:     }
1.1       albertel 3037:     return $answer;
                   3038: }
                   3039:     
1.8       www      3040: # -------------------------------------------------------------- Replicate file
                   3041: 
                   3042: sub repcopy {
                   3043:     my $filename=shift;
1.23      www      3044:     $filename=~s/\/+/\//g;
1.1142    raeburn  3045:     my $londocroot = $perlvar{'lonDocRoot'};
                   3046:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3047:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3048:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3049: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3050: 	return &repcopy_userfile($filename);
                   3051:     }
1.532     albertel 3052:     $filename=~s/[\n\r]//g;
1.8       www      3053:     my $transname="$filename.in.transfer";
1.828     www      3054: # FIXME: this should flock
1.607     raeburn  3055:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3056:     my $remoteurl=subscribe($filename);
1.64      www      3057:     if ($remoteurl =~ /^con_lost by/) {
                   3058: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3059:            return 'unavailable';
1.8       www      3060:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3061: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3062: 	   return 'not_found';
1.64      www      3063:     } elsif ($remoteurl =~ /^rejected by/) {
                   3064: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3065:            return 'forbidden';
1.20      www      3066:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3067:            return 'ok';
1.8       www      3068:     } else {
1.290     www      3069:         my $author=$filename;
                   3070:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3071:         my ($udom,$uname)=split(/\//,$author);
                   3072:         my $home=homeserver($uname,$udom);
                   3073:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3074:            my @parts=split(/\//,$filename);
                   3075:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3076:            if ($path ne "$londocroot/res") {
1.8       www      3077:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3078: 	       return 'bad_request';
1.8       www      3079:            }
                   3080:            my $count;
                   3081:            for ($count=5;$count<$#parts;$count++) {
                   3082:                $path.="/$parts[$count]";
                   3083:                if ((-e $path)!=1) {
                   3084: 		   mkdir($path,0777);
                   3085:                }
                   3086:            }
                   3087:            my $ua=new LWP::UserAgent;
                   3088:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3089:            my $response=$ua->request($request,$transname);
                   3090:            if ($response->is_error()) {
                   3091: 	       unlink($transname);
                   3092:                my $message=$response->status_line;
1.672     albertel 3093:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3094:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3095:                return 'unavailable';
1.8       www      3096:            } else {
1.16      www      3097: 	       if ($remoteurl!~/\.meta$/) {
                   3098:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3099:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3100:                   if ($mresponse->is_error()) {
                   3101: 		      unlink($filename.'.meta');
                   3102:                       &logthis(
1.672     albertel 3103:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3104:                   }
                   3105: 	       }
1.8       www      3106:                rename($transname,$filename);
1.607     raeburn  3107:                return 'ok';
1.8       www      3108:            }
1.290     www      3109:        }
1.8       www      3110:     }
1.330     www      3111: }
                   3112: 
1.1172.2.118.  .5(raebu 3113:20): # ------------------------------------------------- Unsubscribe from a resource
                   3114:20): 
                   3115:20): sub unsubscribe {
                   3116:20):     my ($fname) = @_;
                   3117:20):     my $answer;
                   3118:20):     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3119:20):     $fname=~s/[\n\r]//g;
                   3120:20):     my $author=$fname;
                   3121:20):     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3122:20):     my ($udom,$uname)=split(/\//,$author);
                   3123:20):     my $home=homeserver($uname,$udom);
                   3124:20):     if ($home eq 'no_host') {
                   3125:20):         $answer = 'no_host';
                   3126:20):     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3127:20):         $answer = 'home';
                   3128:20):     } else {
          .7(raebu 3129:20):         $answer = reply("unsub:$fname",$home);
          .5(raebu 3130:20):     }
                   3131:20):     return $answer;
                   3132:20): }
                   3133:20): 
1.330     www      3134: # ------------------------------------------------ Get server side include body
                   3135: sub ssi_body {
1.381     albertel 3136:     my ($filelink,%form)=@_;
1.606     matthew  3137:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3138:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3139:     }
1.953     www      3140:     my $output='';
                   3141:     my $response;
1.980     raeburn  3142:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3143:        ($output,$response)=&externalssi($filelink);
1.953     www      3144:     } else {
1.1004    droeschl 3145:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3146:        $filelink .= 'inhibitmenu=yes';
1.953     www      3147:        ($output,$response)=&ssi($filelink,%form);
                   3148:     }
1.778     albertel 3149:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3150:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3151:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3152:     if (wantarray) {
                   3153:         return ($output, $response);
                   3154:     } else {
                   3155:         return $output;
                   3156:     }
1.8       www      3157: }
                   3158: 
1.15      www      3159: # --------------------------------------------------------- Server Side Include
                   3160: 
1.782     albertel 3161: sub absolute_url {
                   3162:     my ($host_name) = @_;
                   3163:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3164:     if ($host_name eq '') {
                   3165: 	$host_name = $ENV{'SERVER_NAME'};
                   3166:     }
                   3167:     return $protocol.$host_name;
                   3168: }
                   3169: 
1.942     foxr     3170: #
                   3171: #   Server side include.
                   3172: # Parameters:
                   3173: #  fn     Possibly encrypted resource name/id.
                   3174: #  form   Hash that describes how the rendering should be done
                   3175: #         and other things.
1.944     foxr     3176: # Returns:
1.950     raeburn  3177: #   Scalar context: The content of the response.
                   3178: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3179: #     
1.15      www      3180: sub ssi {
                   3181: 
1.944     foxr     3182:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3183:     my ($request,$response);
1.711     albertel 3184: 
                   3185:     $form{'no_update_last_known'}=1;
1.895     albertel 3186:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3187:     if (%form) {
1.782     albertel 3188:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3189:       $request->content(join('&',map {
                   3190:             my $name = escape($_);
                   3191:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3192:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3193:             : &escape($form{$_}) );
                   3194:         } keys(%form)));
1.23      www      3195:     } else {
1.782     albertel 3196:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3197:     }
                   3198: 
1.15      www      3199:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3200: 
1.1172.2.101  raeburn  3201:     if (($env{'request.course.id'}) &&
                   3202:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3203:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3204:         ($form{'grade_symb'} ne '') &&
                   3205:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3206:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3207:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3208:             my $ua=new LWP::UserAgent;
                   3209:             $ua->local_address('127.0.0.1');
                   3210:             $response = $ua->request($request);
                   3211:         } else {
                   3212:             {
                   3213:                 require LWP::Protocol::http;
                   3214:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3215:                 my $ua=new LWP::UserAgent;
                   3216:                 $response = $ua->request($request);
                   3217:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3218:             }
                   3219:         }
                   3220:     } else {
                   3221:         my $ua=new LWP::UserAgent;
                   3222:         $response = $ua->request($request);
                   3223:     }
1.944     foxr     3224:     if (wantarray) {
1.1172.2.3  raeburn  3225: 	return ($response->content, $response);
1.944     foxr     3226:     } else {
1.1172.2.3  raeburn  3227: 	return $response->content;
1.942     foxr     3228:     }
1.324     www      3229: }
                   3230: 
                   3231: sub externalssi {
                   3232:     my ($url)=@_;
                   3233:     my $ua=new LWP::UserAgent;
                   3234:     my $request=new HTTP::Request('GET',$url);
                   3235:     my $response=$ua->request($request);
1.954     raeburn  3236:     if (wantarray) {
                   3237:         return ($response->content, $response);
                   3238:     } else {
                   3239:         return $response->content;
                   3240:     }
1.15      www      3241: }
1.254     www      3242: 
1.1172.2.98  raeburn  3243: # If the local copy of a replicated resource is outdated, trigger a
                   3244: # connection from the homeserver to flush the delayed queue. If no update
                   3245: # happens, remove local copies of outdated resource (and corresponding
                   3246: # metadata file).
                   3247: 
                   3248: sub remove_stale_resfile {
                   3249:     my ($url) = @_;
                   3250:     my $removed;
                   3251:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3252:         my $audom = $1;
                   3253:         my $auname = $2;
                   3254:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3255:             my $homeserver = &homeserver($auname,$audom);
                   3256:             unless (($homeserver eq 'no_host') ||
                   3257:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3258:                 my $fname = &filelocation('',$url);
                   3259:                 if (-e $fname) {
                   3260:                     my $hostname = &hostname($homeserver);
                   3261:                     if ($hostname) {
1.1172.2.118.  .3(raebu 3262:20):                         my $protocol = $protocol{$homeserver};
                   3263:20):                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3264:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.118.  .3(raebu 3265:20):                         my $ua=new LWP::UserAgent;
                   3266:20):                         $ua->timeout(5);
1.1172.2.98  raeburn  3267:                         my $request=new HTTP::Request('HEAD',$uri);
                   3268:                         my $response=$ua->request($request);
                   3269:                         if ($response->is_success()) {
                   3270:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3271:                             my $locmodtime = (stat($fname))[9];
                   3272:                             if ($locmodtime < $remmodtime) {
                   3273:                                 my $stale;
                   3274:                                 my $answer = &reply('pong',$homeserver);
                   3275:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3276:                                     sleep(0.2);
                   3277:                                     $locmodtime = (stat($fname))[9];
                   3278:                                     if ($locmodtime < $remmodtime) {
                   3279:                                         my $posstransfer = $fname.'.in.transfer';
                   3280:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3281:                                             $removed = 1;
                   3282:                                         } else {
                   3283:                                             $stale = 1;
                   3284:                                         }
                   3285:                                     } else {
                   3286:                                         $removed = 1;
                   3287:                                     }
                   3288:                                 } else {
                   3289:                                     $stale = 1;
                   3290:                                 }
                   3291:                                 if ($stale) {
1.1172.2.118.  .5(raebu 3292:20):                                     if (unlink($fname)) {
                   3293:20):                                         if ($uri!~/\.meta$/) {
                   3294:20):                                             if (-e $fname.'.meta') {
                   3295:20):                                                 unlink($fname.'.meta');
                   3296:20):                                             }
                   3297:20):                                         }
                   3298:20):                                         my $unsubresult = &unsubscribe($fname);
                   3299:20):                                         unless ($unsubresult eq 'ok') {
                   3300:20):                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3301:20):                                         }
                   3302:20):                                         $removed = 1;
1.1172.2.98  raeburn  3303:                                     }
                   3304:                                 }
                   3305:                             }
                   3306:                         }
                   3307:                     }
                   3308:                 }
                   3309:             }
                   3310:         }
                   3311:     }
                   3312:     return $removed;
                   3313: }
                   3314: 
1.492     albertel 3315: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3316: 
                   3317: sub allowuploaded {
                   3318:     my ($srcurl,$url)=@_;
                   3319:     $url=&clutter(&declutter($url));
                   3320:     my $dir=$url;
                   3321:     $dir=~s/\/[^\/]+$//;
                   3322:     my %httpref=();
                   3323:     my $httpurl=&hreflocation('',$url);
                   3324:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3325:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3326: }
1.477     raeburn  3327: 
1.1172.2.13  raeburn  3328: #
                   3329: # Determine if the current user should be able to edit a particular resource,
                   3330: # when viewing in course context.
                   3331: # (a) When viewing resource used to determine if "Edit" item is included in
                   3332: #     Functions.
                   3333: # (b) When displaying folder contents in course editor, used to determine if
                   3334: #     "Edit" link will be displayed alongside resource.
                   3335: #
                   3336: #  input: six args -- filename (decluttered), course number, course domain,
                   3337: #                   url, symb (if registered) and group (if this is a group
                   3338: #                   item -- e.g., bulletin board, group page etc.).
                   3339: #  output: array of five scalars --
                   3340: #          $cfile -- url for file editing if editable on current server
                   3341: #          $home -- homeserver of resource (i.e., for author if published,
                   3342: #                                           or course if uploaded.).
                   3343: #          $switchserver --  1 if server switch will be needed.
                   3344: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3345: #          $forceview -- 1 if icon/link should be to go to view mode
                   3346: #
                   3347: 
                   3348: sub can_edit_resource {
                   3349:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3350:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3351: #
                   3352: # For aboutme pages user can only edit his/her own.
                   3353: #
                   3354:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3355:         my ($sdom,$sname) = ($1,$2);
                   3356:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3357:             $home = $env{'user.home'};
                   3358:             $cfile = $resurl;
                   3359:             if ($env{'form.forceedit'}) {
                   3360:                 $forceview = 1;
                   3361:             } else {
                   3362:                 $forceedit = 1;
                   3363:             }
                   3364:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3365:         } else {
                   3366:             return;
                   3367:         }
                   3368:     }
                   3369: 
                   3370:     if ($env{'request.course.id'}) {
                   3371:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3372:         if ($group ne '') {
                   3373: # if this is a group homepage or group bulletin board, check group privs
                   3374:             my $allowed = 0;
                   3375:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3376:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3377:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3378:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3379:                     $allowed = 1;
                   3380:                 }
                   3381:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3382:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3383:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3384:                     $allowed = 1;
                   3385:                 }
                   3386:             }
                   3387:             if ($allowed) {
                   3388:                 $home=&homeserver($cnum,$cdom);
                   3389:                 if ($env{'form.forceedit'}) {
                   3390:                     $forceview = 1;
                   3391:                 } else {
                   3392:                     $forceedit = 1;
                   3393:                 }
                   3394:                 $cfile = $resurl;
                   3395:             } else {
                   3396:                 return;
                   3397:             }
                   3398:         } else {
1.1172.2.15  raeburn  3399:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3400:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3401:                     return;
                   3402:                 }
                   3403:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3404: #
                   3405: # No edit allowed where CC has switched to student role.
                   3406: #
                   3407:                 return;
                   3408:             }
                   3409:         }
                   3410:     }
                   3411: 
                   3412:     if ($file ne '') {
                   3413:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3414:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3415:                 $uploaded = 1;
                   3416:                 $incourse = 1;
                   3417:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3418:                     $cfile = &hreflocation('',$file);
                   3419:                     if ($env{'form.forceedit'}) {
                   3420:                         $forceview = 1;
                   3421:                     } else {
                   3422:                         $forceedit = 1;
                   3423:                     }
                   3424:                 }
                   3425:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3426:                 $incourse = 1;
                   3427:                 if ($env{'form.forceedit'}) {
                   3428:                     $forceview = 1;
                   3429:                 } else {
                   3430:                     $forceedit = 1;
                   3431:                 }
                   3432:                 $cfile = $resurl;
                   3433:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3434:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3435:                     $incourse = 1;
                   3436:                     if ($env{'form.forceedit'}) {
                   3437:                         $forceview = 1;
                   3438:                     } else {
                   3439:                         $forceedit = 1;
                   3440:                     }
                   3441:                     $cfile = $resurl;
                   3442:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3443:                     $incourse = 1;
                   3444:                     $cfile = $resurl.'/smpedit';
                   3445:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3446:                     $incourse = 1;
                   3447:                     if ($env{'form.forceedit'}) {
                   3448:                         $forceview = 1;
                   3449:                     } else {
                   3450:                         $forceedit = 1;
                   3451:                     }
                   3452:                     $cfile = $resurl;
1.1172.2.118.  .5(raebu 3453:20):                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3454:20):                     my ($map,$id,$res) = &decode_symb($symb);
                   3455:20):                     if ($map =~ /\.page$/) {
                   3456:20):                         $incourse = 1;
                   3457:20):                         if ($env{'form.forceedit'}) {
                   3458:20):                             $forceview = 1;
                   3459:20):                             $cfile = $map;
                   3460:20):                         } else {
                   3461:20):                             $forceedit = 1;
                   3462:20):                             $cfile =  '/adm/wrapper'.$resurl;
                   3463:20):                         }
                   3464:20):                     }
          .1(raebu 3465:20):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3466:20):                     $incourse = 1;
                   3467:20):                     if ($env{'form.forceedit'}) {
                   3468:20):                         $forceview = 1;
                   3469:20):                     } else {
                   3470:20):                         $forceedit = 1;
                   3471:20):                     }
                   3472:20):                     $cfile = $resurl;
1.1172.2.15  raeburn  3473:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3474:                     $incourse = 1;
                   3475:                     if ($env{'form.forceedit'}) {
                   3476:                         $forceview = 1;
                   3477:                     } else {
                   3478:                         $forceedit = 1;
                   3479:                     }
                   3480:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3481:                 }
                   3482:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3483:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3484:                 if (&is_on_map($template)) {
                   3485:                     $incourse = 1;
                   3486:                     $forceview = 1;
                   3487:                     $cfile = $template;
                   3488:                 }
                   3489:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3490:                 $incourse = 1;
                   3491:                 if ($env{'form.forceedit'}) {
                   3492:                     $forceview = 1;
                   3493:                 } else {
                   3494:                     $forceedit = 1;
                   3495:                 }
                   3496:                 $cfile = $resurl;
1.1172.2.118.  .1(raebu 3497:20):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3498:20):                 $incourse = 1;
                   3499:20):                 if ($env{'form.forceedit'}) {
                   3500:20):                     $forceview = 1;
                   3501:20):                 } else {
                   3502:20):                     $forceedit = 1;
                   3503:20):                 }
                   3504:20):                 $cfile = $resurl;
1.1172.2.13  raeburn  3505:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3506:                 $incourse = 1;
                   3507:                 $forceview = 1;
                   3508:                 if ($symb) {
                   3509:                     my ($map,$id,$res)=&decode_symb($symb);
                   3510:                     $env{'request.symb'} = $symb;
                   3511:                     $cfile = &clutter($res);
                   3512:                 } else {
                   3513:                     $cfile = $env{'form.suppurl'};
1.1172.2.118.  .1(raebu 3514:20):                     my $escfile = &unescape($cfile);
                   3515:20):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3516:20):                         $cfile = '/adm/wrapper'.$escfile;
                   3517:20):                     } else {
                   3518:20):                         $escfile =~ s{^http://}{};
                   3519:20):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3520:20):                     }
1.1172.2.13  raeburn  3521:                 }
1.1172.2.31  raeburn  3522:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3523:                 if ($env{'form.forceedit'}) {
                   3524:                     $forceview = 1;
                   3525:                 } else {
                   3526:                     $forceedit = 1;
                   3527:                 }
                   3528:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3529:             }
                   3530:         }
                   3531:         if ($uploaded || $incourse) {
                   3532:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3533:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3534:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3535:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3536:             # Check that the user has permission to edit this resource
                   3537:             my $setpriv = 1;
                   3538:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3539:             if (defined($cfudom)) {
                   3540:                 $home=&homeserver($cfuname,$cfudom);
                   3541:                 $cfile=$file;
                   3542:             }
                   3543:         }
                   3544:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3545:             (($home ne '') && ($home ne 'no_host'))) {
                   3546:             my @ids=&current_machine_ids();
                   3547:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3548:                 $switchserver=1;
                   3549:             }
                   3550:         }
                   3551:     }
                   3552:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3553: }
                   3554: 
                   3555: sub is_course_upload {
                   3556:     my ($file,$cnum,$cdom) = @_;
                   3557:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3558:     $uploadpath =~ s{^\/}{};
                   3559:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3560:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3561:         return 1;
                   3562:     }
                   3563:     return;
                   3564: }
                   3565: 
                   3566: sub in_course {
                   3567:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3568:     if ($hideprivileged) {
                   3569:         my $skipuser;
1.1172.2.23  raeburn  3570:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3571:         my @possdoms = ($cdom);
                   3572:         if ($coursehash{'checkforpriv'}) {
                   3573:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3574:         }
                   3575:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3576:             $skipuser = 1;
                   3577:             if ($coursehash{'nothideprivileged'}) {
                   3578:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3579:                     my $user;
                   3580:                     if ($item =~ /:/) {
                   3581:                         $user = $item;
                   3582:                     } else {
                   3583:                         $user = join(':',split(/[\@]/,$item));
                   3584:                     }
                   3585:                     if ($user eq $uname.':'.$udom) {
                   3586:                         undef($skipuser);
                   3587:                         last;
                   3588:                     }
                   3589:                 }
                   3590:             }
                   3591:             if ($skipuser) {
                   3592:                 return 0;
                   3593:             }
                   3594:         }
                   3595:     }
                   3596:     $type ||= 'any';
                   3597:     if (!defined($cdom) || !defined($cnum)) {
                   3598:         my $cid  = $env{'request.course.id'};
                   3599:         $cdom = $env{'course.'.$cid.'.domain'};
                   3600:         $cnum = $env{'course.'.$cid.'.num'};
                   3601:     }
                   3602:     my $typesref;
                   3603:     if (($type eq 'any') || ($type eq 'all')) {
                   3604:         $typesref = ['active','previous','future'];
                   3605:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3606:         $typesref = [$type];
                   3607:     }
                   3608:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3609:                               $typesref,undef,[$cdom]);
                   3610:     my ($tmp) = keys(%roles);
                   3611:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3612:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3613:     if (@course_roles > 0) {
                   3614:         return 1;
                   3615:     }
                   3616:     return 0;
                   3617: }
                   3618: 
1.478     albertel 3619: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3620: # input: action, courseID, current domain, intended
1.637     raeburn  3621: #        path to file, source of file, instruction to parse file for objects,
                   3622: #        ref to hash for embedded objects,
                   3623: #        ref to hash for codebase of java objects.
1.1095    raeburn  3624: #        reference to scalar to accommodate mime type determined
                   3625: #          from File::MMagic if $parser = parse.
1.637     raeburn  3626: #
1.485     raeburn  3627: # output: url to file (if action was uploaddoc), 
                   3628: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3629: #
1.478     albertel 3630: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3631: # course.
1.477     raeburn  3632: #
1.478     albertel 3633: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3634: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3635: #          course's home server.
1.477     raeburn  3636: #
1.478     albertel 3637: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3638: #          be copied from $source (current location) to 
                   3639: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3640: #         and will then be copied to
                   3641: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3642: #         course's home server.
1.485     raeburn  3643: #
1.481     raeburn  3644: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3645: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3646: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3647: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3648: #         in course's home server.
1.637     raeburn  3649: #
1.477     raeburn  3650: 
                   3651: sub process_coursefile {
1.1095    raeburn  3652:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3653:         $mimetype)=@_;
1.477     raeburn  3654:     my $fetchresult;
1.638     albertel 3655:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3656:     if ($action eq 'propagate') {
1.638     albertel 3657:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3658: 			     $home);
1.481     raeburn  3659:     } else {
1.477     raeburn  3660:         my $fpath = '';
                   3661:         my $fname = $file;
1.478     albertel 3662:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3663:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3664:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3665:         if ($action eq 'copy') {
                   3666:             if ($source eq '') {
                   3667:                 $fetchresult = 'no source file';
                   3668:                 return $fetchresult;
                   3669:             } else {
                   3670:                 my $destination = $filepath.'/'.$fname;
                   3671:                 rename($source,$destination);
                   3672:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3673:                                  $home);
1.481     raeburn  3674:             }
                   3675:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3676:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3677:             print $fh $env{'form.'.$source};
1.481     raeburn  3678:             close($fh);
1.637     raeburn  3679:             if ($parser eq 'parse') {
1.1024    raeburn  3680:                 my $mm = new File::MMagic;
1.1095    raeburn  3681:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3682:                 if ($type eq 'text/html') {
1.1024    raeburn  3683:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3684:                     unless ($parse_result eq 'ok') {
                   3685:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3686:                     }
1.637     raeburn  3687:                 }
1.1095    raeburn  3688:                 if (ref($mimetype)) {
                   3689:                     $$mimetype = $type;
                   3690:                 } 
1.637     raeburn  3691:             }
1.477     raeburn  3692:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3693:                                  $home);
1.481     raeburn  3694:             if ($fetchresult eq 'ok') {
                   3695:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3696:             } else {
                   3697:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3698:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3699:                 return '/adm/notfound.html';
                   3700:             }
1.477     raeburn  3701:         }
                   3702:     }
1.485     raeburn  3703:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3704:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3705:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3706:     }
                   3707:     return $fetchresult;
                   3708: }
                   3709: 
1.637     raeburn  3710: sub build_filepath {
                   3711:     my ($fpath) = @_;
                   3712:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3713:     unless ($fpath eq '') {
                   3714:         my @parts=split('/',$fpath);
                   3715:         foreach my $part (@parts) {
                   3716:             $filepath.= '/'.$part;
                   3717:             if ((-e $filepath)!=1) {
                   3718:                 mkdir($filepath,0777);
                   3719:             }
                   3720:         }
                   3721:     }
                   3722:     return $filepath;
                   3723: }
                   3724: 
                   3725: sub store_edited_file {
1.638     albertel 3726:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3727:     my $file = $primary_url;
                   3728:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3729:     my $fpath = '';
                   3730:     my $fname = $file;
                   3731:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3732:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3733:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3734:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3735:     print $fh $content;
                   3736:     close($fh);
1.638     albertel 3737:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3738:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3739: 			  $home);
1.637     raeburn  3740:     if ($$fetchresult eq 'ok') {
                   3741:         return '/uploaded/'.$fpath.'/'.$fname;
                   3742:     } else {
1.638     albertel 3743:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3744: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3745:         return '/adm/notfound.html';
                   3746:     }
                   3747: }
                   3748: 
1.531     albertel 3749: sub clean_filename {
1.831     albertel 3750:     my ($fname,$args)=@_;
1.315     www      3751: # Replace Windows backslashes by forward slashes
1.257     www      3752:     $fname=~s/\\/\//g;
1.831     albertel 3753:     if (!$args->{'keep_path'}) {
                   3754:         # Get rid of everything but the actual filename
                   3755: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3756:     }
1.315     www      3757: # Replace spaces by underscores
                   3758:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3759: # Transliterate non-ascii text to ascii
                   3760:     my $lang = &Apache::lonlocal::current_language();
                   3761:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3762: # Replace all other weird characters by nothing
1.831     albertel 3763:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3764: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3765: # numbers
                   3766:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3767:     return $fname;
                   3768: }
1.1172.2.110  raeburn  3769: 
1.1051    raeburn  3770: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3771: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3772: # image with the same aspect ratio as the original, but with dimensions which do 
                   3773: # not exceed $resizewidth and $resizeheight.
                   3774:  
1.984     neumanie 3775: sub resizeImage {
1.1051    raeburn  3776:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3777:     my $ima = Image::Magick->new;
                   3778:     my $resized;
                   3779:     if (-e $img_path) {
                   3780:         $ima->Read($img_path);
                   3781:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3782:             my $width = $ima->Get('width');
                   3783:             my $height = $ima->Get('height');
                   3784:             if ($width > $resizewidth) {
                   3785: 	        my $factor = $width/$resizewidth;
                   3786:                 my $newheight = $height/$factor;
                   3787:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3788:                 $resized = 1;
                   3789:             }
                   3790:         }
                   3791:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3792:             my $width = $ima->Get('width');
                   3793:             my $height = $ima->Get('height');
                   3794:             if ($height > $resizeheight) {
                   3795:                 my $factor = $height/$resizeheight;
                   3796:                 my $newwidth = $width/$factor;
                   3797:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3798:                 $resized = 1;
                   3799:             }
                   3800:         }
                   3801:         if ($resized) {
                   3802:             $ima->Write($img_path);
                   3803:         }
                   3804:     }
                   3805:     return;
1.977     amueller 3806: }
                   3807: 
1.608     albertel 3808: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3809: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3810: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3811: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3812: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3813: #                   if 'coursedoc': upload to the current course
                   3814: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3815: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3816: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3817: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3818: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3819: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3820: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3821: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3822: #        $allfiles - reference to hash for embedded objects
                   3823: #        $codebase - reference to hash for codebase of java objects
                   3824: #        $desuname - username for permanent storage of uploaded file
                   3825: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3826: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3827: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3828: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3829: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3830: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3831: #                    from File::MMagic.
1.858     raeburn  3832: # 
1.686     albertel 3833: # output: url of file in userspace, or error: <message> 
                   3834: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3835: 
1.531     albertel 3836: sub userfileupload {
1.1090    raeburn  3837:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3838:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3839:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3840:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3841:     $fname=&clean_filename($fname);
1.1090    raeburn  3842:     # See if there is anything left
1.257     www      3843:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3844:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3845:     if ($fname =~ /^\./) {
                   3846:         my ($s,$usec) = &gettimeofday();
                   3847:         while (length($usec) < 6) {
                   3848:             $usec = '0'.$usec;
                   3849:         }
                   3850:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3851:     }
1.1090    raeburn  3852:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3853:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3854:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3855:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3856:         my $now = time;
1.1090    raeburn  3857:         my $filepath;
1.1095    raeburn  3858:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3859:              $filepath = 'tmp/helprequests/'.$now;
                   3860:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3861:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3862:                          '_'.$env{'user.domain'}.'/pending';
                   3863:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3864:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3865:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3866:                 $docudom = $destudom;
                   3867:             } else {
                   3868:                 $docudom = $env{'user.domain'};
                   3869:             }
1.1172.2.96  raeburn  3870:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3871:                 $docuname = $destuname;
                   3872:             } else {
                   3873:                 $docuname = $env{'user.name'};
                   3874:             }
                   3875:             if (exists($env{'form.group'})) {
                   3876:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3877:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3878:             }
                   3879:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3880:             if ($context eq 'canceloverwrite') {
                   3881:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3882:                 if (-e  $tempfile) {
                   3883:                     my @info = stat($tempfile);
                   3884:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3885:                         unlink($tempfile);
                   3886:                     }
                   3887:                 }
                   3888:                 return;
1.523     raeburn  3889:             }
                   3890:         }
1.1090    raeburn  3891:         # Create the directory if not present
1.741     raeburn  3892:         my @parts=split(/\//,$filepath);
                   3893:         my $fullpath = $perlvar{'lonDaemons'};
                   3894:         for (my $i=0;$i<@parts;$i++) {
                   3895:             $fullpath .= '/'.$parts[$i];
                   3896:             if ((-e $fullpath)!=1) {
                   3897:                 mkdir($fullpath,0777);
                   3898:             }
                   3899:         }
1.1172.2.96  raeburn  3900:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3901:         print $fh $env{'form.'.$formname};
                   3902:         close($fh);
1.1090    raeburn  3903:         if ($context eq 'existingfile') {
                   3904:             my @info = stat($fullpath.'/'.$fname);
                   3905:             return ($fullpath.'/'.$fname,$info[9]);
                   3906:         } else {
                   3907:             return $fullpath.'/'.$fname;
                   3908:         }
1.523     raeburn  3909:     }
1.995     raeburn  3910:     if ($subdir eq 'scantron') {
                   3911:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3912:     } else {
1.995     raeburn  3913:         $fname="$subdir/$fname";
                   3914:     }
1.1090    raeburn  3915:     if ($context eq 'coursedoc') {
1.638     albertel 3916: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3917: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3918:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3919:             return &finishuserfileupload($docuname,$docudom,
                   3920: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3921: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3922:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3923:         } else {
1.1172.2.21  raeburn  3924:             if ($env{'form.folder'}) {
                   3925:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3926:             }
1.638     albertel 3927:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3928: 				       $fname,$formname,$parser,
1.1095    raeburn  3929: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3930:         }
1.719     banghart 3931:     } elsif (defined($destuname)) {
                   3932:         my $docuname=$destuname;
                   3933:         my $docudom=$destudom;
1.860     raeburn  3934: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3935: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3936:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3937:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3938:     } else {
1.638     albertel 3939:         my $docuname=$env{'user.name'};
                   3940:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3941:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3942:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3943:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3944:         }
1.860     raeburn  3945: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3946: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3947:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3948:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3949:     }
1.271     www      3950: }
                   3951: 
                   3952: sub finishuserfileupload {
1.860     raeburn  3953:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3954:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3955:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3956:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3957:   
1.860     raeburn  3958:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3959:     $file=$fname;
                   3960:     if ($fname=~m|/|) {
                   3961:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3962: 	$path.=$fnamepath.'/';
                   3963:     }
1.259     www      3964:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3965:     my $count;
                   3966:     for ($count=4;$count<=$#parts;$count++) {
                   3967:         $filepath.="/$parts[$count]";
                   3968:         if ((-e $filepath)!=1) {
                   3969: 	    mkdir($filepath,0777);
                   3970:         }
                   3971:     }
1.984     neumanie 3972: 
1.258     www      3973: # Save the file
                   3974:     {
1.1172.2.96  raeburn  3975: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3976: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3977: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3978: 	    return '/adm/notfound.html';
                   3979: 	}
1.1090    raeburn  3980:         if ($context eq 'overwrite') {
1.1117    foxr     3981:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3982:             my $target = $filepath.'/'.$file;
                   3983:             if (-e $source) {
                   3984:                 my @info = stat($source);
                   3985:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3986:                     unless (&File::Copy::move($source,$target)) {
                   3987:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3988:                         return "Moving from $source failed";
                   3989:                     }
                   3990:                 } else {
                   3991:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3992:                 }
                   3993:             } else {
                   3994:                 return "Temporary file: $source missing";
                   3995:             }
                   3996:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3997: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3998: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3999: 	    return '/adm/notfound.html';
                   4000: 	}
1.570     albertel 4001: 	close(FH);
1.1051    raeburn  4002:         if ($resizewidth && $resizeheight) {
                   4003:             my $mm = new File::MMagic;
                   4004:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4005:             if ($mime_type =~ m{^image/}) {
                   4006: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4007:             }  
1.977     amueller 4008: 	}
1.258     www      4009:     }
1.1152    raeburn  4010:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4011:         if (ref($mimetype)) {
                   4012:             if ($$mimetype eq '') {
                   4013:                 my $mm = new File::MMagic;
                   4014:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4015:                 $$mimetype = $type;
                   4016:             }
                   4017:         }
                   4018:     }
1.1172.2.109  raeburn  4019:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4020:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4021:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4022:                                                        $allfiles,$codebase);
                   4023:             unless ($parse_result eq 'ok') {
                   4024:                 &logthis('Failed to parse '.$filepath.$file.
                   4025: 	   	         ' for embedded media: '.$parse_result); 
                   4026:             }
1.637     raeburn  4027:         }
1.1172.2.109  raeburn  4028:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4029:         my $format = $env{'form.scantron_format'};
                   4030:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4031:     }
1.860     raeburn  4032:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4033:         my $input = $filepath.'/'.$file;
                   4034:         my $output = $filepath.'/'.'tn-'.$file;
                   4035:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4036:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4037:         system({$args[0]} @args);
1.860     raeburn  4038:         if (-e $filepath.'/'.'tn-'.$file) {
                   4039:             $fetchthumb  = 1; 
                   4040:         }
                   4041:     }
1.858     raeburn  4042:  
1.259     www      4043: # Notify homeserver to grep it
                   4044: #
1.984     neumanie 4045:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4046:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4047:     if ($fetchresult eq 'ok') {
1.860     raeburn  4048:         if ($fetchthumb) {
                   4049:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4050:             if ($thumbresult ne 'ok') {
                   4051:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4052:                          $docuhome.': '.$thumbresult);
                   4053:             }
                   4054:         }
1.259     www      4055: #
1.258     www      4056: # Return the URL to it
1.494     albertel 4057:         return '/uploaded/'.$path.$file;
1.263     www      4058:     } else {
1.494     albertel 4059:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4060: 		 ': '.$fetchresult);
1.263     www      4061:         return '/adm/notfound.html';
1.858     raeburn  4062:     }
1.493     albertel 4063: }
                   4064: 
1.637     raeburn  4065: sub extract_embedded_items {
1.961     raeburn  4066:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4067:     my @state = ();
1.1164    raeburn  4068:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4069:     my %javafiles = (
                   4070:                       codebase => '',
                   4071:                       code => '',
                   4072:                       archive => ''
                   4073:                     );
                   4074:     my %mediafiles = (
                   4075:                       src => '',
                   4076:                       movie => '',
                   4077:                      );
1.648     raeburn  4078:     my $p;
                   4079:     if ($content) {
                   4080:         $p = HTML::LCParser->new($content);
                   4081:     } else {
1.961     raeburn  4082:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4083:     }
1.641     albertel 4084:     while (my $t=$p->get_token()) {
1.640     albertel 4085: 	if ($t->[0] eq 'S') {
                   4086: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4087: 	    push(@state, $tagname);
1.648     raeburn  4088:             if (lc($tagname) eq 'allow') {
                   4089:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4090:             }
1.640     albertel 4091: 	    if (lc($tagname) eq 'img') {
                   4092: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4093: 	    }
1.886     albertel 4094: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4095:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4096: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4097:                 }
1.886     albertel 4098: 	    }
1.645     raeburn  4099:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4100:                 my $src;
1.645     raeburn  4101:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4102:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4103:                 } else {
1.1164    raeburn  4104:                     if ($attr->{'src'} ne '') {
                   4105:                         $src = $attr->{'src'};
                   4106:                         &add_filetype($allfiles,$src,'src');
                   4107:                     }
                   4108:                 }
                   4109:                 my $text = $p->get_trimmed_text();
                   4110:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4111:                     my @swfargs = split(/,/,$1);
                   4112:                     foreach my $item (@swfargs) {
                   4113:                         $item =~ s/["']//g;
                   4114:                         $item =~ s/^\s+//;
                   4115:                         $item =~ s/\s+$//;
                   4116:                     }
                   4117:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4118:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4119:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4120:                         } else {
                   4121:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4122:                         }
                   4123:                     }
1.645     raeburn  4124:                 }
                   4125:             }
                   4126:             if (lc($tagname) eq 'link') {
                   4127:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4128:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4129:                 }
                   4130:             }
1.640     albertel 4131: 	    if (lc($tagname) eq 'object' ||
                   4132: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4133: 		foreach my $item (keys(%javafiles)) {
                   4134: 		    $javafiles{$item} = '';
                   4135: 		}
1.1164    raeburn  4136:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4137:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4138:                 }
1.640     albertel 4139: 	    }
                   4140: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4141: 		my $name = lc($attr->{'name'});
                   4142: 		foreach my $item (keys(%javafiles)) {
                   4143: 		    if ($name eq $item) {
                   4144: 			$javafiles{$item} = $attr->{'value'};
                   4145: 			last;
                   4146: 		    }
                   4147: 		}
1.1164    raeburn  4148:                 my $pathfrom;
1.640     albertel 4149: 		foreach my $item (keys(%mediafiles)) {
                   4150: 		    if ($name eq $item) {
1.1164    raeburn  4151:                         $pathfrom = $attr->{'value'};
                   4152:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4153: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4154: 			last;
                   4155: 		    }
                   4156: 		}
1.1164    raeburn  4157:                 if ($name eq 'flashvars') {
                   4158:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4159:                 }
                   4160:                 if ($pathfrom ne '') {
                   4161:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4162:                                          $pathfrom);
                   4163:                 }
1.640     albertel 4164: 	    }
                   4165: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4166: 		foreach my $item (keys(%javafiles)) {
                   4167: 		    if ($attr->{$item}) {
                   4168: 			$javafiles{$item} = $attr->{$item};
                   4169: 			last;
                   4170: 		    }
                   4171: 		}
                   4172: 		foreach my $item (keys(%mediafiles)) {
                   4173: 		    if ($attr->{$item}) {
                   4174: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4175: 			last;
                   4176: 		    }
                   4177: 		}
1.1164    raeburn  4178:                 if (lc($tagname) eq 'embed') {
                   4179:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4180:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4181:                                              $attr->{'src'});
                   4182:                     }
                   4183:                 }
1.640     albertel 4184: 	    }
1.1172.2.35  raeburn  4185:             if (lc($tagname) eq 'iframe') {
                   4186:                 my $src = $attr->{'src'} ;
                   4187:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4188:                     &add_filetype($allfiles,$src,'src');
                   4189:                 } elsif ($src =~ m{^/}) {
                   4190:                     if ($env{'request.course.id'}) {
                   4191:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4192:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4193:                         my $url = &hreflocation('',$fullpath);
                   4194:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4195:                             my $relpath = $1;
                   4196:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4197:                                 &add_filetype($allfiles,$1,'src');
                   4198:                             }
                   4199:                         }
                   4200:                     }
                   4201:                 }
                   4202:             }
1.1164    raeburn  4203:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4204:                 pop(@state);
1.1164    raeburn  4205:             }
1.640     albertel 4206: 	} elsif ($t->[0] eq 'E') {
                   4207: 	    my ($tagname) = ($t->[1]);
                   4208: 	    if ($javafiles{'codebase'} ne '') {
                   4209: 		$javafiles{'codebase'} .= '/';
                   4210: 	    }  
                   4211: 	    if (lc($tagname) eq 'applet' ||
                   4212: 		lc($tagname) eq 'object' ||
                   4213: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4214: 		) {
                   4215: 		foreach my $item (keys(%javafiles)) {
                   4216: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4217: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4218: 			&add_filetype($allfiles,$file,$item);
                   4219: 		    }
                   4220: 		}
                   4221: 	    } 
                   4222: 	    pop @state;
                   4223: 	}
                   4224:     }
1.1164    raeburn  4225:     foreach my $id (sort(keys(%flashvars))) {
                   4226:         if ($shockwave{$id} ne '') {
                   4227:             my @pairs = split(/\&/,$flashvars{$id});
                   4228:             foreach my $pair (@pairs) {
                   4229:                 my ($key,$value) = split(/\=/,$pair);
                   4230:                 if ($key eq 'thumb') {
                   4231:                     &add_filetype($allfiles,$value,$key);
                   4232:                 } elsif ($key eq 'content') {
                   4233:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4234:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4235:                     if ($ext ne '') {
                   4236:                         &add_filetype($allfiles,$path.$value,$ext);
                   4237:                     }
                   4238:                 }
                   4239:             }
                   4240:         }
                   4241:     }
1.637     raeburn  4242:     return 'ok';
                   4243: }
                   4244: 
1.639     albertel 4245: sub add_filetype {
                   4246:     my ($allfiles,$file,$type)=@_;
                   4247:     if (exists($allfiles->{$file})) {
                   4248: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4249: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4250: 	}
                   4251:     } else {
                   4252: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4253:     }
                   4254: }
                   4255: 
1.1164    raeburn  4256: sub embedded_dependency {
                   4257:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4258:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4259:         if (($identifier ne '') &&
                   4260:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4261:             ($pathfrom ne '')) {
                   4262:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4263:             foreach my $dep (@{$related->{$identifier}}) {
                   4264:                 &add_filetype($allfiles,$path.$dep,'object');
                   4265:             }
                   4266:         }
                   4267:     }
                   4268:     return;
                   4269: }
                   4270: 
1.1172.2.109  raeburn  4271: sub bubblesheet_converter {
                   4272:     my ($cdom,$fullpath,$config,$format) = @_;
                   4273:     if ((&domain($cdom) ne '') &&
                   4274:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4275:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4276:         my (%csvcols,%csvoptions);
                   4277:         if (ref($config->{'fields'}) eq 'HASH') {
                   4278:             %csvcols = %{$config->{'fields'}};
                   4279:         }
                   4280:         if (ref($config->{'options'}) eq 'HASH') {
                   4281:             %csvoptions = %{$config->{'options'}};
                   4282:         }
                   4283:         my %csvbynum = reverse(%csvcols);
                   4284:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4285:         if (keys(%scantronconf)) {
                   4286:             my %bynum = (
                   4287:                           $scantronconf{CODEstart} => 'CODEstart',
                   4288:                           $scantronconf{IDstart}   => 'IDstart',
                   4289:                           $scantronconf{PaperID}   => 'PaperID',
                   4290:                           $scantronconf{FirstName} => 'FirstName',
                   4291:                           $scantronconf{LastName}  => 'LastName',
                   4292:                           $scantronconf{Qstart}    => 'Qstart',
                   4293:                         );
                   4294:             my @ordered;
                   4295:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4296:                 push(@ordered,$bynum{$item});
                   4297:             }
                   4298:             my %mapstart = (
                   4299:                               CODEstart => 'CODE',
                   4300:                               IDstart   => 'ID',
                   4301:                               PaperID   => 'PaperID',
                   4302:                               FirstName => 'FirstName',
                   4303:                               LastName  => 'LastName',
                   4304:                               Qstart    => 'FirstQuestion',
                   4305:                            );
                   4306:             my %maplength = (
                   4307:                               CODEstart => 'CODElength',
                   4308:                               IDstart   => 'IDlength',
                   4309:                               PaperID   => 'PaperIDlength',
                   4310:                               FirstName => 'FirstNamelength',
                   4311:                               LastName  => 'LastNamelength',
                   4312:             );
                   4313:             if (open(my $fh,'<',$fullpath)) {
                   4314:                 my $output;
                   4315:                 my %lettdig = &letter_to_digits();
                   4316:                 my %diglett = reverse(%lettdig);
                   4317:                 my $numletts = scalar(keys(%lettdig));
                   4318:                 my $num = 0;
                   4319:                 while (my $line=<$fh>) {
                   4320:                     $num ++;
                   4321:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4322:                     $line =~ s{[\r\n]+$}{};
                   4323:                     my %found;
                   4324:                     my @values = split(/,/,$line);
                   4325:                     my ($qstart,$record);
                   4326:                     for (my $i=0; $i<@values; $i++) {
                   4327:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4328:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4329:                             if ($values[$i] eq '') {
                   4330:                                 $values[$i] = $scantronconf{'Qoff'};
                   4331:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4332:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4333:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4334:                                 }
                   4335:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4336:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4337:                                     $values[$i] = $diglett{$values[$i]};
                   4338:                                 }
                   4339:                             } else {
                   4340:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4341:                                     my $digit;
                   4342:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4343:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4344:                                         if ($values[$i] eq 'J') {
                   4345:                                             $digit += $numletts;
                   4346:                                         }
                   4347:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4348:                                         $digit = $values[$i]-1;
                   4349:                                         if ($values[$i] eq '0') {
                   4350:                                             $digit += $numletts;
                   4351:                                         }
                   4352:                                     }
                   4353:                                     my $qval='';
                   4354:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4355:                                         if ($j == $digit) {
                   4356:                                             $qval .= $scantronconf{'Qon'};
                   4357:                                         } else {
                   4358:                                             $qval .= $scantronconf{'Qoff'};
                   4359:                                         }
                   4360:                                     }
                   4361:                                     $values[$i] = $qval;
                   4362:                                 }
                   4363:                             }
                   4364:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4365:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4366:                             }
                   4367:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4368:                             if ($numblank > 0) {
                   4369:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4370:                             }
                   4371:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4372:                                 $qstart = $i;
                   4373:                                 $found{$csvbynum{$i}} = $values[$i];
                   4374:                             } else {
                   4375:                                 $found{'FirstQuestion'} .= $values[$i];
                   4376:                             }
                   4377:                         } elsif (exists($csvbynum{$i})) {
                   4378:                             if ($csvoptions{'rem'}) {
                   4379:                                 $values[$i] =~ s/^\s+//;
                   4380:                             }
                   4381:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4382:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4383:                                     $values[$i] = '0'.$values[$i];
                   4384:                                 }
                   4385:                             }
                   4386:                             $found{$csvbynum{$i}} = $values[$i];
                   4387:                         }
                   4388:                     }
                   4389:                     foreach my $item (@ordered) {
                   4390:                         my $currlength = 1+length($record);
                   4391:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4392:                         if ($numspaces > 0) {
                   4393:                             $record .= (' ' x $numspaces);
                   4394:                         }
                   4395:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4396:                             unless ($item eq 'Qstart') {
                   4397:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4398:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4399:                                 }
                   4400:                             }
                   4401:                             $record .= $found{$mapstart{$item}};
                   4402:                         }
                   4403:                     }
                   4404:                     $output .= "$record\n";
                   4405:                 }
                   4406:                 close($fh);
                   4407:                 if ($output) {
                   4408:                     if (open(my $fh,'>',$fullpath)) {
                   4409:                         print $fh $output;
                   4410:                         close($fh);
                   4411:                     }
                   4412:                 }
                   4413:             }
                   4414:         }
                   4415:         return;
                   4416:     }
                   4417: }
                   4418: 
                   4419: sub letter_to_digits {
                   4420:     my %lettdig = (
                   4421:                     A => 1,
                   4422:                     B => 2,
                   4423:                     C => 3,
                   4424:                     D => 4,
                   4425:                     E => 5,
                   4426:                     F => 6,
                   4427:                     G => 7,
                   4428:                     H => 8,
                   4429:                     I => 9,
                   4430:                     J => 0,
                   4431:                   );
                   4432:     return %lettdig;
                   4433: }
                   4434: 
                   4435: sub get_scantron_config {
                   4436:     my ($which,$cdom) = @_;
                   4437:     my @lines = &get_scantronformat_file($cdom);
                   4438:     my %config;
                   4439:     #FIXME probably should move to XML it has already gotten a bit much now
                   4440:     foreach my $line (@lines) {
                   4441:         my ($name,$descrip)=split(/:/,$line);
                   4442:         if ($name ne $which ) { next; }
                   4443:         chomp($line);
                   4444:         my @config=split(/:/,$line);
                   4445:         $config{'name'}=$config[0];
                   4446:         $config{'description'}=$config[1];
                   4447:         $config{'CODElocation'}=$config[2];
                   4448:         $config{'CODEstart'}=$config[3];
                   4449:         $config{'CODElength'}=$config[4];
                   4450:         $config{'IDstart'}=$config[5];
                   4451:         $config{'IDlength'}=$config[6];
                   4452:         $config{'Qstart'}=$config[7];
                   4453:         $config{'Qlength'}=$config[8];
                   4454:         $config{'Qoff'}=$config[9];
                   4455:         $config{'Qon'}=$config[10];
                   4456:         $config{'PaperID'}=$config[11];
                   4457:         $config{'PaperIDlength'}=$config[12];
                   4458:         $config{'FirstName'}=$config[13];
                   4459:         $config{'FirstNamelength'}=$config[14];
                   4460:         $config{'LastName'}=$config[15];
                   4461:         $config{'LastNamelength'}=$config[16];
                   4462:         $config{'BubblesPerRow'}=$config[17];
                   4463:         last;
                   4464:     }
                   4465:     return %config;
                   4466: }
                   4467: 
                   4468: sub get_scantronformat_file {
                   4469:     my ($cdom) = @_;
                   4470:     if ($cdom eq '') {
                   4471:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4472:     }
                   4473:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4474:     my $gottab = 0;
                   4475:     my @lines;
                   4476:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4477:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4478:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4479:             if ($formatfile ne '-1') {
                   4480:                 @lines = split("\n",$formatfile,-1);
                   4481:                 $gottab = 1;
                   4482:             }
                   4483:         }
                   4484:     }
                   4485:     if (!$gottab) {
                   4486:         my $confname = $cdom.'-domainconfig';
                   4487:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4488:         my $formatfile = &getfile($default);
                   4489:         if ($formatfile ne '-1') {
                   4490:             @lines = split("\n",$formatfile,-1);
                   4491:             $gottab = 1;
                   4492:         }
                   4493:     }
                   4494:     if (!$gottab) {
                   4495:         my @domains = &current_machine_domains();
                   4496:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4497:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4498:                 @lines = <$fh>;
                   4499:                 close($fh);
                   4500:             }
                   4501:         } else {
                   4502:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4503:                 @lines = <$fh>;
                   4504:                 close($fh);
                   4505:             }
                   4506:         }
                   4507:     }
                   4508:     return @lines;
                   4509: }
                   4510: 
1.493     albertel 4511: sub removeuploadedurl {
1.984     neumanie 4512:     my ($url)=@_;	
                   4513:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4514:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4515: }
                   4516: 
                   4517: sub removeuserfile {
                   4518:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4519:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4520:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4521:     if ($result eq 'ok') {	
1.798     raeburn  4522:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4523:             my $metafile = $fname.'.meta';
                   4524:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4525: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4526:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4527:             my $sqlresult = 
1.823     albertel 4528:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4529:                                         'portfolio_metadata',$group,
                   4530:                                         'delete');
1.798     raeburn  4531:         }
                   4532:     }
                   4533:     return $result;
1.257     www      4534: }
1.15      www      4535: 
1.530     albertel 4536: sub mkdiruserfile {
                   4537:     my ($docuname,$docudom,$dir)=@_;
                   4538:     my $home=&homeserver($docuname,$docudom);
                   4539:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4540: }
                   4541: 
1.531     albertel 4542: sub renameuserfile {
                   4543:     my ($docuname,$docudom,$old,$new)=@_;
                   4544:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4545:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4546:                         &escape("$old").':'.&escape("$new"),$home);
                   4547:     if ($result eq 'ok') {
                   4548:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4549:             my $oldmeta = $old.'.meta';
                   4550:             my $newmeta = $new.'.meta';
                   4551:             my $metaresult = 
                   4552:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4553: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4554:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4555:             my $sqlresult = 
1.823     albertel 4556:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4557:                                         'portfolio_metadata',$group,
                   4558:                                         'delete');
1.798     raeburn  4559:         }
                   4560:     }
                   4561:     return $result;
1.531     albertel 4562: }
                   4563: 
1.14      www      4564: # ------------------------------------------------------------------------- Log
                   4565: 
                   4566: sub log {
                   4567:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4568:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4569: }
                   4570: 
                   4571: # ------------------------------------------------------------------ Course Log
1.352     www      4572: #
                   4573: # This routine flushes several buffers of non-mission-critical nature
                   4574: #
1.157     www      4575: 
                   4576: sub flushcourselogs {
1.352     www      4577:     &logthis('Flushing log buffers');
                   4578: #
                   4579: # course logs
                   4580: # This is a log of all transactions in a course, which can be used
                   4581: # for data mining purposes
                   4582: #
                   4583: # It also collects the courseid database, which lists last transaction
                   4584: # times and course titles for all courseids
                   4585: #
                   4586:     my %courseidbuffer=();
1.921     raeburn  4587:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4588:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4589: 		          &escape($courselogs{$crsid}),
                   4590: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4591: 	    delete $courselogs{$crsid};
                   4592:         } else {
                   4593:             &logthis('Failed to flush log buffer for '.$crsid);
                   4594:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4595:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4596:                         " exceeded maximum size, deleting.</font>");
                   4597:                delete $courselogs{$crsid};
                   4598:             }
1.352     www      4599:         }
1.920     raeburn  4600:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4601:             'description' => $coursedescrbuf{$crsid},
                   4602:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4603:             'type'        => $coursetypebuf{$crsid},
                   4604:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4605:         };
1.191     harris41 4606:     }
1.352     www      4607: #
                   4608: # Write course id database (reverse lookup) to homeserver of courses 
                   4609: # Is used in pickcourse
                   4610: #
1.840     albertel 4611:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4612:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4613:                                     $courseidbuffer{$crs_home},
                   4614:                                     $crs_home,'timeonly');
1.352     www      4615:     }
                   4616: #
                   4617: # File accesses
                   4618: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4619: #
1.449     matthew  4620:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4621:         if ($entry =~ /___count$/) {
                   4622:             my ($dom,$name);
1.807     albertel 4623:             ($dom,$name,undef)=
1.811     albertel 4624: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4625:             if (! defined($dom) || $dom eq '' || 
                   4626:                 ! defined($name) || $name eq '') {
1.620     albertel 4627:                 my $cid = $env{'request.course.id'};
                   4628:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4629:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4630:             }
1.450     matthew  4631:             my $value = $accesshash{$entry};
                   4632:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4633:             my %temphash=($url => $value);
1.449     matthew  4634:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4635:             if ($result eq 'ok') {
                   4636:                 delete $accesshash{$entry};
                   4637:             }
                   4638:         } else {
1.811     albertel 4639:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4640:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4641:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4642:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4643:                 delete $accesshash{$entry};
                   4644:             }
1.185     www      4645:         }
1.191     harris41 4646:     }
1.352     www      4647: #
                   4648: # Roles
                   4649: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4650: #
1.800     albertel 4651:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4652:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4653: 	    split(/\:/,$entry);
                   4654:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4655:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4656:                 $rudom,$runame) eq 'ok') {
                   4657: 	    delete $userrolehash{$entry};
                   4658:         }
                   4659:     }
1.662     raeburn  4660: #
1.1172.2.90  raeburn  4661: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4662: #
                   4663:     my %domrolebuffer = ();
1.1000    raeburn  4664:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4665:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4666:         if ($domrolebuffer{$rudom}) {
                   4667:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4668:                       '='.&escape($domainrolehash{$entry});
                   4669:         } else {
                   4670:             $domrolebuffer{$rudom}.=&escape($entry).
                   4671:                       '='.&escape($domainrolehash{$entry});
                   4672:         }
                   4673:         delete $domainrolehash{$entry};
                   4674:     }
                   4675:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4676:         my %servers;
                   4677:         if (defined(&domain($dom,'primary'))) {
                   4678:             my $primary=&domain($dom,'primary');
                   4679:             my $hostname=&hostname($primary);
                   4680:             $servers{$primary} = $hostname;
                   4681:         } else {
                   4682:             %servers = &get_servers($dom,'library');
                   4683:         }
1.841     albertel 4684: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4685: 	    if (&reply('domroleput:'.$dom.':'.
                   4686: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4687: 	        last;
                   4688: 	    } else {
1.841     albertel 4689: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4690: 	    }
1.662     raeburn  4691:         }
                   4692:     }
1.186     www      4693:     $dumpcount++;
1.157     www      4694: }
                   4695: 
                   4696: sub courselog {
                   4697:     my $what=shift;
1.158     www      4698:     $what=time.':'.$what;
1.620     albertel 4699:     unless ($env{'request.course.id'}) { return ''; }
                   4700:     $coursedombuf{$env{'request.course.id'}}=
                   4701:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4702:     $coursenumbuf{$env{'request.course.id'}}=
                   4703:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4704:     $coursehombuf{$env{'request.course.id'}}=
                   4705:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4706:     $coursedescrbuf{$env{'request.course.id'}}=
                   4707:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4708:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4709:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4710:     $courseownerbuf{$env{'request.course.id'}}=
                   4711:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4712:     $coursetypebuf{$env{'request.course.id'}}=
                   4713:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4714:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4715: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4716:     } else {
1.620     albertel 4717: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4718:     }
1.620     albertel 4719:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4720: 	&flushcourselogs();
                   4721:     }
1.158     www      4722: }
                   4723: 
                   4724: sub courseacclog {
                   4725:     my $fnsymb=shift;
1.620     albertel 4726:     unless ($env{'request.course.id'}) { return ''; }
                   4727:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4728:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4729:         $what.=':POST';
1.583     matthew  4730:         # FIXME: Probably ought to escape things....
1.800     albertel 4731: 	foreach my $key (keys(%env)) {
                   4732:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4733:                 my $formitem = $1;
                   4734:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4735:                     $what.=':'.$formitem.'='.$env{$key};
                   4736:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.118.  .12(raeb 4737:-20):                     if ($formitem eq 'proctorpassword') {
                   4738:-20):                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
                   4739:-20):                     } else {
                   4740:-20):                         $what.=':'.$formitem.'='.$env{$key};
                   4741:-20):                     }
1.975     raeburn  4742:                 }
1.158     www      4743:             }
1.191     harris41 4744:         }
1.583     matthew  4745:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4746:         # FIXME: We should not be depending on a form parameter that someone
                   4747:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4748:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4749:             $what.= ':POST';
                   4750:             # FIXME: Probably ought to escape things....
                   4751:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4752:                                  'crsdiscuss') {
1.620     albertel 4753:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4754:             }
                   4755:         }
1.158     www      4756:     }
                   4757:     &courselog($what);
1.149     www      4758: }
                   4759: 
1.185     www      4760: sub countacc {
                   4761:     my $url=&declutter(shift);
1.458     matthew  4762:     return if (! defined($url) || $url eq '');
1.620     albertel 4763:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4764: #
                   4765: # Mark that this url was used in this course
                   4766: #
1.620     albertel 4767:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4768: #
                   4769: # Increase the access count for this resource in this child process
                   4770: #
1.281     www      4771:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4772:     $accesshash{$key}++;
1.185     www      4773: }
1.349     www      4774: 
1.361     www      4775: sub linklog {
                   4776:     my ($from,$to)=@_;
                   4777:     $from=&declutter($from);
                   4778:     $to=&declutter($to);
                   4779:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4780:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4781: }
1.1160    www      4782: 
                   4783: sub statslog {
                   4784:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4785:     if ($users<2) { return; }
                   4786:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4787:             'course'       => $env{'request.course.id'},
                   4788:             'sections'     => '"all"',
                   4789:             'num_students' => $users,
                   4790:             'part'         => $part,
                   4791:             'symb'         => $symb,
                   4792:             'mean_tries'   => $av_attempts,
                   4793:             'deg_of_diff'  => $degdiff});
                   4794:     foreach my $key (keys(%dynstore)) {
                   4795:         $accesshash{$key}=$dynstore{$key};
                   4796:     }
                   4797: }
1.361     www      4798:   
1.349     www      4799: sub userrolelog {
                   4800:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4801:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4802:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4803:        $userrolehash
                   4804:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4805:                     =$tend.':'.$tstart;
1.662     raeburn  4806:     }
1.1169    droeschl 4807:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4808:        $userrolehash
                   4809:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4810:                     =$tend.':'.$tstart;
                   4811:     }
1.1172.2.90  raeburn  4812:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4813:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4814:        $domainrolehash
                   4815:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4816:                     = $tend.':'.$tstart;
                   4817:     }
1.351     www      4818: }
                   4819: 
1.957     raeburn  4820: sub courserolelog {
                   4821:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4822:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4823:         my $cdom = $1;
                   4824:         my $cnum = $2;
                   4825:         my $sec = $3;
                   4826:         my $namespace = 'rolelog';
                   4827:         my %storehash = (
                   4828:                            role    => $trole,
                   4829:                            start   => $tstart,
                   4830:                            end     => $tend,
                   4831:                            selfenroll => $selfenroll,
                   4832:                            context    => $context,
                   4833:                         );
                   4834:         if ($trole eq 'gr') {
                   4835:             $namespace = 'groupslog';
                   4836:             $storehash{'group'} = $sec;
                   4837:         } else {
                   4838:             $storehash{'section'} = $sec;
                   4839:         }
                   4840:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4841:                    $domain,$cnum,$cdom);
                   4842:         if (($trole ne 'st') || ($sec ne '')) {
                   4843:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4844:         }
                   4845:     }
                   4846:     return;
                   4847: }
                   4848: 
1.1172.2.9  raeburn  4849: sub domainrolelog {
                   4850:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4851:     if ($area =~ m{^/($match_domain)/$}) {
                   4852:         my $cdom = $1;
                   4853:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4854:         my $namespace = 'rolelog';
                   4855:         my %storehash = (
                   4856:                            role    => $trole,
                   4857:                            start   => $tstart,
                   4858:                            end     => $tend,
                   4859:                            context => $context,
                   4860:                         );
                   4861:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4862:                    $domain,$domconfiguser,$cdom);
                   4863:     }
                   4864:     return;
                   4865: 
                   4866: }
                   4867: 
                   4868: sub coauthorrolelog {
                   4869:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4870:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4871:         my $audom = $1;
                   4872:         my $auname = $2;
                   4873:         my $namespace = 'rolelog';
                   4874:         my %storehash = (
                   4875:                            role    => $trole,
                   4876:                            start   => $tstart,
                   4877:                            end     => $tend,
                   4878:                            context => $context,
                   4879:                         );
                   4880:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4881:                    $domain,$auname,$audom);
                   4882:     }
                   4883:     return;
                   4884: }
                   4885: 
1.351     www      4886: sub get_course_adv_roles {
1.948     raeburn  4887:     my ($cid,$codes) = @_;
1.620     albertel 4888:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4889:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4890:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4891:     my %nothide=();
1.800     albertel 4892:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4893:         if ($user !~ /:/) {
                   4894: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4895:         } else {
                   4896:             $nothide{$user}=1;
                   4897:         }
1.470     www      4898:     }
1.1172.2.23  raeburn  4899:     my @possdoms = ($coursehash{'domain'});
                   4900:     if ($coursehash{'checkforpriv'}) {
                   4901:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4902:     }
1.351     www      4903:     my %returnhash=();
                   4904:     my %dumphash=
                   4905:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4906:     my $now=time;
1.997     raeburn  4907:     my %privileged;
1.1000    raeburn  4908:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4909: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4910:         if (($tstart) && ($tstart<0)) { next; }
                   4911:         if (($tend) && ($tend<$now)) { next; }
                   4912:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4913:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4914: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4915:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4916:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4917: 	if ($role eq 'cr') { next; }
1.948     raeburn  4918:         if ($codes) {
                   4919:             if ($section) { $role .= ':'.$section; }
                   4920:             if ($returnhash{$role}) {
                   4921:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4922:             } else {
                   4923:                 $returnhash{$role}=$username.':'.$domain;
                   4924:             }
1.351     www      4925:         } else {
1.988     raeburn  4926:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4927:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4928:             if ($returnhash{$key}) {
                   4929: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4930:             } else {
                   4931:                 $returnhash{$key}=$username.':'.$domain;
                   4932:             }
1.351     www      4933:         }
1.948     raeburn  4934:     }
1.400     www      4935:     return %returnhash;
                   4936: }
                   4937: 
                   4938: sub get_my_roles {
1.937     raeburn  4939:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4940:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4941:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4942:     my (%dumphash,%nothide);
1.1086    raeburn  4943:     if ($context eq 'userroles') {
1.1166    raeburn  4944:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4945:     } else {
1.1172.2.23  raeburn  4946:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4947:         if ($hidepriv) {
                   4948:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4949:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4950:                 if ($user !~ /:/) {
                   4951:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4952:                 } else {
                   4953:                     $nothide{$user} = 1;
                   4954:                 }
                   4955:             }
                   4956:         }
1.858     raeburn  4957:     }
1.400     www      4958:     my %returnhash=();
                   4959:     my $now=time;
1.999     raeburn  4960:     my %privileged;
1.800     albertel 4961:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4962:         my ($role,$tend,$tstart);
                   4963:         if ($context eq 'userroles') {
1.1149    raeburn  4964:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4965: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4966:         } else {
                   4967:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4968:         }
1.400     www      4969:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4970:         my $status = 'active';
1.939     raeburn  4971:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4972:             $status = 'previous';
                   4973:         } 
                   4974:         if (($tstart) && ($now<$tstart)) {
                   4975:             $status = 'future';
                   4976:         }
                   4977:         if (ref($types) eq 'ARRAY') {
                   4978:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4979:                 next;
                   4980:             } 
                   4981:         } else {
                   4982:             if ($status ne 'active') {
                   4983:                 next;
                   4984:             }
                   4985:         }
1.867     raeburn  4986:         my ($rolecode,$username,$domain,$section,$area);
                   4987:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4988:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4989:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4990:         } else {
                   4991:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4992:         }
1.832     raeburn  4993:         if (ref($roledoms) eq 'ARRAY') {
                   4994:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4995:                 next;
                   4996:             }
                   4997:         }
                   4998:         if (ref($roles) eq 'ARRAY') {
                   4999:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5000:                 if ($role =~ /^cr\//) {
                   5001:                     if (!grep(/^cr$/,@{$roles})) {
                   5002:                         next;
                   5003:                     }
1.1104    raeburn  5004:                 } elsif ($role =~ /^gr\//) {
                   5005:                     if (!grep(/^gr$/,@{$roles})) {
                   5006:                         next;
                   5007:                     }
1.922     raeburn  5008:                 } else {
                   5009:                     next;
                   5010:                 }
1.832     raeburn  5011:             }
1.867     raeburn  5012:         }
1.937     raeburn  5013:         if ($hidepriv) {
1.1172.2.23  raeburn  5014:             my @privroles = ('dc','su');
1.999     raeburn  5015:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5016:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5017:             } else {
1.1172.2.23  raeburn  5018:                 my $possdoms = [$domain];
                   5019:                 if (ref($roledoms) eq 'ARRAY') {
                   5020:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5021:                 }
1.1172.2.23  raeburn  5022:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5023:                     if (!$nothide{$username.':'.$domain}) {
                   5024:                         next;
                   5025:                     }
                   5026:                 }
1.937     raeburn  5027:             }
                   5028:         }
1.933     raeburn  5029:         if ($withsec) {
                   5030:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5031:                 $tstart.':'.$tend;
                   5032:         } else {
                   5033:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5034:         }
1.832     raeburn  5035:     }
1.373     www      5036:     return %returnhash;
1.399     www      5037: }
                   5038: 
1.1172.2.89  raeburn  5039: sub get_all_adhocroles {
                   5040:     my ($dom) = @_;
                   5041:     my @roles_by_num = ();
                   5042:     my %domdefaults = &get_domain_defaults($dom);
                   5043:     my (%description,%access_in_dom,%access_info);
                   5044:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5045:         my $count = 0;
                   5046:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5047:         my %ordered;
                   5048:         foreach my $role (sort(keys(%domcurrent))) {
                   5049:             my ($order,$desc,$access_in_dom);
                   5050:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5051:                 $order = $domcurrent{$role}{'order'};
                   5052:                 $desc = $domcurrent{$role}{'desc'};
                   5053:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5054:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5055:             }
                   5056:             if ($order eq '') {
                   5057:                 $order = $count;
                   5058:             }
                   5059:             $ordered{$order} = $role;
                   5060:             if ($desc ne '') {
                   5061:                 $description{$role} = $desc;
                   5062:             } else {
                   5063:                 $description{$role}= $role;
                   5064:             }
                   5065:             $count++;
                   5066:         }
                   5067:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5068:             push(@roles_by_num,$ordered{$item});
                   5069:         }
                   5070:     }
                   5071:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5072: }
                   5073: 
                   5074: sub get_my_adhocroles {
                   5075:     my ($cid,$checkreg) = @_;
                   5076:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5077:     if ($env{'request.course.id'} eq $cid) {
                   5078:         $cdom = $env{'course.'.$cid.'.domain'};
                   5079:         $cnum = $env{'course.'.$cid.'.num'};
                   5080:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5081:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5082:         $cdom = $1;
                   5083:         $cnum = $2;
                   5084:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5085:                                      $cdom,$cnum);
                   5086:     }
                   5087:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5088:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5089:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5090:         if ($rosterhash{$user} ne '') {
                   5091:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5092:             return ([],{}) if ($type eq 'auto');
                   5093:         }
                   5094:     }
                   5095:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5096:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5097:             my $then=$env{'user.login.time'};
                   5098:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5099:             if (!$update) {
                   5100:                 $update = $then;
                   5101:             }
                   5102:             my @liveroles;
                   5103:             foreach my $role ('dh','da') {
                   5104:                 if ($env{"user.role.$role./$cdom/"}) {
                   5105:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5106:                     my $limit = $update;
                   5107:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5108:                         $limit = $then;
                   5109:                     }
                   5110:                     my $activerole = 1;
                   5111:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5112:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5113:                     if ($activerole) {
                   5114:                         push(@liveroles,$role);
                   5115:                     }
                   5116:                 }
                   5117:             }
                   5118:             if (@liveroles) {
1.1172.2.89  raeburn  5119:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5120:                     my ($accessref,$accessinfo,%access_in_dom);
                   5121:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5122:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5123:                         if (@{$roles_by_num}) {
                   5124:                             my %settings;
                   5125:                             if ($env{'request.course.id'} eq $cid) {
                   5126:                                 foreach my $envkey (keys(%env)) {
                   5127:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5128:                                         $settings{$1} = $env{$envkey};
                   5129:                                     }
                   5130:                                 }
                   5131:                             } else {
                   5132:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5133:                             }
                   5134:                             my %setincrs;
                   5135:                             if ($settings{'internal.adhocaccess'}) {
                   5136:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5137:                             }
                   5138:                             my @statuses;
                   5139:                             if ($env{'environment.inststatus'}) {
                   5140:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5141:                             }
                   5142:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5143:                             if (ref($accessref) eq 'HASH') {
                   5144:                                 %access_in_dom = %{$accessref};
                   5145:                             }
                   5146:                             foreach my $role (@{$roles_by_num}) {
                   5147:                                 my ($curraccess,@okstatus,@personnel);
                   5148:                                 if ($setincrs{$role}) {
                   5149:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5150:                                     if ($curraccess eq 'status') {
                   5151:                                         @okstatus = split(/\&/,$rest);
                   5152:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5153:                                         @personnel = split(/\&/,$rest);
                   5154:                                     }
                   5155:                                 } else {
                   5156:                                     $curraccess = $access_in_dom{$role};
                   5157:                                     if (ref($accessinfo) eq 'HASH') {
                   5158:                                         if ($curraccess eq 'status') {
                   5159:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5160:                                                 @okstatus = @{$accessinfo->{$role}};
                   5161:                                             }
                   5162:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5163:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5164:                                                 @personnel = @{$accessinfo->{$role}};
                   5165:                                             }
                   5166:                                         }
                   5167:                                     }
                   5168:                                 }
                   5169:                                 if ($curraccess eq 'none') {
                   5170:                                     next;
                   5171:                                 } elsif ($curraccess eq 'all') {
                   5172:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5173:                                 } elsif ($curraccess eq 'dh') {
                   5174:                                     if (grep(/^dh$/,@liveroles)) {
                   5175:                                         push(@possroles,$role);
                   5176:                                     } else {
                   5177:                                         next;
                   5178:                                     }
                   5179:                                 } elsif ($curraccess eq 'da') {
                   5180:                                     if (grep(/^da$/,@liveroles)) {
                   5181:                                         push(@possroles,$role);
                   5182:                                     } else {
                   5183:                                         next;
                   5184:                                     }
1.1172.2.89  raeburn  5185:                                 } elsif ($curraccess eq 'status') {
                   5186:                                     if (@okstatus) {
                   5187:                                         if (!@statuses) {
                   5188:                                             if (grep(/^default$/,@okstatus)) {
                   5189:                                                 push(@possroles,$role);
                   5190:                                             }
                   5191:                                         } else {
                   5192:                                             foreach my $status (@okstatus) {
                   5193:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5194:                                                     push(@possroles,$role);
                   5195:                                                     last;
                   5196:                                                 }
                   5197:                                             }
                   5198:                                         }
                   5199:                                     }
                   5200:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5201:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5202:                                         if ($curraccess eq 'exc') {
                   5203:                                             push(@possroles,$role);
                   5204:                                         }
                   5205:                                     } elsif ($curraccess eq 'inc') {
                   5206:                                         push(@possroles,$role);
                   5207:                                     }
                   5208:                                 }
                   5209:                             }
                   5210:                         }
                   5211:                     }
                   5212:                 }
                   5213:             }
                   5214:         }
                   5215:     }
                   5216:     unless (ref($description) eq 'HASH') {
                   5217:         if (ref($roles_by_num) eq 'ARRAY') {
                   5218:             my %desc;
                   5219:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5220:             $description = \%desc;
                   5221:         } else {
                   5222:             $description = {};
                   5223:         }
                   5224:     }
                   5225:     return (\@possroles,$description);
                   5226: }
                   5227: 
1.399     www      5228: # ----------------------------------------------------- Frontpage Announcements
                   5229: #
                   5230: #
                   5231: 
                   5232: sub postannounce {
                   5233:     my ($server,$text)=@_;
1.844     albertel 5234:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5235:     unless ($text=~/\w/) { $text=''; }
                   5236:     return &reply('setannounce:'.&escape($text),$server);
                   5237: }
                   5238: 
                   5239: sub getannounce {
1.448     albertel 5240: 
1.1172.2.96  raeburn  5241:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5242: 	my $announcement='';
1.800     albertel 5243: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5244: 	close($fh);
1.399     www      5245: 	if ($announcement=~/\w/) { 
                   5246: 	    return 
                   5247:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5248:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5249: 	} else {
                   5250: 	    return '';
                   5251: 	}
                   5252:     } else {
                   5253: 	return '';
                   5254:     }
1.351     www      5255: }
1.353     www      5256: 
                   5257: # ---------------------------------------------------------- Course ID routines
                   5258: # Deal with domain's nohist_courseid.db files
                   5259: #
                   5260: 
                   5261: sub courseidput {
1.921     raeburn  5262:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5263:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5264:     my $outcome;
                   5265:     if ($caller eq 'timeonly') {
                   5266:         my $cids = '';
                   5267:         foreach my $item (keys(%$storehash)) {
                   5268:             $cids.=&escape($item).'&';
                   5269:         }
                   5270:         $cids=~s/\&$//;
                   5271:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5272:                           $coursehome);       
                   5273:     } else {
                   5274:         my $items = '';
                   5275:         foreach my $item (keys(%$storehash)) {
                   5276:             $items.= &escape($item).'='.
                   5277:                      &freeze_escape($$storehash{$item}).'&';
                   5278:         }
                   5279:         $items=~s/\&$//;
                   5280:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5281:                           $coursehome);
1.918     raeburn  5282:     }
                   5283:     if ($outcome eq 'unknown_cmd') {
                   5284:         my $what;
                   5285:         foreach my $cid (keys(%$storehash)) {
                   5286:             $what .= &escape($cid).'=';
1.921     raeburn  5287:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5288:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5289:             }
                   5290:             $what =~ s/\:$/&/;
                   5291:         }
                   5292:         $what =~ s/\&$//;  
                   5293:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5294:     } else {
                   5295:         return $outcome;
                   5296:     }
1.353     www      5297: }
                   5298: 
                   5299: sub courseiddump {
1.921     raeburn  5300:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5301:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5302:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5303:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5304:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5305:     my $as_hash = 1;
                   5306:     my %returnhash;
                   5307:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5308:     my %libserv = &all_library();
                   5309:     foreach my $tryserver (keys(%libserv)) {
                   5310:         if ( (  $hostidflag == 1 
                   5311: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5312: 	     || (!defined($hostidflag)) ) {
                   5313: 
1.918     raeburn  5314: 	    if (($domfilter eq '') ||
                   5315: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5316:                 my $rep;
                   5317:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5318:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5319:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5320:                                 &escape($descfilter), &escape($instcodefilter),
                   5321:                                 &escape($ownerfilter), &escape($coursefilter),
                   5322:                                 &escape($typefilter), &escape($regexp_ok),
                   5323:                                 $as_hash, &escape($selfenrollonly),
                   5324:                                 &escape($catfilter), $showhidden, $caller,
                   5325:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5326:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5327:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5328:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5329:                 } else {
                   5330:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5331:                              $sincefilter.':'.&escape($descfilter).':'.
                   5332:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5333:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5334:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5335:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5336:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5337:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5338:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5339:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5340:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5341:                 }
                   5342: 
1.918     raeburn  5343:                 my @pairs=split(/\&/,$rep);
                   5344:                 foreach my $item (@pairs) {
                   5345:                     my ($key,$value)=split(/\=/,$item,2);
                   5346:                     $key = &unescape($key);
                   5347:                     next if ($key =~ /^error: 2 /);
                   5348:                     my $result = &thaw_unescape($value);
                   5349:                     if (ref($result) eq 'HASH') {
                   5350:                         $returnhash{$key}=$result;
                   5351:                     } else {
1.921     raeburn  5352:                         my @responses = split(/:/,$value);
                   5353:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5354:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5355:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5356:                         }
1.1008    raeburn  5357:                     }
1.353     www      5358:                 }
                   5359:             }
                   5360:         }
                   5361:     }
                   5362:     return %returnhash;
                   5363: }
                   5364: 
1.1055    raeburn  5365: sub courselastaccess {
                   5366:     my ($cdom,$cnum,$hostidref) = @_;
                   5367:     my %returnhash;
                   5368:     if ($cdom && $cnum) {
                   5369:         my $chome = &homeserver($cnum,$cdom);
                   5370:         if ($chome ne 'no_host') {
                   5371:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5372:             &extract_lastaccess(\%returnhash,$rep);
                   5373:         }
                   5374:     } else {
                   5375:         if (!$cdom) { $cdom=''; }
                   5376:         my %libserv = &all_library();
                   5377:         foreach my $tryserver (keys(%libserv)) {
                   5378:             if (ref($hostidref) eq 'ARRAY') {
                   5379:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5380:             } 
                   5381:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5382:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5383:                 &extract_lastaccess(\%returnhash,$rep);
                   5384:             }
                   5385:         }
                   5386:     }
                   5387:     return %returnhash;
                   5388: }
                   5389: 
                   5390: sub extract_lastaccess {
                   5391:     my ($returnhash,$rep) = @_;
                   5392:     if (ref($returnhash) eq 'HASH') {
                   5393:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5394:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5395:                  $rep eq '') {
                   5396:             my @pairs=split(/\&/,$rep);
                   5397:             foreach my $item (@pairs) {
                   5398:                 my ($key,$value)=split(/\=/,$item,2);
                   5399:                 $key = &unescape($key);
                   5400:                 next if ($key =~ /^error: 2 /);
                   5401:                 $returnhash->{$key} = &thaw_unescape($value);
                   5402:             }
                   5403:         }
                   5404:     }
                   5405:     return;
                   5406: }
                   5407: 
1.658     raeburn  5408: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5409: 
                   5410: sub dcmailput {
1.685     raeburn  5411:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5412:     my $status = &Apache::lonnet::critical(
1.740     www      5413:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5414:        &escape($message),$server);
1.662     raeburn  5415:     return $status;
                   5416: }
                   5417: 
1.658     raeburn  5418: sub dcmaildump {
                   5419:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5420:     my %returnhash=();
1.846     albertel 5421: 
                   5422:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5423:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5424:                                                          &escape($enddate).':';
                   5425: 	my @esc_senders=map { &escape($_)} @$senders;
                   5426: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5427: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5428:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5429:             if (($key) && ($value)) {
                   5430:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5431:             }
                   5432:         }
                   5433:     }
                   5434:     return %returnhash;
                   5435: }
1.662     raeburn  5436: # ---------------------------------------------------------- Domain roles
                   5437: 
                   5438: sub get_domain_roles {
                   5439:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5440:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5441:         $startdate = '.';
                   5442:     }
1.1018    raeburn  5443:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5444:         $enddate = '.';
                   5445:     }
1.922     raeburn  5446:     my $rolelist;
                   5447:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5448:         $rolelist = join('&',@{$roles});
1.922     raeburn  5449:     }
1.662     raeburn  5450:     my %personnel = ();
1.841     albertel 5451: 
                   5452:     my %servers = &get_servers($dom,'library');
                   5453:     foreach my $tryserver (keys(%servers)) {
                   5454: 	%{$personnel{$tryserver}}=();
                   5455: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5456: 					    &escape($startdate).':'.
                   5457: 					    &escape($enddate).':'.
                   5458: 					    &escape($rolelist), $tryserver))) {
                   5459: 	    my ($key,$value) = split(/\=/,$line,2);
                   5460: 	    if (($key) && ($value)) {
                   5461: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5462: 	    }
                   5463: 	}
1.662     raeburn  5464:     }
                   5465:     return %personnel;
                   5466: }
1.658     raeburn  5467: 
1.1172.2.89  raeburn  5468: sub get_active_domroles {
                   5469:     my ($dom,$roles) = @_;
                   5470:     return () unless (ref($roles) eq 'ARRAY');
                   5471:     my $now = time;
                   5472:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5473:     my %domroles;
                   5474:     foreach my $server (keys(%dompersonnel)) {
                   5475:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5476:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5477:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5478:         }
                   5479:     }
                   5480:     return %domroles;
                   5481: }
                   5482: 
1.1057    www      5483: # ----------------------------------------------------------- Interval timing 
1.149     www      5484: 
1.1153    www      5485: {
                   5486: # Caches needed for speedup of navmaps
                   5487: # We don't want to cache this for very long at all (5 seconds at most)
                   5488: # 
                   5489: # The user for whom we cache
                   5490: my $cachedkey='';
                   5491: # The cached times for this user
                   5492: my %cachedtimes=();
                   5493: # When this was last done
1.1172.2.66  raeburn  5494: my $cachedtime='';
1.1153    www      5495: 
                   5496: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5497:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5498:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5499:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5500:20):         (!$ignorecache)) {
1.1154    raeburn  5501:         return;
                   5502:     }
                   5503:     $cachedtime=time;
                   5504:     $cachedkey=$uname.':'.$udom;
                   5505:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5506: }
                   5507: 
1.504     albertel 5508: sub get_first_access {
1.1172.2.118.  .1(raebu 5509:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5510:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5511:     if ($argsymb) { $symb=$argsymb; }
                   5512:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5513:     if ($argmap) { $map = $argmap; }
1.926     albertel 5514:     if ($type eq 'course') {
                   5515: 	$res='course';
                   5516:     } elsif ($type eq 'map') {
1.588     albertel 5517: 	$res=&symbread($map);
                   5518:     } else {
                   5519: 	$res=$symb;
                   5520:     }
1.1172.2.118.  .1(raebu 5521:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5522:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5523: }
                   5524: 
                   5525: sub set_first_access {
1.1162    raeburn  5526:     my ($type,$interval)=@_;
1.790     albertel 5527:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5528:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5529:     if ($type eq 'course') {
                   5530: 	$res='course';
                   5531:     } elsif ($type eq 'map') {
1.588     albertel 5532: 	$res=&symbread($map);
                   5533:     } else {
                   5534: 	$res=$symb;
                   5535:     }
1.1153    www      5536:     $cachedkey='';
1.1162    raeburn  5537:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5538:     if ($firstaccess) {
                   5539:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5540:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5541:                  "in $courseid");
                   5542:         return 'already_set';
                   5543:     } else {
1.1162    raeburn  5544:         my $start = time;
                   5545: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5546:                           $udom,$uname);
                   5547:         if ($putres eq 'ok') {
                   5548:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5549:                  $udom,$uname); 
                   5550:             &appenv(
                   5551:                      {
                   5552:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5553:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5554:                      }
                   5555:                   );
1.1172.2.97  raeburn  5556:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5557:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5558:             }
1.1172.2.102  raeburn  5559:         } elsif ($putres ne 'refused') {
                   5560:             &logthis("Result: $putres when attempting to set first access time ".
                   5561:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5562:         }
                   5563:         return $putres;
1.505     albertel 5564:     }
                   5565:     return 'already_set';
1.504     albertel 5566: }
1.1153    www      5567: }
1.1172.2.32  raeburn  5568: 
                   5569: sub checkout {
                   5570:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5571:     my $now=time;
                   5572:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.118.  .14(raeb 5573:-21):     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5574:     my $infostr=&escape(
                   5575:                  'CHECKOUTTOKEN&'.
                   5576:                  $tuname.'&'.
                   5577:                  $tudom.'&'.
                   5578:                  $tcrsid.'&'.
                   5579:                  $symb.'&'.
1.1172.2.118.  .14(raeb 5580:-21):                  $now.'&'.$ip);
1.1172.2.32  raeburn  5581:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5582:     if ($token=~/^error\:/) {
                   5583:         &logthis("<font color=\"blue\">WARNING: ".
                   5584:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5585:                  "</font>");
                   5586:         return '';
                   5587:     }
                   5588: 
                   5589:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5590:     $token=~tr/a-z/A-Z/;
                   5591: 
                   5592:     my %infohash=('resource.0.outtoken' => $token,
                   5593:                   'resource.0.checkouttime' => $now,
1.1172.2.118.  .14(raeb 5594:-21):                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5595: 
                   5596:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5597:        return '';
                   5598:     } else {
                   5599:         &logthis("<font color=\"blue\">WARNING: ".
                   5600:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5601:                  "</font>");
                   5602:     }
                   5603: 
                   5604:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5605:                          &escape('Checkout '.$infostr.' - '.
                   5606:                                                  $token)) ne 'ok') {
                   5607:         return '';
                   5608:     } else {
                   5609:         &logthis("<font color=\"blue\">WARNING: ".
                   5610:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5611:                  "</font>");
                   5612:     }
                   5613:     return $token;
                   5614: }
                   5615: 
                   5616: # ------------------------------------------------------------ Check in an item
                   5617: 
                   5618: sub checkin {
                   5619:     my $token=shift;
                   5620:     my $now=time;
                   5621:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5622:     $lonhost=~tr/A-Z/a-z/;
                   5623:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5624:     $dtoken=~s/\W/\_/g;
1.1172.2.118.  .14(raeb 5625:-21):     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5626:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5627:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5628: 
                   5629:     unless (($tuname) && ($tudom)) {
                   5630:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5631:         return '';
                   5632:     }
                   5633: 
                   5634:     unless (&allowed('mgr',$tcrsid)) {
                   5635:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5636:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5637:         return '';
                   5638:     }
                   5639: 
                   5640:     my %infohash=('resource.0.intoken' => $token,
                   5641:                   'resource.0.checkintime' => $now,
1.1172.2.118.  .14(raeb 5642:-21):                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5643: 
                   5644:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5645:        return '';
                   5646:     }
                   5647: 
                   5648:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5649:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5650:         return '';
                   5651:     }
                   5652: 
                   5653:     return ($symb,$tuname,$tudom,$tcrsid);
                   5654: }
                   5655: 
1.110     www      5656: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5657: 
                   5658: sub expirespread {
                   5659:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5660:     my $cid=$env{'request.course.id'}; 
1.110     www      5661:     if ($cid) {
                   5662:        my $now=time;
                   5663:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5664:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5665:                             $env{'course.'.$cid.'.num'}.
1.110     www      5666: 	        	    ':nohist_expirationdates:'.
                   5667:                             &escape($key).'='.$now,
1.620     albertel 5668:                             $env{'course.'.$cid.'.home'})
1.110     www      5669:     }
                   5670:     return 'ok';
1.14      www      5671: }
                   5672: 
1.109     www      5673: # ----------------------------------------------------- Devalidate Spreadsheets
                   5674: 
                   5675: sub devalidate {
1.325     www      5676:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5677:     my $cid=$env{'request.course.id'}; 
1.109     www      5678:     if ($cid) {
1.391     matthew  5679:         # delete the stored spreadsheets for
                   5680:         # - the student level sheet of this user in course's homespace
                   5681:         # - the assessment level sheet for this resource 
                   5682:         #   for this user in user's homespace
1.553     albertel 5683: 	# - current conditional state info
1.325     www      5684: 	my $key=$uname.':'.$udom.':';
1.109     www      5685:         my $status=
1.299     matthew  5686: 	    &del('nohist_calculatedsheets',
1.391     matthew  5687: 		 [$key.'studentcalc:'],
1.620     albertel 5688: 		 $env{'course.'.$cid.'.domain'},
                   5689: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5690: 		.' '.
                   5691: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5692: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5693:         unless ($status eq 'ok ok') {
                   5694:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5695:                     $uname.' at '.$udom.' for '.
1.109     www      5696: 		    $symb.': '.$status);
1.133     albertel 5697:         }
1.553     albertel 5698: 	&delenv('user.state.'.$cid);
1.109     www      5699:     }
                   5700: }
                   5701: 
1.265     albertel 5702: sub get_scalar {
                   5703:     my ($string,$end) = @_;
                   5704:     my $value;
                   5705:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5706: 	$value = $1;
                   5707:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5708: 	$value = $1;
                   5709:     }
                   5710:     return &unescape($value);
                   5711: }
                   5712: 
                   5713: sub array2str {
                   5714:   my (@array) = @_;
                   5715:   my $result=&arrayref2str(\@array);
                   5716:   $result=~s/^__ARRAY_REF__//;
                   5717:   $result=~s/__END_ARRAY_REF__$//;
                   5718:   return $result;
                   5719: }
                   5720: 
1.204     albertel 5721: sub arrayref2str {
                   5722:   my ($arrayref) = @_;
1.265     albertel 5723:   my $result='__ARRAY_REF__';
1.204     albertel 5724:   foreach my $elem (@$arrayref) {
1.265     albertel 5725:     if(ref($elem) eq 'ARRAY') {
                   5726:       $result.=&arrayref2str($elem).'&';
                   5727:     } elsif(ref($elem) eq 'HASH') {
                   5728:       $result.=&hashref2str($elem).'&';
                   5729:     } elsif(ref($elem)) {
                   5730:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5731:     } else {
                   5732:       $result.=&escape($elem).'&';
                   5733:     }
                   5734:   }
                   5735:   $result=~s/\&$//;
1.265     albertel 5736:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5737:   return $result;
                   5738: }
                   5739: 
1.168     albertel 5740: sub hash2str {
1.204     albertel 5741:   my (%hash) = @_;
                   5742:   my $result=&hashref2str(\%hash);
1.265     albertel 5743:   $result=~s/^__HASH_REF__//;
                   5744:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5745:   return $result;
                   5746: }
                   5747: 
                   5748: sub hashref2str {
                   5749:   my ($hashref)=@_;
1.265     albertel 5750:   my $result='__HASH_REF__';
1.800     albertel 5751:   foreach my $key (sort(keys(%$hashref))) {
                   5752:     if (ref($key) eq 'ARRAY') {
                   5753:       $result.=&arrayref2str($key).'=';
                   5754:     } elsif (ref($key) eq 'HASH') {
                   5755:       $result.=&hashref2str($key).'=';
                   5756:     } elsif (ref($key)) {
1.265     albertel 5757:       $result.='=';
1.800     albertel 5758:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5759:     } else {
1.1132    raeburn  5760: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5761:     }
                   5762: 
1.800     albertel 5763:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5764:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5765:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5766:       $result.=&hashref2str($hashref->{$key}).'&';
                   5767:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5768:        $result.='&';
1.800     albertel 5769:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5770:     } else {
1.800     albertel 5771:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5772:     }
                   5773:   }
1.168     albertel 5774:   $result=~s/\&$//;
1.265     albertel 5775:   $result .= '__END_HASH_REF__';
1.168     albertel 5776:   return $result;
                   5777: }
                   5778: 
                   5779: sub str2hash {
1.265     albertel 5780:     my ($string)=@_;
                   5781:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5782:     return %$hash;
                   5783: }
                   5784: 
                   5785: sub str2hashref {
1.168     albertel 5786:   my ($string) = @_;
1.265     albertel 5787: 
                   5788:   my %hash;
                   5789: 
                   5790:   if($string !~ /^__HASH_REF__/) {
                   5791:       if (! ($string eq '' || !defined($string))) {
                   5792: 	  $hash{'error'}='Not hash reference';
                   5793:       }
                   5794:       return (\%hash, $string);
                   5795:   }
                   5796: 
                   5797:   $string =~ s/^__HASH_REF__//;
                   5798: 
                   5799:   while($string !~ /^__END_HASH_REF__/) {
                   5800:       #key
                   5801:       my $key='';
                   5802:       if($string =~ /^__HASH_REF__/) {
                   5803:           ($key, $string)=&str2hashref($string);
                   5804:           if(defined($key->{'error'})) {
                   5805:               $hash{'error'}='Bad data';
                   5806:               return (\%hash, $string);
                   5807:           }
                   5808:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5809:           ($key, $string)=&str2arrayref($string);
                   5810:           if($key->[0] eq 'Array reference error') {
                   5811:               $hash{'error'}='Bad data';
                   5812:               return (\%hash, $string);
                   5813:           }
                   5814:       } else {
                   5815:           $string =~ s/^(.*?)=//;
1.267     albertel 5816: 	  $key=&unescape($1);
1.265     albertel 5817:       }
                   5818:       $string =~ s/^=//;
                   5819: 
                   5820:       #value
                   5821:       my $value='';
                   5822:       if($string =~ /^__HASH_REF__/) {
                   5823:           ($value, $string)=&str2hashref($string);
                   5824:           if(defined($value->{'error'})) {
                   5825:               $hash{'error'}='Bad data';
                   5826:               return (\%hash, $string);
                   5827:           }
                   5828:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5829:           ($value, $string)=&str2arrayref($string);
                   5830:           if($value->[0] eq 'Array reference error') {
                   5831:               $hash{'error'}='Bad data';
                   5832:               return (\%hash, $string);
                   5833:           }
                   5834:       } else {
                   5835: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5836:       }
                   5837:       $string =~ s/^&//;
                   5838: 
                   5839:       $hash{$key}=$value;
1.204     albertel 5840:   }
1.265     albertel 5841: 
                   5842:   $string =~ s/^__END_HASH_REF__//;
                   5843: 
                   5844:   return (\%hash, $string);
1.204     albertel 5845: }
                   5846: 
                   5847: sub str2array {
1.265     albertel 5848:     my ($string)=@_;
                   5849:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5850:     return @$array;
                   5851: }
                   5852: 
                   5853: sub str2arrayref {
1.204     albertel 5854:   my ($string) = @_;
1.265     albertel 5855:   my @array;
                   5856: 
                   5857:   if($string !~ /^__ARRAY_REF__/) {
                   5858:       if (! ($string eq '' || !defined($string))) {
                   5859: 	  $array[0]='Array reference error';
                   5860:       }
                   5861:       return (\@array, $string);
                   5862:   }
                   5863: 
                   5864:   $string =~ s/^__ARRAY_REF__//;
                   5865: 
                   5866:   while($string !~ /^__END_ARRAY_REF__/) {
                   5867:       my $value='';
                   5868:       if($string =~ /^__HASH_REF__/) {
                   5869:           ($value, $string)=&str2hashref($string);
                   5870:           if(defined($value->{'error'})) {
                   5871:               $array[0] ='Array reference error';
                   5872:               return (\@array, $string);
                   5873:           }
                   5874:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5875:           ($value, $string)=&str2arrayref($string);
                   5876:           if($value->[0] eq 'Array reference error') {
                   5877:               $array[0] ='Array reference error';
                   5878:               return (\@array, $string);
                   5879:           }
                   5880:       } else {
                   5881: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5882:       }
                   5883:       $string =~ s/^&//;
                   5884: 
                   5885:       push(@array, $value);
1.191     harris41 5886:   }
1.265     albertel 5887: 
                   5888:   $string =~ s/^__END_ARRAY_REF__//;
                   5889: 
                   5890:   return (\@array, $string);
1.168     albertel 5891: }
                   5892: 
1.167     albertel 5893: # -------------------------------------------------------------------Temp Store
                   5894: 
1.168     albertel 5895: sub tmpreset {
                   5896:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5897:   if (!$symb) {
                   5898:     $symb=&symbread();
1.620     albertel 5899:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5900:   }
                   5901:   $symb=escape($symb);
                   5902: 
1.620     albertel 5903:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5904:   $namespace=~s/\//\_/g;
                   5905:   $namespace=~s/\W//g;
                   5906: 
1.620     albertel 5907:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5908:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5909:   if ($domain eq 'public' && $stuname eq 'public') {
                   5910:       $stuname=$ENV{'REMOTE_ADDR'};
                   5911:   }
1.1117    foxr     5912:   my $path=LONCAPA::tempdir();
1.168     albertel 5913:   my %hash;
                   5914:   if (tie(%hash,'GDBM_File',
                   5915: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5916: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5917:     foreach my $key (keys(%hash)) {
1.180     albertel 5918:       if ($key=~ /:$symb/) {
1.168     albertel 5919: 	delete($hash{$key});
                   5920:       }
                   5921:     }
                   5922:   }
                   5923: }
                   5924: 
1.167     albertel 5925: sub tmpstore {
1.168     albertel 5926:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5927: 
                   5928:   if (!$symb) {
                   5929:     $symb=&symbread();
1.620     albertel 5930:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5931:   }
                   5932:   $symb=escape($symb);
                   5933: 
                   5934:   if (!$namespace) {
                   5935:     # I don't think we would ever want to store this for a course.
                   5936:     # it seems this will only be used if we don't have a course.
1.620     albertel 5937:     #$namespace=$env{'request.course.id'};
1.168     albertel 5938:     #if (!$namespace) {
1.620     albertel 5939:       $namespace=$env{'request.state'};
1.168     albertel 5940:     #}
                   5941:   }
                   5942:   $namespace=~s/\//\_/g;
                   5943:   $namespace=~s/\W//g;
1.620     albertel 5944:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5945:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5946:   if ($domain eq 'public' && $stuname eq 'public') {
                   5947:       $stuname=$ENV{'REMOTE_ADDR'};
                   5948:   }
1.168     albertel 5949:   my $now=time;
                   5950:   my %hash;
1.1117    foxr     5951:   my $path=LONCAPA::tempdir();
1.168     albertel 5952:   if (tie(%hash,'GDBM_File',
                   5953: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5954: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5955:     $hash{"version:$symb"}++;
                   5956:     my $version=$hash{"version:$symb"};
                   5957:     my $allkeys=''; 
                   5958:     foreach my $key (keys(%$storehash)) {
                   5959:       $allkeys.=$key.':';
1.591     albertel 5960:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5961:     }
                   5962:     $hash{"$version:$symb:timestamp"}=$now;
                   5963:     $allkeys.='timestamp';
                   5964:     $hash{"$version:keys:$symb"}=$allkeys;
                   5965:     if (untie(%hash)) {
                   5966:       return 'ok';
                   5967:     } else {
                   5968:       return "error:$!";
                   5969:     }
                   5970:   } else {
                   5971:     return "error:$!";
                   5972:   }
                   5973: }
1.167     albertel 5974: 
1.168     albertel 5975: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5976: 
1.168     albertel 5977: sub tmprestore {
                   5978:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5979: 
1.168     albertel 5980:   if (!$symb) {
                   5981:     $symb=&symbread();
1.620     albertel 5982:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5983:   }
                   5984:   $symb=escape($symb);
                   5985: 
1.620     albertel 5986:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5987: 
1.620     albertel 5988:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5989:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5990:   if ($domain eq 'public' && $stuname eq 'public') {
                   5991:       $stuname=$ENV{'REMOTE_ADDR'};
                   5992:   }
1.168     albertel 5993:   my %returnhash;
                   5994:   $namespace=~s/\//\_/g;
                   5995:   $namespace=~s/\W//g;
                   5996:   my %hash;
1.1117    foxr     5997:   my $path=LONCAPA::tempdir();
1.168     albertel 5998:   if (tie(%hash,'GDBM_File',
                   5999: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6000: 	  &GDBM_READER(),0640)) {
1.168     albertel 6001:     my $version=$hash{"version:$symb"};
                   6002:     $returnhash{'version'}=$version;
                   6003:     my $scope;
                   6004:     for ($scope=1;$scope<=$version;$scope++) {
                   6005:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6006:       my @keys=split(/:/,$vkeys);
                   6007:       my $key;
                   6008:       $returnhash{"$scope:keys"}=$vkeys;
                   6009:       foreach $key (@keys) {
1.591     albertel 6010: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6011: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6012:       }
                   6013:     }
1.168     albertel 6014:     if (!(untie(%hash))) {
                   6015:       return "error:$!";
                   6016:     }
                   6017:   } else {
                   6018:     return "error:$!";
                   6019:   }
                   6020:   return %returnhash;
1.167     albertel 6021: }
                   6022: 
1.9       www      6023: # ----------------------------------------------------------------------- Store
                   6024: 
                   6025: sub store {
1.1172.2.64  raeburn  6026:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6027:     my $home='';
                   6028: 
1.168     albertel 6029:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6030: 
1.213     www      6031:     $symb=&symbclean($symb);
1.122     albertel 6032:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6033: 
1.620     albertel 6034:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6035:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6036: 
                   6037:     &devalidate($symb,$stuname,$domain);
1.109     www      6038: 
                   6039:     $symb=escape($symb);
1.187     www      6040:     if (!$namespace) { 
1.620     albertel 6041:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6042:           return ''; 
                   6043:        } 
                   6044:     }
1.620     albertel 6045:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6046: 
                   6047:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6048:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6049: 
1.12      www      6050:     my $namevalue='';
1.800     albertel 6051:     foreach my $key (keys(%$storehash)) {
                   6052:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6053:     }
1.12      www      6054:     $namevalue=~s/\&$//;
1.187     www      6055:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6056:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6057: }
                   6058: 
1.47      www      6059: # -------------------------------------------------------------- Critical Store
                   6060: 
                   6061: sub cstore {
1.1172.2.64  raeburn  6062:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6063:     my $home='';
                   6064: 
1.168     albertel 6065:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6066: 
1.213     www      6067:     $symb=&symbclean($symb);
1.122     albertel 6068:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6069: 
1.620     albertel 6070:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6071:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6072: 
                   6073:     &devalidate($symb,$stuname,$domain);
1.109     www      6074: 
                   6075:     $symb=escape($symb);
1.187     www      6076:     if (!$namespace) { 
1.620     albertel 6077:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6078:           return ''; 
                   6079:        } 
                   6080:     }
1.620     albertel 6081:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6082: 
                   6083:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6084:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6085: 
1.47      www      6086:     my $namevalue='';
1.800     albertel 6087:     foreach my $key (keys(%$storehash)) {
                   6088:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6089:     }
1.47      www      6090:     $namevalue=~s/\&$//;
1.187     www      6091:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6092:     return critical
1.1172.2.64  raeburn  6093:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6094: }
                   6095: 
1.9       www      6096: # --------------------------------------------------------------------- Restore
                   6097: 
                   6098: sub restore {
1.124     www      6099:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6100:     my $home='';
                   6101: 
1.168     albertel 6102:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6103: 
1.122     albertel 6104:     if (!$symb) {
1.1172.2.26  raeburn  6105:         return if ($namespace eq 'courserequests');
                   6106:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6107:     } else {
1.1172.2.26  raeburn  6108:         unless ($namespace eq 'courserequests') {
                   6109:             $symb=&escape(&symbclean($symb));
                   6110:         }
1.122     albertel 6111:     }
1.188     www      6112:     if (!$namespace) { 
1.620     albertel 6113:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6114:           return ''; 
                   6115:        } 
                   6116:     }
1.620     albertel 6117:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6118:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6119:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6120:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6121: 
1.12      www      6122:     my %returnhash=();
1.800     albertel 6123:     foreach my $line (split(/\&/,$answer)) {
                   6124: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6125:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6126:     }
1.75      www      6127:     my $version;
                   6128:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6129:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6130:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6131:        }
1.75      www      6132:     }
1.13      www      6133:     return %returnhash;
1.34      www      6134: }
                   6135: 
                   6136: # ---------------------------------------------------------- Course Description
1.1118    foxr     6137: #
                   6138: #  
1.34      www      6139: 
                   6140: sub coursedescription {
1.731     albertel 6141:     my ($courseid,$args)=@_;
1.34      www      6142:     $courseid=~s/^\///;
1.49      www      6143:     $courseid=~s/\_/\//g;
1.34      www      6144:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6145:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6146:     my $normalid=$cdomain.'_'.$cnum;
                   6147:     # need to always cache even if we get errors otherwise we keep 
                   6148:     # trying and trying and trying to get the course description.
                   6149:     my %envhash=();
                   6150:     my %returnhash=();
1.731     albertel 6151:     
                   6152:     my $expiretime=600;
                   6153:     if ($env{'request.course.id'} eq $normalid) {
                   6154: 	$expiretime=120;
                   6155:     }
                   6156: 
                   6157:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6158:     if (!$args->{'freshen_cache'}
                   6159: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6160: 	foreach my $key (keys(%env)) {
                   6161: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6162: 	    my ($setting) = $1;
                   6163: 	    $returnhash{$setting} = $env{$key};
                   6164: 	}
                   6165: 	return %returnhash;
                   6166:     }
                   6167: 
1.1118    foxr     6168:     # get the data again
                   6169: 
1.731     albertel 6170:     if (!$args->{'one_time'}) {
                   6171: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6172:     }
1.811     albertel 6173: 
1.34      www      6174:     if ($chome ne 'no_host') {
1.302     albertel 6175:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6176:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6177: 	   my $username = $env{'user.name'}; # Defult username
                   6178: 	   if(defined $args->{'user'}) {
                   6179: 	       $username = $args->{'user'};
                   6180: 	   }
1.129     albertel 6181:            $returnhash{'home'}= $chome;
                   6182: 	   $returnhash{'domain'} = $cdomain;
                   6183: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6184:            if (!defined($returnhash{'type'})) {
                   6185:                $returnhash{'type'} = 'Course';
                   6186:            }
1.130     albertel 6187:            while (my ($name,$value) = each %returnhash) {
1.53      www      6188:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6189:            }
1.270     www      6190:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6191:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6192: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6193:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6194:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6195:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6196:        }
                   6197:     }
1.731     albertel 6198:     if (!$args->{'one_time'}) {
1.949     raeburn  6199: 	&appenv(\%envhash);
1.731     albertel 6200:     }
1.302     albertel 6201:     return %returnhash;
1.461     www      6202: }
                   6203: 
1.1080    raeburn  6204: sub update_released_required {
                   6205:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6206:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6207:         $cid = $env{'request.course.id'};
                   6208:         $cdom = $env{'course.'.$cid.'.domain'};
                   6209:         $cnum = $env{'course.'.$cid.'.num'};
                   6210:         $chome = $env{'course.'.$cid.'.home'};
                   6211:     }
                   6212:     if ($needsrelease) {
                   6213:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6214:         my $needsupdate;
                   6215:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6216:             $needsupdate = 1;
                   6217:         } else {
                   6218:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6219:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6220:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6221:                 $needsupdate = 1;
                   6222:             }
                   6223:         }
                   6224:         if ($needsupdate) {
                   6225:             my %needshash = (
                   6226:                              'internal.releaserequired' => $needsrelease,
                   6227:                             );
                   6228:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6229:             if ($putresult eq 'ok') {
                   6230:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6231:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6232:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6233:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6234:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6235:                 }
                   6236:             }
                   6237:         }
                   6238:     }
                   6239:     return;
                   6240: }
                   6241: 
1.461     www      6242: # -------------------------------------------------See if a user is privileged
                   6243: 
                   6244: sub privileged {
1.1172.2.23  raeburn  6245:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6246:     my $now = time;
1.1172.2.23  raeburn  6247:     my $roles;
                   6248:     if (ref($possroles) eq 'ARRAY') {
                   6249:         $roles = $possroles;
                   6250:     } else {
                   6251:         $roles = ['dc','su'];
                   6252:     }
                   6253:     if (ref($possdomains) eq 'ARRAY') {
                   6254:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6255:         foreach my $dom (@{$possdomains}) {
                   6256:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6257:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6258:                 foreach my $role (@{$roles}) {
                   6259:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6260:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6261:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6262:                             return 1 unless (($end && $end < $now) ||
                   6263:                                              ($start && $start > $now));
                   6264:                         }
                   6265:                     }
                   6266:                 }
                   6267:             }
                   6268:         }
                   6269:     } else {
                   6270:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6271:         my $now = time;
1.1170    droeschl 6272: 
1.1172.2.58  raeburn  6273:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6274:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6275:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6276:                 return 1 unless ($tend && $tend < $now)
                   6277:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6278:             }
1.1172.2.23  raeburn  6279:         }
                   6280:     }
1.461     www      6281:     return 0;
1.9       www      6282: }
1.1       albertel 6283: 
1.1172.2.23  raeburn  6284: sub privileged_by_domain {
                   6285:     my ($domains,$roles) = @_;
                   6286:     my %privileged = ();
                   6287:     my $cachetime = 60*60*24;
                   6288:     my $now = time;
                   6289:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6290:         return %privileged;
                   6291:     }
                   6292:     foreach my $dom (@{$domains}) {
                   6293:         next if (ref($privileged{$dom}) eq 'HASH');
                   6294:         my $needroles;
                   6295:         foreach my $role (@{$roles}) {
                   6296:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6297:             if (defined($cached)) {
                   6298:                 if (ref($result) eq 'HASH') {
                   6299:                     $privileged{$dom}{$role} = $result;
                   6300:                 }
                   6301:             } else {
                   6302:                 $needroles = 1;
                   6303:             }
                   6304:         }
                   6305:         if ($needroles) {
                   6306:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6307:             $privileged{$dom} = {};
                   6308:             foreach my $server (keys(%dompersonnel)) {
                   6309:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6310:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6311:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6312:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6313:                         next if ($end && $end < $now);
                   6314:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6315:                             $dompersonnel{$server}{$item};
                   6316:                     }
                   6317:                 }
                   6318:             }
                   6319:             if (ref($privileged{$dom}) eq 'HASH') {
                   6320:                 foreach my $role (@{$roles}) {
                   6321:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6322:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6323:                     } else {
                   6324:                         my %hash = ();
                   6325:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6326:                     }
                   6327:                 }
                   6328:             }
                   6329:         }
                   6330:     }
                   6331:     return %privileged;
                   6332: }
                   6333: 
1.103     harris41 6334: # -------------------------------------------------------- Get user privileges
1.11      www      6335: 
                   6336: sub rolesinit {
1.1169    droeschl 6337:     my ($domain, $username) = @_;
                   6338:     my %userroles = ('user.login.time' => time);
                   6339:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6340: 
                   6341:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6342:     # also, blocking can be triggered by an activating timer
                   6343:     # it's saved in the user's %env.
                   6344:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6345:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6346:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6347:         %timerintchk, %timerintenv);
                   6348: 
1.1162    raeburn  6349:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6350:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6351:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6352:     }
1.1169    droeschl 6353: 
1.1162    raeburn  6354:     foreach my $key (keys(%timerinterval)) {
                   6355:         my ($cid,$rest) = split(/\0/,$key);
                   6356:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6357:     }
1.1169    droeschl 6358: 
1.11      www      6359:     my %allroles=();
1.1162    raeburn  6360:     my %allgroups=();
1.11      www      6361: 
1.1172.2.58  raeburn  6362:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6363:         my $role = $rolesdump{$area};
                   6364:         $area =~ s/\_\w\w$//;
                   6365: 
                   6366:         my ($trole, $tend, $tstart, $group_privs);
                   6367: 
                   6368:         if ($role =~ /^cr/) {
                   6369:         # Custom role, defined by a user 
                   6370:         # e.g., user.role.cr/msu/smith/mynewrole
                   6371:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6372:                 $trole = $1;
                   6373:                 ($tend, $tstart) = split('_', $2);
                   6374:             } else {
                   6375:                 $trole = $role;
                   6376:             }
                   6377:         } elsif ($role =~ m|^gr/|) {
                   6378:         # Role of member in a group, defined within a course/community
                   6379:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6380:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6381:             next if $tstart eq '-1';
                   6382:             ($trole, $group_privs) = split(/\//, $trole);
                   6383:             $group_privs = &unescape($group_privs);
                   6384:         } else {
                   6385:         # Just a normal role, defined in roles.tab
                   6386:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6387:         }
                   6388: 
                   6389:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6390:                  $username);
                   6391:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6392: 
                   6393:         # role expired or not available yet?
                   6394:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6395:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6396: 
                   6397:         next if $area eq '' or $trole eq '';
                   6398: 
                   6399:         my $spec = "$trole.$area";
                   6400:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6401: 
                   6402:         if ($trole =~ /^cr\//) {
                   6403:         # Custom role, defined by a user
                   6404:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6405:         } elsif ($trole eq 'gr') {
                   6406:         # Role of a member in a group, defined within a course/community
                   6407:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6408:             next;
                   6409:         } else {
                   6410:         # Normal role, defined in roles.tab
                   6411:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6412:         }
                   6413: 
                   6414:         my $cid = $tdomain.'_'.$trest;
                   6415:         unless ($firstaccchk{$cid}) {
                   6416:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6417:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6418:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6419:                         $coursetimerstarts{$cid}{$item}; 
                   6420:                 }
                   6421:             }
                   6422:             $firstaccchk{$cid} = 1;
                   6423:         }
                   6424:         unless ($timerintchk{$cid}) {
                   6425:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6426:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6427:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6428:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6429:                 }
1.12      www      6430:             }
1.1169    droeschl 6431:             $timerintchk{$cid} = 1;
1.191     harris41 6432:         }
1.11      www      6433:     }
1.1169    droeschl 6434: 
1.1172.2.91  raeburn  6435:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6436:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6437:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6438:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6439: 
1.1162    raeburn  6440:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6441: }
                   6442: 
1.567     raeburn  6443: sub set_arearole {
1.1172.2.19  raeburn  6444:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6445:     unless ($nolog) {
1.567     raeburn  6446: # log the associated role with the area
1.1172.2.19  raeburn  6447:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6448:     }
1.743     albertel 6449:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6450: }
                   6451: 
                   6452: sub custom_roleprivs {
                   6453:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6454:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6455:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6456:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6457:         my ($rdummy,$roledef)=
                   6458:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6459:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6460:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6461:             if (defined($syspriv)) {
1.1043    raeburn  6462:                 if ($trest =~ /^$match_community$/) {
                   6463:                     $syspriv =~ s/bre\&S//; 
                   6464:                 }
1.567     raeburn  6465:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6466:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6467:             }
                   6468:             if ($tdomain ne '') {
                   6469:                 if (defined($dompriv)) {
                   6470:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6471:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6472:                 }
                   6473:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6474:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6475:                         my $rolename = $1;
                   6476:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6477:                     }
1.567     raeburn  6478:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6479:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6480:                 }
                   6481:             }
                   6482:         }
                   6483:     }
                   6484: }
                   6485: 
1.1172.2.89  raeburn  6486: sub course_adhocrole_privs {
                   6487:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6488:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6489:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6490:         my (%currprivs,%storeprivs);
                   6491:         foreach my $item (split(/:/,$coursepriv)) {
                   6492:             my ($priv,$restrict) = split(/\&/,$item);
                   6493:             $currprivs{$priv} = $restrict;
                   6494:         }
                   6495:         my (%possadd,%possremove,%full);
                   6496:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6497:             my ($priv,$restrict)=split(/\&/,$item);
                   6498:             $full{$priv} = $restrict;
                   6499:         }
                   6500:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6501:              next if ($item eq '');
                   6502:              my ($rule,$rest) = split(/=/,$item);
                   6503:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6504:              foreach my $priv (split(/:/,$rest)) {
                   6505:                  if ($priv ne '') {
                   6506:                      if ($rule eq 'off') {
                   6507:                          $possremove{$priv} = 1;
                   6508:                      } else {
                   6509:                          $possadd{$priv} = 1;
                   6510:                      }
                   6511:                  }
                   6512:              }
                   6513:          }
                   6514:          foreach my $priv (sort(keys(%full))) {
                   6515:              if (exists($currprivs{$priv})) {
                   6516:                  unless (exists($possremove{$priv})) {
                   6517:                      $storeprivs{$priv} = $currprivs{$priv};
                   6518:                  }
                   6519:              } elsif (exists($possadd{$priv})) {
                   6520:                  $storeprivs{$priv} = $full{$priv};
                   6521:              }
                   6522:          }
                   6523:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6524:      }
                   6525:      return $coursepriv;
                   6526: }
                   6527: 
1.678     raeburn  6528: sub group_roleprivs {
                   6529:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6530:     my $access = 1;
                   6531:     my $now = time;
                   6532:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6533:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6534:     if ($access) {
1.811     albertel 6535:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6536:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6537:     }
                   6538: }
1.567     raeburn  6539: 
                   6540: sub standard_roleprivs {
                   6541:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6542:     if (defined($pr{$trole.':s'})) {
                   6543:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6544:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6545:     }
                   6546:     if ($tdomain ne '') {
                   6547:         if (defined($pr{$trole.':d'})) {
                   6548:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6549:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6550:         }
                   6551:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6552:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6553:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6554:         }
                   6555:     }
                   6556: }
                   6557: 
                   6558: sub set_userprivs {
1.1064    raeburn  6559:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6560:     my $author=0;
                   6561:     my $adv=0;
1.1172.2.91  raeburn  6562:     my $rar=0;
1.678     raeburn  6563:     my %grouproles = ();
                   6564:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6565:         my @groupkeys; 
1.1000    raeburn  6566:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6567:             push(@groupkeys,$role);
                   6568:         }
                   6569:         if (ref($groups_roles) eq 'HASH') {
                   6570:             foreach my $key (keys(%{$groups_roles})) {
                   6571:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6572:                     push(@groupkeys,$key);
                   6573:                 }
                   6574:             }
                   6575:         }
                   6576:         if (@groupkeys > 0) {
                   6577:             foreach my $role (@groupkeys) {
                   6578:                 my ($trole,$area,$sec,$extendedarea);
                   6579:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6580:                     $trole = $1;
                   6581:                     $area = $2;
                   6582:                     $sec = $3;
                   6583:                     $extendedarea = $area.$sec;
                   6584:                     if (exists($$allgroups{$area})) {
                   6585:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6586:                             my $spec = $trole.'.'.$extendedarea;
                   6587:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6588:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6589:                         }
1.678     raeburn  6590:                     }
                   6591:                 }
                   6592:             }
                   6593:         }
                   6594:     }
1.800     albertel 6595:     foreach my $group (keys(%grouproles)) {
                   6596:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6597:     }
1.800     albertel 6598:     foreach my $role (keys(%{$allroles})) {
                   6599:         my %thesepriv;
1.941     raeburn  6600:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6601:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6602:             if ($item ne '') {
                   6603:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6604:                 if ($restrictions eq '') {
                   6605:                     $thesepriv{$privilege}='F';
                   6606:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6607:                     $thesepriv{$privilege}.=$restrictions;
                   6608:                 }
                   6609:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6610:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6611:             }
                   6612:         }
                   6613:         my $thesestr='';
1.1104    raeburn  6614:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6615: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6616: 	}
                   6617:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6618:     }
1.1172.2.91  raeburn  6619:     return ($author,$adv,$rar);
1.567     raeburn  6620: }
                   6621: 
1.994     raeburn  6622: sub role_status {
1.1104    raeburn  6623:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6624:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6625:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6626:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6627:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6628:             $$where = '/'.$two;
1.994     raeburn  6629:             $$trolecode=$$role.'.'.$$where;
                   6630:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6631:             $$tstatus='is';
1.1104    raeburn  6632:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6633:                 $$tstatus='future';
1.1034    raeburn  6634:                 if ($$tstart<$now) {
                   6635:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6636:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6637:                             my (%allroles,%allgroups,$group_privs,
                   6638:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6639:                             my %userroles = (
                   6640:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6641:                             );
1.1064    raeburn  6642:                             @rolecodes = ('cm'); 
1.1002    raeburn  6643:                             my $spec=$$role.'.'.$$where;
                   6644:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6645:                             if ($$role =~ /^cr\//) {
                   6646:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6647:                                 push(@rolecodes,'cr');
1.1002    raeburn  6648:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6649:                                 push(@rolecodes,$$role);
1.1002    raeburn  6650:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6651:                                                     $env{'user.name'});
1.1064    raeburn  6652:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6653:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6654:                                 $group_privs = &unescape($group_privs);
                   6655:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6656:                                 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  6657:                                 &get_groups_roles($tdomain,$trest,
                   6658:                                                   \%course_roles,\@rolecodes,
                   6659:                                                   \%groups_roles);
1.1002    raeburn  6660:                             } else {
1.1064    raeburn  6661:                                 push(@rolecodes,$$role);
1.1002    raeburn  6662:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6663:                             }
1.1172.2.91  raeburn  6664:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6665:                                                                    \%groups_roles);
1.1064    raeburn  6666:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6667:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6668:                         }
                   6669:                     }
1.1034    raeburn  6670:                     $$tstatus = 'is';
1.1002    raeburn  6671:                 }
1.994     raeburn  6672:             }
                   6673:             if ($$tend) {
1.1104    raeburn  6674:                 if ($$tend<$update) {
1.994     raeburn  6675:                     $$tstatus='expired';
                   6676:                 } elsif ($$tend<$now) {
                   6677:                     $$tstatus='will_not';
                   6678:                 }
                   6679:             }
                   6680:         }
                   6681:     }
                   6682: }
                   6683: 
1.1104    raeburn  6684: sub get_groups_roles {
                   6685:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6686:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6687:                   (ref($rolecodes) eq 'ARRAY') && 
                   6688:                   (ref($groups_roles) eq 'HASH')); 
                   6689:     if (keys(%{$cdom_courseroles}) > 0) {
                   6690:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6691:         if ($cdom ne '' && $cnum ne '') {
                   6692:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6693:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6694:                     my $crsrole = $1;
                   6695:                     my $crssec = $2;
                   6696:                     if ($crsrole =~ /^cr/) {
                   6697:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6698:                             push(@{$rolecodes},'cr');
                   6699:                         }
                   6700:                     } else {
                   6701:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6702:                             push(@{$rolecodes},$crsrole);
                   6703:                         }
                   6704:                     }
                   6705:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6706:                     if ($crssec ne '') {
                   6707:                         $rolekey .= "/$crssec";
                   6708:                     }
                   6709:                     $rolekey .= './';
                   6710:                     $groups_roles->{$rolekey} = $rolecodes;
                   6711:                 }
                   6712:             }
                   6713:         }
                   6714:     }
                   6715:     return;
                   6716: }
                   6717: 
                   6718: sub delete_env_groupprivs {
                   6719:     my ($where,$courseroles,$possroles) = @_;
                   6720:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6721:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6722:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6723:         %{$courseroles->{$udom}} =
                   6724:             &get_my_roles('','','userroles',['active'],
                   6725:                           $possroles,[$udom],1);
                   6726:     }
                   6727:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6728:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6729:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6730:             my $area = '/'.$cdom.'/'.$cnum;
                   6731:             my $privkey = "user.priv.$crsrole.$area";
                   6732:             if ($crssec ne '') {
                   6733:                 $privkey .= '/'.$crssec;
                   6734:             }
                   6735:             $privkey .= ".$area/$group";
                   6736:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6737:         }
                   6738:     }
                   6739:     return;
                   6740: }
                   6741: 
1.994     raeburn  6742: sub check_adhoc_privs {
1.1172.2.86  raeburn  6743:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6744:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6745:     if ($sec) {
                   6746:         $cckey .= '/'.$sec;
                   6747:     }
1.1172.2.9  raeburn  6748:     my $setprivs;
1.994     raeburn  6749:     if ($env{$cckey}) {
                   6750:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6751:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6752:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6753:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6754:             $setprivs = 1;
1.994     raeburn  6755:         }
                   6756:     } else {
1.1172.2.87  raeburn  6757:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6758:         $setprivs = 1;
1.994     raeburn  6759:     }
1.1172.2.9  raeburn  6760:     return $setprivs;
1.994     raeburn  6761: }
                   6762: 
                   6763: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6764: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6765:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6766:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6767:     if ($sec ne '') {
                   6768:         $area .= '/'.$sec;
                   6769:     }
1.994     raeburn  6770:     my $spec = $role.'.'.$area;
                   6771:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6772:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6773:     my %rolehash = ();
1.1172.2.89  raeburn  6774:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6775:         my $rolename = $1;
1.1172.2.84  raeburn  6776:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6777:         my %domdef = &get_domain_defaults($dcdom);
                   6778:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6779:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6780:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6781:             }
                   6782:         }
1.1172.2.84  raeburn  6783:     } else {
                   6784:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6785:     }
1.1172.2.91  raeburn  6786:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6787:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6788:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6789:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6790:         &appenv( {'request.role'        => $spec,
                   6791:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6792:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6793:                  }
                   6794:                );
                   6795:         my $tadv=0;
                   6796:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6797:         &appenv({'request.role.adv'    => $tadv});
                   6798:     }
1.994     raeburn  6799: }
                   6800: 
1.12      www      6801: # --------------------------------------------------------------- get interface
                   6802: 
                   6803: sub get {
1.131     albertel 6804:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6805:    my $items='';
1.800     albertel 6806:    foreach my $item (@$storearr) {
                   6807:        $items.=&escape($item).'&';
1.191     harris41 6808:    }
1.12      www      6809:    $items=~s/\&$//;
1.620     albertel 6810:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6811:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6812:    my $uhome=&homeserver($uname,$udomain);
                   6813: 
1.133     albertel 6814:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6815:    my @pairs=split(/\&/,$rep);
1.273     albertel 6816:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6817:      return @pairs;
                   6818:    }
1.15      www      6819:    my %returnhash=();
1.42      www      6820:    my $i=0;
1.800     albertel 6821:    foreach my $item (@$storearr) {
                   6822:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6823:       $i++;
1.191     harris41 6824:    }
1.15      www      6825:    return %returnhash;
1.27      www      6826: }
                   6827: 
                   6828: # --------------------------------------------------------------- del interface
                   6829: 
                   6830: sub del {
1.133     albertel 6831:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6832:    my $items='';
1.800     albertel 6833:    foreach my $item (@$storearr) {
                   6834:        $items.=&escape($item).'&';
1.191     harris41 6835:    }
1.984     neumanie 6836: 
1.27      www      6837:    $items=~s/\&$//;
1.620     albertel 6838:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6839:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6840:    my $uhome=&homeserver($uname,$udomain);
                   6841:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6842: }
                   6843: 
                   6844: # -------------------------------------------------------------- dump interface
                   6845: 
1.1172.2.22  raeburn  6846: sub unserialize {
                   6847:     my ($rep, $escapedkeys) = @_;
                   6848: 
                   6849:     return {} if $rep =~ /^error/;
                   6850: 
                   6851:     my %returnhash=();
                   6852:     foreach my $item (split(/\&/,$rep)) {
                   6853:         my ($key, $value) = split(/=/, $item, 2);
                   6854:         $key = unescape($key) unless $escapedkeys;
                   6855:         next if $key =~ /^error: 2 /;
                   6856:         $returnhash{$key} = &thaw_unescape($value);
                   6857:     }
                   6858:     return \%returnhash;
                   6859: }
                   6860: 
                   6861: # see Lond::dump_with_regexp
                   6862: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6863: sub dump {
1.1172.2.22  raeburn  6864:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6865:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6866:     if (!$uname) { $uname=$env{'user.name'}; }
                   6867:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6868: 
1.1172.2.55  raeburn  6869:     if ($regexp) {
                   6870:         $regexp=&escape($regexp);
                   6871:     } else {
                   6872:         $regexp='.';
                   6873:     }
1.1172.2.22  raeburn  6874:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6875:         # user is hosted on this machine
1.1172.2.55  raeburn  6876:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6877:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6878:         return %{&unserialize($reply, $escapedkeys)};
                   6879:     }
1.1166    raeburn  6880:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6881:     my @pairs=split(/\&/,$rep);
                   6882:     my %returnhash=();
1.1098    foxr     6883:     if (!($rep =~ /^error/ )) {
                   6884: 	foreach my $item (@pairs) {
                   6885: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6886:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6887: 	    next if ($key =~ /^error: 2 /);
                   6888: 	    $returnhash{$key}=&thaw_unescape($value);
                   6889: 	}
1.755     albertel 6890:     }
                   6891:     return %returnhash;
1.407     www      6892: }
                   6893: 
1.1098    foxr     6894: 
1.717     albertel 6895: # --------------------------------------------------------- dumpstore interface
                   6896: 
                   6897: sub dumpstore {
                   6898:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6899:    # same as dump but keys must be escaped. They may contain colon separated
                   6900:    # lists of values that may themself contain colons (e.g. symbs).
                   6901:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6902: }
                   6903: 
1.407     www      6904: # -------------------------------------------------------------- keys interface
                   6905: 
                   6906: sub getkeys {
                   6907:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6908:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6909:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6910:    my $uhome=&homeserver($uname,$udomain);
                   6911:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6912:    my @keyarray=();
1.800     albertel 6913:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6914:       next if ($key =~ /^error: 2 /);
1.800     albertel 6915:       push(@keyarray,&unescape($key));
1.407     www      6916:    }
                   6917:    return @keyarray;
1.318     matthew  6918: }
                   6919: 
1.319     matthew  6920: # --------------------------------------------------------------- currentdump
                   6921: sub currentdump {
1.328     matthew  6922:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6923:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6924:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6925:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6926:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6927:    my $rep;
                   6928: 
                   6929:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6930:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6931:                    $courseid)));
                   6932:    } else {
                   6933:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6934:    }
                   6935: 
1.318     matthew  6936:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6937:    #
1.318     matthew  6938:    my %returnhash=();
1.319     matthew  6939:    #
1.1172.2.118.  .1(raebu 6940:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6941:        # an old lond will not know currentdump
                   6942:        # Do a dump and make it look like a currentdump
1.822     albertel 6943:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6944:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6945:        my %hash = @tmp;
                   6946:        @tmp=();
1.424     matthew  6947:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6948:    } else {
                   6949:        my @pairs=split(/\&/,$rep);
1.800     albertel 6950:        foreach my $pair (@pairs) {
                   6951:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6952:            my ($symb,$param) = split(/:/,$key);
                   6953:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6954:                                                         &thaw_unescape($value);
1.319     matthew  6955:        }
1.191     harris41 6956:    }
1.12      www      6957:    return %returnhash;
1.424     matthew  6958: }
                   6959: 
                   6960: sub convert_dump_to_currentdump{
                   6961:     my %hash = %{shift()};
                   6962:     my %returnhash;
                   6963:     # Code ripped from lond, essentially.  The only difference
                   6964:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6965:     # we might run in to problems with parameter names =~ /^v\./
                   6966:     while (my ($key,$value) = each(%hash)) {
                   6967:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6968: 	$symb  = &unescape($symb);
                   6969: 	$param = &unescape($param);
1.424     matthew  6970:         next if ($v eq 'version' || $symb eq 'keys');
                   6971:         next if (exists($returnhash{$symb}) &&
                   6972:                  exists($returnhash{$symb}->{$param}) &&
                   6973:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6974:         $returnhash{$symb}->{$param}=$value;
                   6975:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6976:     }
                   6977:     #
                   6978:     # Remove all of the keys in the hashes which keep track of
                   6979:     # the version of the parameter.
                   6980:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6981:         # use a foreach because we are going to delete from the hash.
                   6982:         foreach my $key (keys(%$param_hash)) {
                   6983:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6984:         }
                   6985:     }
                   6986:     return \%returnhash;
1.12      www      6987: }
                   6988: 
1.627     albertel 6989: # ------------------------------------------------------ critical inc interface
                   6990: 
                   6991: sub cinc {
                   6992:     return &inc(@_,'critical');
                   6993: }
                   6994: 
1.449     matthew  6995: # --------------------------------------------------------------- inc interface
                   6996: 
                   6997: sub inc {
1.627     albertel 6998:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6999:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7000:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7001:     my $uhome=&homeserver($uname,$udomain);
                   7002:     my $items='';
                   7003:     if (! ref($store)) {
                   7004:         # got a single value, so use that instead
                   7005:         $items = &escape($store).'=&';
                   7006:     } elsif (ref($store) eq 'SCALAR') {
                   7007:         $items = &escape($$store).'=&';        
                   7008:     } elsif (ref($store) eq 'ARRAY') {
                   7009:         $items = join('=&',map {&escape($_);} @{$store});
                   7010:     } elsif (ref($store) eq 'HASH') {
                   7011:         while (my($key,$value) = each(%{$store})) {
                   7012:             $items.= &escape($key).'='.&escape($value).'&';
                   7013:         }
                   7014:     }
                   7015:     $items=~s/\&$//;
1.627     albertel 7016:     if ($critical) {
                   7017: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7018:     } else {
                   7019: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7020:     }
1.449     matthew  7021: }
                   7022: 
1.12      www      7023: # --------------------------------------------------------------- put interface
                   7024: 
                   7025: sub put {
1.134     albertel 7026:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7027:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7028:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7029:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7030:    my $items='';
1.800     albertel 7031:    foreach my $item (keys(%$storehash)) {
                   7032:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7033:    }
1.12      www      7034:    $items=~s/\&$//;
1.134     albertel 7035:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7036: }
                   7037: 
1.631     albertel 7038: # ------------------------------------------------------------ newput interface
                   7039: 
                   7040: sub newput {
                   7041:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7042:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7043:    if (!$uname) { $uname=$env{'user.name'}; }
                   7044:    my $uhome=&homeserver($uname,$udomain);
                   7045:    my $items='';
                   7046:    foreach my $key (keys(%$storehash)) {
                   7047:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7048:    }
                   7049:    $items=~s/\&$//;
                   7050:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7051: }
                   7052: 
                   7053: # ---------------------------------------------------------  putstore interface
                   7054: 
1.524     raeburn  7055: sub putstore {
1.1172.2.59  raeburn  7056:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7057:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7058:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7059:    my $uhome=&homeserver($uname,$udomain);
                   7060:    my $items='';
1.715     albertel 7061:    foreach my $key (keys(%$storehash)) {
                   7062:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7063:    }
1.715     albertel 7064:    $items=~s/\&$//;
1.716     albertel 7065:    my $esc_symb=&escape($symb);
                   7066:    my $esc_v=&escape($version);
1.715     albertel 7067:    my $reply =
1.716     albertel 7068:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7069: 	      $uhome);
1.1172.2.59  raeburn  7070:    if (($tolog) && ($reply eq 'ok')) {
                   7071:        my $namevalue='';
                   7072:        foreach my $key (keys(%{$storehash})) {
                   7073:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7074:        }
1.1172.2.118.  .14(raeb 7075:-21):        my $ip = &get_requestor_ip();
                   7076:-21):        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7077:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7078:                      '&version='.$esc_v.
                   7079:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7080:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7081:    }
1.715     albertel 7082:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7083:        # gfall back to way things use to be done
1.715     albertel 7084:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7085: 			    $uname);
1.524     raeburn  7086:    }
1.715     albertel 7087:    return $reply;
                   7088: }
                   7089: 
                   7090: sub old_putstore {
1.716     albertel 7091:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7092:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7093:     if (!$uname) { $uname=$env{'user.name'}; }
                   7094:     my $uhome=&homeserver($uname,$udomain);
                   7095:     my %newstorehash;
1.800     albertel 7096:     foreach my $item (keys(%$storehash)) {
                   7097: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7098: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7099:     }
                   7100:     my $items='';
                   7101:     my %allitems = ();
1.800     albertel 7102:     foreach my $item (keys(%newstorehash)) {
                   7103: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7104: 	    my $key = $1.':keys:'.$2;
                   7105: 	    $allitems{$key} .= $3.':';
                   7106: 	}
1.800     albertel 7107: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7108:     }
1.800     albertel 7109:     foreach my $item (keys(%allitems)) {
                   7110: 	$allitems{$item} =~ s/\:$//;
                   7111: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7112:     }
                   7113:     $items=~s/\&$//;
                   7114:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7115: }
                   7116: 
1.47      www      7117: # ------------------------------------------------------ critical put interface
                   7118: 
                   7119: sub cput {
1.134     albertel 7120:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7121:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7122:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7123:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7124:    my $items='';
1.800     albertel 7125:    foreach my $item (keys(%$storehash)) {
                   7126:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7127:    }
1.47      www      7128:    $items=~s/\&$//;
1.134     albertel 7129:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7130: }
                   7131: 
                   7132: # -------------------------------------------------------------- eget interface
                   7133: 
                   7134: sub eget {
1.133     albertel 7135:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7136:    my $items='';
1.800     albertel 7137:    foreach my $item (@$storearr) {
                   7138:        $items.=&escape($item).'&';
1.191     harris41 7139:    }
1.12      www      7140:    $items=~s/\&$//;
1.620     albertel 7141:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7142:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7143:    my $uhome=&homeserver($uname,$udomain);
                   7144:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7145:    my @pairs=split(/\&/,$rep);
                   7146:    my %returnhash=();
1.42      www      7147:    my $i=0;
1.800     albertel 7148:    foreach my $item (@$storearr) {
                   7149:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7150:       $i++;
1.191     harris41 7151:    }
1.12      www      7152:    return %returnhash;
                   7153: }
                   7154: 
1.667     albertel 7155: # ------------------------------------------------------------ tmpput interface
                   7156: sub tmpput {
1.802     raeburn  7157:     my ($storehash,$server,$context)=@_;
1.667     albertel 7158:     my $items='';
1.800     albertel 7159:     foreach my $item (keys(%$storehash)) {
                   7160: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7161:     }
                   7162:     $items=~s/\&$//;
1.802     raeburn  7163:     if (defined($context)) {
                   7164:         $items .= ':'.&escape($context);
                   7165:     }
1.667     albertel 7166:     return &reply("tmpput:$items",$server);
                   7167: }
                   7168: 
                   7169: # ------------------------------------------------------------ tmpget interface
                   7170: sub tmpget {
1.688     albertel 7171:     my ($token,$server)=@_;
                   7172:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7173:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7174:     my %returnhash;
1.1172.2.85  raeburn  7175:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7176:         return %returnhash;
                   7177:     }
1.667     albertel 7178:     foreach my $item (split(/\&/,$rep)) {
                   7179: 	my ($key,$value)=split(/=/,$item);
                   7180: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7181:     }
                   7182:     return %returnhash;
                   7183: }
                   7184: 
1.1113    raeburn  7185: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7186: sub tmpdel {
                   7187:     my ($token,$server)=@_;
                   7188:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7189:     return &reply("tmpdel:$token",$server);
                   7190: }
                   7191: 
1.1172.2.13  raeburn  7192: # ------------------------------------------------------------ get_timebased_id
                   7193: 
                   7194: sub get_timebased_id {
                   7195:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7196:         $maxtries) = @_;
                   7197:     my ($newid,$error,$dellock);
                   7198:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7199:         return ('','ok','invalid call to get suffix');
                   7200:     }
                   7201: 
                   7202: # set defaults for any optional args for which values were not supplied
                   7203:     if ($who eq '') {
                   7204:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7205:     }
                   7206:     if (!$locktries) {
                   7207:         $locktries = 3;
                   7208:     }
                   7209:     if (!$maxtries) {
                   7210:         $maxtries = 10;
                   7211:     }
                   7212: 
                   7213:     if (($cdom eq '') || ($cnum eq '')) {
                   7214:         if ($env{'request.course.id'}) {
                   7215:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7216:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7217:         }
                   7218:         if (($cdom eq '') || ($cnum eq '')) {
                   7219:             return ('','ok','call to get suffix not in course context');
                   7220:         }
                   7221:     }
                   7222: 
                   7223: # construct locking item
                   7224:     my $lockhash = {
                   7225:                       $prefix."\0".'locked_'.$keyid => $who,
                   7226:                    };
                   7227:     my $tries = 0;
                   7228: 
                   7229: # attempt to get lock on nohist_$namespace file
                   7230:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7231:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7232:         $tries ++;
                   7233:         sleep 1;
                   7234:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7235:     }
                   7236: 
                   7237: # attempt to get unique identifier, based on current timestamp
                   7238:     if ($gotlock eq 'ok') {
                   7239:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7240:         my $id = time;
                   7241:         $newid = $id;
1.1172.2.56  raeburn  7242:         if ($idtype eq 'addcode') {
                   7243:             $newid .= &sixnum_code();
                   7244:         }
1.1172.2.13  raeburn  7245:         my $idtries = 0;
                   7246:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7247:             if ($idtype eq 'concat') {
                   7248:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7249:             } elsif ($idtype eq 'addcode') {
                   7250:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7251:             } else {
                   7252:                 $newid ++;
                   7253:             }
                   7254:             $idtries ++;
                   7255:         }
                   7256:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7257:             my %new_item =  (
                   7258:                               $prefix."\0".$newid => $who,
                   7259:                             );
                   7260:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7261:                                                  $cdom,$cnum);
                   7262:             if ($putresult ne 'ok') {
                   7263:                 undef($newid);
                   7264:                 $error = 'error saving new item: '.$putresult;
                   7265:             }
                   7266:         } else {
1.1172.2.56  raeburn  7267:              undef($newid);
1.1172.2.13  raeburn  7268:              $error = ('error: no unique suffix available for the new item ');
                   7269:         }
                   7270: #  remove lock
                   7271:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7272:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7273:     } else {
                   7274:         $error = "error: could not obtain lockfile\n";
                   7275:         $dellock = 'ok';
1.1172.2.58  raeburn  7276:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7277:             $dellock = 'nolock';
                   7278:         }
1.1172.2.13  raeburn  7279:     }
                   7280:     return ($newid,$dellock,$error);
                   7281: }
                   7282: 
1.1172.2.56  raeburn  7283: sub sixnum_code {
                   7284:     my $code;
                   7285:     for (0..6) {
                   7286:         $code .= int( rand(9) );
                   7287:     }
                   7288:     return $code;
                   7289: }
                   7290: 
1.765     albertel 7291: # -------------------------------------------------- portfolio access checking
                   7292: 
                   7293: sub portfolio_access {
1.1172.2.77  raeburn  7294:     my ($requrl,$clientip) = @_;
1.765     albertel 7295:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7296:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7297:     if ($result) {
                   7298:         my %setters;
                   7299:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7300:             my ($startblock,$endblock) =
                   7301:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7302:             if ($startblock && $endblock) {
                   7303:                 return 'B';
                   7304:             }
                   7305:         } else {
                   7306:             my ($startblock,$endblock) =
                   7307:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7308:             if ($startblock && $endblock) {
                   7309:                 return 'B';
                   7310:             }
                   7311:         }
                   7312:     }
1.765     albertel 7313:     if ($result eq 'ok') {
1.766     albertel 7314:        return 'F';
1.765     albertel 7315:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7316:        return 'A';
1.765     albertel 7317:     }
1.766     albertel 7318:     return '';
1.765     albertel 7319: }
                   7320: 
                   7321: sub get_portfolio_access {
1.1172.2.77  raeburn  7322:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7323: 
                   7324:     if (!ref($access_hash)) {
                   7325: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7326: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7327: 						   $file_name);
                   7328: 	$access_hash = $access_controls{$file_name};
                   7329:     }
                   7330: 
1.1172.2.77  raeburn  7331:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7332:     my $now = time;
                   7333:     if (ref($access_hash) eq 'HASH') {
                   7334:         foreach my $key (keys(%{$access_hash})) {
                   7335:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7336:             if ($start > $now) {
                   7337:                 next;
                   7338:             }
                   7339:             if ($end && $end<$now) {
                   7340:                 next;
                   7341:             }
                   7342:             if ($scope eq 'public') {
                   7343:                 $public = $key;
                   7344:                 last;
                   7345:             } elsif ($scope eq 'guest') {
                   7346:                 $guest = $key;
                   7347:             } elsif ($scope eq 'domains') {
                   7348:                 push(@domains,$key);
                   7349:             } elsif ($scope eq 'users') {
                   7350:                 push(@users,$key);
                   7351:             } elsif ($scope eq 'course') {
                   7352:                 push(@courses,$key);
                   7353:             } elsif ($scope eq 'group') {
                   7354:                 push(@groups,$key);
1.1172.2.77  raeburn  7355:             } elsif ($scope eq 'ip') {
                   7356:                 push(@ips,$key);
1.765     albertel 7357:             }
                   7358:         }
                   7359:         if ($public) {
                   7360:             return 'ok';
1.1172.2.77  raeburn  7361:         } elsif (@ips > 0) {
                   7362:             my $allowed;
                   7363:             foreach my $ipkey (@ips) {
                   7364:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7365:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7366:                         $allowed = 1;
                   7367:                         last;
                   7368:                     }
                   7369:                 }
                   7370:             }
                   7371:             if ($allowed) {
                   7372:                 return 'ok';
                   7373:             }
1.765     albertel 7374:         }
                   7375:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7376:             if ($guest) {
                   7377:                 return $guest;
                   7378:             }
                   7379:         } else {
                   7380:             if (@domains > 0) {
                   7381:                 foreach my $domkey (@domains) {
                   7382:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7383:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7384:                             return 'ok';
                   7385:                         }
                   7386:                     }
                   7387:                 }
                   7388:             }
                   7389:             if (@users > 0) {
                   7390:                 foreach my $userkey (@users) {
1.865     raeburn  7391:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7392:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7393:                             if (ref($item) eq 'HASH') {
                   7394:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7395:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7396:                                     return 'ok';
                   7397:                                 }
                   7398:                             }
                   7399:                         }
                   7400:                     } 
1.765     albertel 7401:                 }
                   7402:             }
                   7403:             my %roleshash;
                   7404:             my @courses_and_groups = @courses;
                   7405:             push(@courses_and_groups,@groups); 
                   7406:             if (@courses_and_groups > 0) {
                   7407:                 my (%allgroups,%allroles); 
                   7408:                 my ($start,$end,$role,$sec,$group);
                   7409:                 foreach my $envkey (%env) {
1.1060    raeburn  7410:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7411:                         my $cid = $2.'_'.$3; 
                   7412:                         if ($1 eq 'gr') {
                   7413:                             $group = $4;
                   7414:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7415:                         } else {
                   7416:                             if ($4 eq '') {
                   7417:                                 $sec = 'none';
                   7418:                             } else {
                   7419:                                 $sec = $4;
                   7420:                             }
                   7421:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7422:                         }
1.811     albertel 7423:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7424:                         my $cid = $2.'_'.$3;
                   7425:                         if ($4 eq '') {
                   7426:                             $sec = 'none';
                   7427:                         } else {
                   7428:                             $sec = $4;
                   7429:                         }
                   7430:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7431:                     }
                   7432:                 }
                   7433:                 if (keys(%allroles) == 0) {
                   7434:                     return;
                   7435:                 }
                   7436:                 foreach my $key (@courses_and_groups) {
                   7437:                     my %content = %{$$access_hash{$key}};
                   7438:                     my $cnum = $content{'number'};
                   7439:                     my $cdom = $content{'domain'};
                   7440:                     my $cid = $cdom.'_'.$cnum;
                   7441:                     if (!exists($allroles{$cid})) {
                   7442:                         next;
                   7443:                     }    
                   7444:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7445:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7446:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7447:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7448:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7449:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7450:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7451:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7452:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7453:                                         if (grep/^all$/,@sections) {
                   7454:                                             return 'ok';
                   7455:                                         } else {
                   7456:                                             if (grep/^$sec$/,@sections) {
                   7457:                                                 return 'ok';
                   7458:                                             }
                   7459:                                         }
                   7460:                                     }
                   7461:                                 }
                   7462:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7463:                                     if (grep/^none$/,@groups) {
                   7464:                                         return 'ok';
                   7465:                                     }
                   7466:                                 } else {
                   7467:                                     if (grep/^all$/,@groups) {
                   7468:                                         return 'ok';
                   7469:                                     } 
                   7470:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7471:                                         if (grep/^$group$/,@groups) {
                   7472:                                             return 'ok';
                   7473:                                         }
                   7474:                                     }
                   7475:                                 } 
                   7476:                             }
                   7477:                         }
                   7478:                     }
                   7479:                 }
                   7480:             }
                   7481:             if ($guest) {
                   7482:                 return $guest;
                   7483:             }
                   7484:         }
                   7485:     }
                   7486:     return;
                   7487: }
                   7488: 
                   7489: sub course_group_datechecker {
                   7490:     my ($dates,$now,$status) = @_;
                   7491:     my ($start,$end) = split(/\./,$dates);
                   7492:     if (!$start && !$end) {
                   7493:         return 'ok';
                   7494:     }
                   7495:     if (grep/^active$/,@{$status}) {
                   7496:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7497:             return 'ok';
                   7498:         }
                   7499:     }
                   7500:     if (grep/^previous$/,@{$status}) {
                   7501:         if ($end > $now ) {
                   7502:             return 'ok';
                   7503:         }
                   7504:     }
                   7505:     if (grep/^future$/,@{$status}) {
                   7506:         if ($start > $now) {
                   7507:             return 'ok';
                   7508:         }
                   7509:     }
                   7510:     return; 
                   7511: }
                   7512: 
                   7513: sub parse_portfolio_url {
                   7514:     my ($url) = @_;
                   7515: 
                   7516:     my ($type,$udom,$unum,$group,$file_name);
                   7517:     
1.823     albertel 7518:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7519: 	$type = 1;
                   7520:         $udom = $1;
                   7521:         $unum = $2;
                   7522:         $file_name = $3;
1.823     albertel 7523:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7524: 	$type = 2;
                   7525:         $udom = $1;
                   7526:         $unum = $2;
                   7527:         $group = $3;
                   7528:         $file_name = $3.'/'.$4;
                   7529:     }
                   7530:     if (wantarray) {
                   7531: 	return ($type,$udom,$unum,$file_name,$group);
                   7532:     }
                   7533:     return $type;
                   7534: }
                   7535: 
                   7536: sub is_portfolio_url {
                   7537:     my ($url) = @_;
                   7538:     return scalar(&parse_portfolio_url($url));
                   7539: }
                   7540: 
1.798     raeburn  7541: sub is_portfolio_file {
                   7542:     my ($file) = @_;
1.820     raeburn  7543:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7544:         return 1;
                   7545:     }
                   7546:     return;
                   7547: }
                   7548: 
1.976     raeburn  7549: sub usertools_access {
1.1084    raeburn  7550:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7551:     my ($access,%tools);
                   7552:     if ($context eq '') {
                   7553:         $context = 'tools';
                   7554:     }
                   7555:     if ($context eq 'requestcourses') {
                   7556:         %tools = (
                   7557:                       official   => 1,
                   7558:                       unofficial => 1,
1.1006    raeburn  7559:                       community  => 1,
1.1172.2.37  raeburn  7560:                       textbook   => 1,
1.985     raeburn  7561:                  );
1.1172.2.9  raeburn  7562:     } elsif ($context eq 'requestauthor') {
                   7563:         %tools = (
                   7564:                       requestauthor => 1,
                   7565:                  );
1.985     raeburn  7566:     } else {
                   7567:         %tools = (
                   7568:                       aboutme   => 1,
                   7569:                       blog      => 1,
1.1172.2.6  raeburn  7570:                       webdav    => 1,
1.985     raeburn  7571:                       portfolio => 1,
                   7572:                  );
                   7573:     }
1.976     raeburn  7574:     return if (!defined($tools{$tool}));
                   7575: 
1.1172.2.35  raeburn  7576:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7577:         $udom = $env{'user.domain'};
                   7578:         $uname = $env{'user.name'};
                   7579:     }
                   7580: 
1.978     raeburn  7581:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7582:         if ($action ne 'reload') {
1.985     raeburn  7583:             if ($context eq 'requestcourses') {
                   7584:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7585:             } elsif ($context eq 'requestauthor') {
                   7586:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7587:             } else {
                   7588:                 return $env{'environment.availabletools.'.$tool};
                   7589:             }
                   7590:         }
1.976     raeburn  7591:     }
                   7592: 
1.1172.2.9  raeburn  7593:     my ($toolstatus,$inststatus,$envkey);
                   7594:     if ($context eq 'requestauthor') {
                   7595:         $envkey = $context;
                   7596:     } else {
                   7597:         $envkey = $context.'.'.$tool;
                   7598:     }
1.976     raeburn  7599: 
1.985     raeburn  7600:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7601:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7602:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7603:         $inststatus = $env{'environment.inststatus'};
                   7604:     } else {
1.1084    raeburn  7605:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7606:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7607:             $inststatus = $userenvref->{'inststatus'};
                   7608:         } else {
1.1172.2.9  raeburn  7609:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7610:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7611:             $inststatus = $userenv{'inststatus'};
                   7612:         }
1.976     raeburn  7613:     }
                   7614: 
                   7615:     if ($toolstatus ne '') {
                   7616:         if ($toolstatus) {
                   7617:             $access = 1;
                   7618:         } else {
                   7619:             $access = 0;
                   7620:         }
                   7621:         return $access;
                   7622:     }
                   7623: 
1.1084    raeburn  7624:     my ($is_adv,%domdef);
                   7625:     if (ref($is_advref) eq 'HASH') {
                   7626:         $is_adv = $is_advref->{'is_adv'};
                   7627:     } else {
                   7628:         $is_adv = &is_advanced_user($udom,$uname);
                   7629:     }
                   7630:     if (ref($domdefref) eq 'HASH') {
                   7631:         %domdef = %{$domdefref};
                   7632:     } else {
                   7633:         %domdef = &get_domain_defaults($udom);
                   7634:     }
1.976     raeburn  7635:     if (ref($domdef{$tool}) eq 'HASH') {
                   7636:         if ($is_adv) {
                   7637:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7638:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7639:                     $access = 1;
                   7640:                 } else {
                   7641:                     $access = 0;
                   7642:                 }
                   7643:                 return $access;
                   7644:             }
                   7645:         }
                   7646:         if ($inststatus ne '') {
                   7647:             my ($hasaccess,$hasnoaccess);
                   7648:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7649:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7650:                     if ($domdef{$tool}{$affiliation}) {
                   7651:                         $hasaccess = 1;
                   7652:                     } else {
                   7653:                         $hasnoaccess = 1;
                   7654:                     }
                   7655:                 }
                   7656:             }
                   7657:             if ($hasaccess || $hasnoaccess) {
                   7658:                 if ($hasaccess) {
                   7659:                     $access = 1;
                   7660:                 } elsif ($hasnoaccess) {
                   7661:                     $access = 0; 
                   7662:                 }
                   7663:                 return $access;
                   7664:             }
                   7665:         } else {
                   7666:             if ($domdef{$tool}{'default'} ne '') {
                   7667:                 if ($domdef{$tool}{'default'}) {
                   7668:                     $access = 1;
                   7669:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7670:                     $access = 0;
                   7671:                 }
                   7672:                 return $access;
                   7673:             }
                   7674:         }
                   7675:     } else {
1.1172.2.6  raeburn  7676:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7677:             $access = 1;
                   7678:         } else {
                   7679:             $access = 0;
                   7680:         }
1.976     raeburn  7681:         return $access;
                   7682:     }
                   7683: }
                   7684: 
1.1050    raeburn  7685: sub is_course_owner {
                   7686:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7687:     if (($udom eq '') || ($uname eq '')) {
                   7688:         $udom = $env{'user.domain'};
                   7689:         $uname = $env{'user.name'};
                   7690:     }
                   7691:     unless (($udom eq '') || ($uname eq '')) {
                   7692:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7693:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7694:                 return 1;
                   7695:             } else {
                   7696:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7697:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7698:                     return 1;
                   7699:                 }
                   7700:             }
                   7701:         }
                   7702:     }
                   7703:     return;
                   7704: }
                   7705: 
1.976     raeburn  7706: sub is_advanced_user {
                   7707:     my ($udom,$uname) = @_;
1.1085    raeburn  7708:     if ($udom ne '' && $uname ne '') {
                   7709:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7710:             if (wantarray) {
                   7711:                 return ($env{'user.adv'},$env{'user.author'});
                   7712:             } else {
                   7713:                 return $env{'user.adv'};
                   7714:             }
1.1085    raeburn  7715:         }
                   7716:     }
1.976     raeburn  7717:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7718:     my %allroles;
1.1128    raeburn  7719:     my ($is_adv,$is_author);
1.976     raeburn  7720:     foreach my $role (keys(%roleshash)) {
                   7721:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7722:         my $area = '/'.$tdomain.'/'.$trest;
                   7723:         if ($sec ne '') {
                   7724:             $area .= '/'.$sec;
                   7725:         }
                   7726:         if (($area ne '') && ($trole ne '')) {
                   7727:             my $spec=$trole.'.'.$area;
                   7728:             if ($trole =~ /^cr\//) {
                   7729:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7730:             } elsif ($trole ne 'gr') {
                   7731:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7732:             }
1.1128    raeburn  7733:             if ($trole eq 'au') {
                   7734:                 $is_author = 1;
                   7735:             }
1.976     raeburn  7736:         }
                   7737:     }
                   7738:     foreach my $role (keys(%allroles)) {
                   7739:         last if ($is_adv);
                   7740:         foreach my $item (split(/:/,$allroles{$role})) {
                   7741:             if ($item ne '') {
                   7742:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7743:                 if ($privilege eq 'adv') {
                   7744:                     $is_adv = 1;
                   7745:                     last;
                   7746:                 }
                   7747:             }
                   7748:         }
                   7749:     }
1.1128    raeburn  7750:     if (wantarray) {
                   7751:         return ($is_adv,$is_author);
                   7752:     }
1.976     raeburn  7753:     return $is_adv;
                   7754: }
1.798     raeburn  7755: 
1.1035    raeburn  7756: sub check_can_request {
1.1036    raeburn  7757:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7758:     my $canreq = 0;
                   7759:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7760:     my @options = ('approval','validate','autolimit');
                   7761:     my $optregex = join('|',@options);
                   7762:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7763:         foreach my $type (@{$types}) {
                   7764:             if (&usertools_access($env{'user.name'},
                   7765:                                   $env{'user.domain'},
                   7766:                                   $type,undef,'requestcourses')) {
                   7767:                 $canreq ++;
1.1036    raeburn  7768:                 if (ref($request_domains) eq 'HASH') {
                   7769:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7770:                 }
1.1035    raeburn  7771:                 if ($dom eq $env{'user.domain'}) {
                   7772:                     $can_request->{$type} = 1;
                   7773:                 }
                   7774:             }
                   7775:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7776:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7777:                 if (@curr > 0) {
1.1036    raeburn  7778:                     foreach my $item (@curr) {
                   7779:                         if (ref($request_domains) eq 'HASH') {
                   7780:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7781:                             if ($otherdom ne '') {
                   7782:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7783:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7784:                                         push(@{$request_domains->{$type}},$otherdom);
                   7785:                                     }
                   7786:                                 } else {
                   7787:                                     push(@{$request_domains->{$type}},$otherdom);
                   7788:                                 }
                   7789:                             }
                   7790:                         }
                   7791:                     }
                   7792:                     unless($dom eq $env{'user.domain'}) {
                   7793:                         $canreq ++;
1.1035    raeburn  7794:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7795:                             $can_request->{$type} = 1;
                   7796:                         }
                   7797:                     }
                   7798:                 }
                   7799:             }
                   7800:         }
                   7801:     }
                   7802:     return $canreq;
                   7803: }
                   7804: 
1.341     www      7805: # ---------------------------------------------- Custom access rule evaluation
                   7806: 
                   7807: sub customaccess {
                   7808:     my ($priv,$uri)=@_;
1.807     albertel 7809:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7810:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7811:     $udom = &LONCAPA::clean_domain($udom);
                   7812:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7813:     my $access=0;
1.800     albertel 7814:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7815: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7816: 	if ($type eq 'user') {
                   7817: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7818: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7819: 		if ($tdom) {
                   7820: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7821: 		}
1.896     albertel 7822: 		if ($tuname) {
                   7823: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7824: 		}
                   7825: 		$access=($effect eq 'allow');
                   7826: 		last;
                   7827: 	    }
                   7828: 	} else {
                   7829: 	    if ($role) {
                   7830: 		if ($role ne $urole) { next; }
                   7831: 	    }
                   7832: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7833: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7834: 		if ($tdom) {
                   7835: 		    if ($tdom ne $udom) { next; }
                   7836: 		}
                   7837: 		if ($tcrs) {
                   7838: 		    if ($tcrs ne $ucrs) { next; }
                   7839: 		}
                   7840: 		if ($tsec) {
                   7841: 		    if ($tsec ne $usec) { next; }
                   7842: 		}
                   7843: 		$access=($effect eq 'allow');
                   7844: 		last;
                   7845: 	    }
                   7846: 	    if ($realm eq '' && $role eq '') {
                   7847: 		$access=($effect eq 'allow');
                   7848: 	    }
1.402     bowersj2 7849: 	}
1.341     www      7850:     }
                   7851:     return $access;
                   7852: }
                   7853: 
1.103     harris41 7854: # ------------------------------------------------- Check for a user privilege
1.12      www      7855: 
                   7856: sub allowed {
1.1172.2.118.  .8(raebu 7857:20):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7858:     my $ver_orguri=$uri;
1.439     www      7859:     $uri=&deversion($uri);
1.152     www      7860:     my $orguri=$uri;
1.52      www      7861:     $uri=&declutter($uri);
1.809     raeburn  7862: 
1.810     raeburn  7863:     if ($priv eq 'evb') {
                   7864: # Evade communication block restrictions for specified role in a course
                   7865:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7866:             return $1;
                   7867:         } else {
                   7868:             return;
                   7869:         }
                   7870:     }
                   7871: 
1.620     albertel 7872:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7873: # Free bre access to adm and meta resources
1.1172.2.118.  .13(raeb 7874:-21):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 7875: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7876: 	&& ($priv eq 'bre')) {
1.14      www      7877: 	return 'F';
1.159     www      7878:     }
                   7879: 
1.545     banghart 7880: # Free bre access to user's own portfolio contents
1.714     raeburn  7881:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7882:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7883: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7884:         my %setters;
                   7885:         my ($startblock,$endblock) = 
                   7886:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7887:         if ($startblock && $endblock) {
                   7888:             return 'B';
                   7889:         } else {
                   7890:             return 'F';
                   7891:         }
1.545     banghart 7892:     }
                   7893: 
1.762     raeburn  7894: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7895:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7896:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7897:         if (exists($env{'request.course.id'})) {
                   7898:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7899:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7900:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7901:                 my $courseprivid=$env{'request.course.id'};
                   7902:                 $courseprivid=~s/\_/\//;
                   7903:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7904:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7905:                     return $1; 
1.762     raeburn  7906:                 } else {
                   7907:                     if ($env{'request.course.sec'}) {
                   7908:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7909:                     }
                   7910:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7911:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7912:                         return $2;
                   7913:                     }
1.714     raeburn  7914:                 }
                   7915:             }
                   7916:         }
                   7917:     }
                   7918: 
1.159     www      7919: # Free bre to public access
                   7920: 
                   7921:     if ($priv eq 'bre') {
1.238     www      7922:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7923: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7924:            return 'F'; 
                   7925:         }
1.238     www      7926:         if ($copyright eq 'priv') {
                   7927:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7928: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7929: 		return '';
                   7930:             }
                   7931:         }
                   7932:         if ($copyright eq 'domain') {
                   7933:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7934: 	    unless (($env{'user.domain'} eq $1) ||
                   7935:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7936: 		return '';
                   7937:             }
1.262     matthew  7938:         }
1.620     albertel 7939:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7940:             # Library role, so allow browsing of resources in this domain.
                   7941:             return 'F';
1.238     www      7942:         }
1.341     www      7943:         if ($copyright eq 'custom') {
                   7944: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7945:         }
1.14      www      7946:     }
1.264     matthew  7947:     # Domain coordinator is trying to create a course
1.620     albertel 7948:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7949:         # uri is the requested domain in this case.
                   7950:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7951:         # a role of dc for the domain in question.
1.620     albertel 7952:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7953:     }
1.29      www      7954: 
1.52      www      7955:     my $thisallowed='';
                   7956:     my $statecond=0;
                   7957:     my $courseprivid='';
                   7958: 
1.1039    raeburn  7959:     my $ownaccess;
1.1043    raeburn  7960:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7961:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7962:         if ($uri eq '') {
                   7963:             $ownaccess = 1;
                   7964:         } else {
                   7965:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7966:                 my $udom = $env{'user.domain'};
                   7967:                 my $uname = $env{'user.name'};
                   7968:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7969:                     $ownaccess = 1;
1.1040    raeburn  7970:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7971:                     unless ($uri =~ m{\.\./}) {
                   7972:                         $ownaccess = 1;
                   7973:                     }
                   7974:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7975:                     my $now = time;
                   7976:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7977:                         my $adom = $1;
                   7978:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7979:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7980:                                 my ($start,$end) = split('.',$env{$key});
                   7981:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7982:                                     $ownaccess = 1;
                   7983:                                     last;
                   7984:                                 }
                   7985:                             }
                   7986:                         }
                   7987:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7988:                         my $adom = $1;
                   7989:                         my $aname = $2;
1.1042    raeburn  7990:                         foreach my $role ('ca','aa') { 
                   7991:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7992:                                 my ($start,$end) =
                   7993:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7994:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7995:                                     $ownaccess = 1;
                   7996:                                     last;
                   7997:                                 }
1.1039    raeburn  7998:                             }
                   7999:                         }
                   8000:                     }
                   8001:                 }
                   8002:             }
                   8003:         }
                   8004:     }
                   8005: 
1.52      www      8006: # Course
                   8007: 
1.620     albertel 8008:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8009:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8010:             $thisallowed.=$1;
                   8011:         }
1.52      www      8012:     }
1.29      www      8013: 
1.52      www      8014: # Domain
                   8015: 
1.620     albertel 8016:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8017:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8018:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8019:             $thisallowed.=$1;
                   8020:         }
1.12      www      8021:     }
1.52      www      8022: 
1.1141    raeburn  8023: # User who is not author or co-author might still be able to edit
                   8024: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8025:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8026:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8027:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8028:             $thisallowed.=$1;
                   8029:         }
                   8030:     }
                   8031: 
1.52      www      8032: # Course: uri itself is a course
1.66      www      8033:     my $courseuri=$uri;
                   8034:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8035:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8036: 
1.620     albertel 8037:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8038:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8039:         if ($priv eq 'mip') {
                   8040:             my $rem = $1;
                   8041:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8042:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8043:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8044:                 if ($cdom ne '') {
                   8045:                     my %passwdconf = &get_passwdconf($cdom);
                   8046:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8047:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8048:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8049:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8050:                                 unless (@inststatuses) {
                   8051:                                     @inststatuses = ('default');
                   8052:                                 }
                   8053:                                 foreach my $status (@inststatuses) {
                   8054:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8055:                                         $thisallowed.=$rem;
                   8056:                                     }
                   8057:                                 }
                   8058:                             }
                   8059:                         }
                   8060:                     }
                   8061:                 }
                   8062:             }
                   8063:         } else {
                   8064:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8065:                 $thisallowed.=$1;
                   8066:             }
1.1039    raeburn  8067:         }
1.12      www      8068:     }
1.29      www      8069: 
1.665     albertel 8070: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8071: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8072:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8073: 	$thisallowed='';
1.671     raeburn  8074:         my ($match)=&is_on_map($uri);
                   8075:         if ($match) {
                   8076:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8077:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8078:                 my $value = $1;
                   8079:                 if ($noblockcheck) {
                   8080:                     $thisallowed.=$value;
1.1162    raeburn  8081:                 } else {
1.1172.2.118.  .8(raebu 8082:20):                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8083:                     if (@blockers > 0) {
                   8084:                         $thisallowed = 'B';
                   8085:                     } else {
                   8086:                         $thisallowed.=$value;
                   8087:                     }
1.1162    raeburn  8088:                 }
1.671     raeburn  8089:             }
                   8090:         } else {
1.705     albertel 8091:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8092:             if ($refuri) {
                   8093:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8094:                     $thisallowed='F';
1.671     raeburn  8095:                 } else {
                   8096:                     $refuri=&declutter($refuri);
                   8097:                     my ($match) = &is_on_map($refuri);
                   8098:                     if ($match) {
1.1172.2.65  raeburn  8099:                         if ($noblockcheck) {
1.1162    raeburn  8100:                             $thisallowed='F';
1.1172.2.65  raeburn  8101:                         } else {
1.1172.2.118.  .8(raebu 8102:20):                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8103:                             if (@blockers > 0) {
                   8104:                                 $thisallowed = 'B';
                   8105:                             } else {
                   8106:                                 $thisallowed='F';
                   8107:                             }
1.1162    raeburn  8108:                         }
1.671     raeburn  8109:                     }
1.669     raeburn  8110:                 }
1.671     raeburn  8111:             }
                   8112:         }
1.314     www      8113:     }
1.492     albertel 8114: 
1.766     albertel 8115:     if ($priv eq 'bre'
                   8116: 	&& $thisallowed ne 'F' 
                   8117: 	&& $thisallowed ne '2'
                   8118: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8119: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8120:     }
1.1172.2.118.  .8(raebu 8121:20): 
1.52      www      8122: # Full access at system, domain or course-wide level? Exit.
1.29      www      8123:     if ($thisallowed=~/F/) {
                   8124: 	return 'F';
                   8125:     }
                   8126: 
1.52      www      8127: # If this is generating or modifying users, exit with special codes
1.29      www      8128: 
1.643     www      8129:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8130: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8131: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8132: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8133: 	    unless ($auname) { return $thisallowed; }
                   8134: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8135: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8136: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8137: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8138: 	}
1.52      www      8139: 	return $thisallowed;
                   8140:     }
                   8141: #
1.103     harris41 8142: # Gathered so far: system, domain and course wide privileges
1.52      www      8143: #
                   8144: # Course: See if uri or referer is an individual resource that is part of 
                   8145: # the course
                   8146: 
1.620     albertel 8147:     if ($env{'request.course.id'}) {
1.232     www      8148: 
1.1172.2.115  raeburn  8149: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8150: 
                   8151:         if ($priv eq 'mip') {
                   8152:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8153:                 return $thisallowed;
                   8154:             } else {
                   8155:                 return '';
                   8156:             }
                   8157:         }
                   8158: 
1.620     albertel 8159:        $courseprivid=$env{'request.course.id'};
                   8160:        if ($env{'request.course.sec'}) {
                   8161:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8162:        }
                   8163:        $courseprivid=~s/\_/\//;
                   8164:        my $checkreferer=1;
1.232     www      8165:        my ($match,$cond)=&is_on_map($uri);
                   8166:        if ($match) {
                   8167:            $statecond=$cond;
1.620     albertel 8168:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8169:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8170:                my $value = $1;
                   8171:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8172:                    if ($noblockcheck) {
1.1162    raeburn  8173:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8174:                    } else {
1.1172.2.118.  .8(raebu 8175:20):                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8176:                        if (@blockers > 0) {
                   8177:                            $thisallowed = 'B';
                   8178:                        } else {
                   8179:                            $thisallowed.=$value;
                   8180:                        }
1.1162    raeburn  8181:                    }
                   8182:                } else {
                   8183:                    $thisallowed.=$value;
                   8184:                }
1.52      www      8185:                $checkreferer=0;
                   8186:            }
1.29      www      8187:        }
1.1172.2.118.  .8(raebu 8188:20): 
1.148     www      8189:        if ($checkreferer) {
1.620     albertel 8190: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8191:             unless ($refuri) {
1.800     albertel 8192:                 foreach my $key (keys(%env)) {
                   8193: 		    if ($key=~/^httpref\..*\*/) {
                   8194: 			my $pattern=$key;
1.156     www      8195:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8196:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8197:                         $pattern=~s/\//\\\//g;
1.152     www      8198:                         if ($orguri=~/$pattern/) {
1.800     albertel 8199: 			    $refuri=$env{$key};
1.148     www      8200:                         }
                   8201:                     }
1.191     harris41 8202:                 }
1.148     www      8203:             }
1.232     www      8204: 
1.148     www      8205:          if ($refuri) { 
1.152     www      8206: 	  $refuri=&declutter($refuri);
1.232     www      8207:           my ($match,$cond)=&is_on_map($refuri);
                   8208:             if ($match) {
                   8209:               my $refstatecond=$cond;
1.620     albertel 8210:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8211:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8212:                   my $value = $1;
                   8213:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8214:                       if ($noblockcheck) {
1.1162    raeburn  8215:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8216:                       } else {
1.1172.2.118.  .8(raebu 8217:20):                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8218:                           if (@blockers > 0) {
                   8219:                               $thisallowed = 'B';
                   8220:                           } else {
                   8221:                               $thisallowed.=$value;
                   8222:                           }
1.1162    raeburn  8223:                       }
                   8224:                   } else {
                   8225:                       $thisallowed.=$value;
                   8226:                   }
1.53      www      8227:                   $uri=$refuri;
                   8228:                   $statecond=$refstatecond;
1.52      www      8229:               }
                   8230:           }
1.148     www      8231:         }
1.29      www      8232:        }
1.52      www      8233:    }
1.29      www      8234: 
1.52      www      8235: #
1.103     harris41 8236: # Gathered now: all privileges that could apply, and condition number
1.52      www      8237: # 
                   8238: #
                   8239: # Full or no access?
                   8240: #
1.29      www      8241: 
1.52      www      8242:     if ($thisallowed=~/F/) {
                   8243: 	return 'F';
                   8244:     }
1.29      www      8245: 
1.52      www      8246:     unless ($thisallowed) {
                   8247:         return '';
                   8248:     }
1.29      www      8249: 
1.52      www      8250: # Restrictions exist, deal with them
                   8251: #
                   8252: #   C:according to course preferences
                   8253: #   R:according to resource settings
                   8254: #   L:unless locked
                   8255: #   X:according to user session state
                   8256: #
                   8257: 
                   8258: # Possibly locked functionality, check all courses
1.54      www      8259: # Locks might take effect only after 10 minutes cache expiration for other
                   8260: # courses, and 2 minutes for current course
1.52      www      8261: 
                   8262:     my $envkey;
                   8263:     if ($thisallowed=~/L/) {
1.1000    raeburn  8264:         foreach $envkey (keys(%env)) {
1.54      www      8265:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8266:                my $courseid=$2;
                   8267:                my $roleid=$1.'.'.$2;
1.92      www      8268:                $courseid=~s/^\///;
1.54      www      8269:                my $expiretime=600;
1.620     albertel 8270:                if ($env{'request.role'} eq $roleid) {
1.54      www      8271: 		  $expiretime=120;
                   8272:                }
                   8273: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8274:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8275:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8276: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8277:                }
1.620     albertel 8278:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8279:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8280: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8281:                        &log($env{'user.domain'},$env{'user.name'},
                   8282:                             $env{'user.home'},
1.57      www      8283:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8284:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8285:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8286: 		       return '';
                   8287:                    }
                   8288:                }
1.620     albertel 8289:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8290:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8291: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8292:                        &log($env{'user.domain'},$env{'user.name'},
                   8293:                             $env{'user.home'},
1.57      www      8294:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8295:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8296:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8297: 		       return '';
                   8298:                    }
                   8299:                }
                   8300: 	   }
1.29      www      8301:        }
1.52      www      8302:     }
1.1172.2.118.  .8(raebu 8303:20): 
1.52      www      8304: #
                   8305: # Rest of the restrictions depend on selected course
                   8306: #
                   8307: 
1.620     albertel 8308:     unless ($env{'request.course.id'}) {
1.766     albertel 8309: 	if ($thisallowed eq 'A') {
                   8310: 	    return 'A';
1.814     raeburn  8311:         } elsif ($thisallowed eq 'B') {
                   8312:             return 'B';
1.766     albertel 8313: 	} else {
                   8314: 	    return '1';
                   8315: 	}
1.52      www      8316:     }
1.29      www      8317: 
1.52      www      8318: #
                   8319: # Now user is definitely in a course
                   8320: #
1.53      www      8321: 
                   8322: 
                   8323: # Course preferences
                   8324: 
                   8325:    if ($thisallowed=~/C/) {
1.620     albertel 8326:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8327:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8328:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8329: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8330: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8331: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8332: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8333: 			$env{'request.course.id'});
                   8334: 	   }
1.237     www      8335:            return '';
                   8336:        }
                   8337: 
1.620     albertel 8338:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8339: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8340: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8341: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8342: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8343: 			$env{'request.course.id'});
                   8344: 	   }
1.54      www      8345:            return '';
                   8346:        }
1.53      www      8347:    }
                   8348: 
                   8349: # Resource preferences
                   8350: 
                   8351:    if ($thisallowed=~/R/) {
1.620     albertel 8352:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8353:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8354: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8355: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8356: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8357: 	   }
                   8358: 	   return '';
1.54      www      8359:        }
1.53      www      8360:    }
1.30      www      8361: 
1.246     www      8362: # Restricted by state or randomout?
1.30      www      8363: 
1.52      www      8364:    if ($thisallowed=~/X/) {
1.620     albertel 8365:       if ($env{'acc.randomout'}) {
1.579     albertel 8366: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8367:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8368:             return ''; 
                   8369:          }
1.247     www      8370:       }
                   8371:       if (&condval($statecond)) {
1.52      www      8372: 	 return '2';
                   8373:       } else {
                   8374:          return '';
                   8375:       }
                   8376:    }
1.30      www      8377: 
1.766     albertel 8378:     if ($thisallowed eq 'A') {
                   8379: 	return 'A';
1.814     raeburn  8380:     } elsif ($thisallowed eq 'B') {
                   8381:         return 'B';
1.766     albertel 8382:     }
1.52      www      8383:    return 'F';
1.232     www      8384: }
1.1162    raeburn  8385: 
1.1172.2.13  raeburn  8386: # ------------------------------------------- Check construction space access
                   8387: 
                   8388: sub constructaccess {
                   8389:     my ($url,$setpriv)=@_;
                   8390: 
                   8391: # We do not allow editing of previous versions of files
                   8392:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8393: 
                   8394: # Get username and domain from URL
                   8395:     my ($ownername,$ownerdomain,$ownerhome);
                   8396: 
                   8397:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8398:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8399: 
                   8400: # The URL does not really point to any authorspace, forget it
                   8401:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8402: 
                   8403: # Now we need to see if the user has access to the authorspace of
                   8404: # $ownername at $ownerdomain
                   8405: 
                   8406:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8407: # Real author for this?
                   8408:        $ownerhome = $env{'user.home'};
                   8409:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8410:           return ($ownername,$ownerdomain,$ownerhome);
                   8411:        }
                   8412:     } else {
                   8413: # Co-author for this?
                   8414:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8415:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8416:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8417:             return ($ownername,$ownerdomain,$ownerhome);
                   8418:         }
                   8419:     }
                   8420: 
                   8421: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8422: # we might as well leave
                   8423:    unless ($setpriv) { return ''; }
                   8424: 
                   8425: # Backdoor access?
                   8426:     my $allowed=&allowed('eco',$ownerdomain);
                   8427: # Nope
                   8428:     unless ($allowed) { return ''; }
                   8429: # Looks like we may have access, but could be locked by the owner of the construction space
                   8430:     if ($allowed eq 'U') {
                   8431:         my %blocked=&get('environment',['domcoord.author'],
                   8432:                          $ownerdomain,$ownername);
                   8433: # Is blocked by owner
                   8434:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8435:     }
                   8436:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8437: # Grant temporary access
                   8438:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8439:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8440:         if (!$update) { $update = $then; }
                   8441:         my $refresh=$env{'user.refresh.time'};
                   8442:         if (!$refresh) { $refresh = $update; }
                   8443:         my $now = time;
                   8444:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8445:                            $now,'ca','constructaccess');
                   8446:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8447:         return($ownername,$ownerdomain,$ownerhome);
                   8448:     }
                   8449: # No business here
                   8450:     return '';
                   8451: }
                   8452: 
1.1172.2.66  raeburn  8453: # ----------------------------------------------------------- Content Blocking
                   8454: 
                   8455: {
                   8456: # Caches for faster Course Contents display where content blocking
                   8457: # is in operation (i.e., interval param set) for timed quiz.
                   8458: #
                   8459: # User for whom data are being temporarily cached.
                   8460: my $cacheduser='';
1.1172.2.118.  .8(raebu 8461:20): # Course for which data are being temporarily cached.
                   8462:20): my $cachedcid='';
1.1172.2.66  raeburn  8463: # Cached blockers for this user (a hash of blocking items).
                   8464: my %cachedblockers=();
                   8465: # When the data were last cached.
                   8466: my $cachedlast='';
                   8467: 
                   8468: sub load_all_blockers {
1.1172.2.118.  .9(raebu 8469:20):     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8470:     if (($uname ne '') && ($udom ne '')) {
                   8471:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.118.  .8(raebu 8472:20):             ($cachedcid eq $env{'request.course.id'}) &&
          .9(raebu 8473:20):             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8474:             return;
                   8475:         }
                   8476:     }
                   8477:     $cachedlast=time;
                   8478:     $cacheduser=$uname.':'.$udom;
1.1172.2.118.  .8(raebu 8479:20):     $cachedcid=$env{'request.course.id'};
          .9(raebu 8480:20):     %cachedblockers = &get_commblock_resources();
          .8(raebu 8481:20):     return;
1.1172.2.66  raeburn  8482: }
                   8483: 
1.1162    raeburn  8484: sub get_comm_blocks {
                   8485:     my ($cdom,$cnum) = @_;
                   8486:     if ($cdom eq '' || $cnum eq '') {
                   8487:         return unless ($env{'request.course.id'});
                   8488:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8489:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8490:     }
                   8491:     my %commblocks;
                   8492:     my $hashid=$cdom.'_'.$cnum;
                   8493:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8494:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8495:         %commblocks = %{$blocksref};
                   8496:     } else {
                   8497:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8498:         my $cachetime = 600;
                   8499:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8500:     }
                   8501:     return %commblocks;
                   8502: }
                   8503: 
1.1172.2.66  raeburn  8504: sub get_commblock_resources {
                   8505:     my ($blocks) = @_;
                   8506:     my %blockers = ();
                   8507:     return %blockers unless ($env{'request.course.id'});
                   8508:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8509:     my %commblocks;
                   8510:     if (ref($blocks) eq 'HASH') {
                   8511:         %commblocks = %{$blocks};
                   8512:     } else {
                   8513:         %commblocks = &get_comm_blocks();
                   8514:     }
1.1172.2.66  raeburn  8515:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8516:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8517:     return %blockers unless (ref($navmap));
                   8518:     my $now = time;
1.1162    raeburn  8519:     foreach my $block (keys(%commblocks)) {
                   8520:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8521:             my ($start,$end) = ($1,$2);
                   8522:             if ($start <= $now && $end >= $now) {
                   8523:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8524:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8525:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8526:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8527:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8528:                             }
                   8529:                         }
                   8530:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8531:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8532:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8533:                             }
                   8534:                         }
                   8535:                     }
                   8536:                 }
                   8537:             }
                   8538:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8539:             my $item = $1;
1.1163    raeburn  8540:             my @to_test;
1.1162    raeburn  8541:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8542:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8543:                     my @interval;
                   8544:                     my $type = 'map';
                   8545:                     if ($item eq 'course') {
                   8546:                         $type = 'course';
                   8547:                         @interval=&EXT("resource.0.interval");
                   8548:                     } else {
                   8549:                         if ($item =~ /___\d+___/) {
                   8550:                             $type = 'resource';
                   8551:                             @interval=&EXT("resource.0.interval",$item);
                   8552:                             if (ref($navmap)) {
                   8553:                                 my $res = $navmap->getBySymb($item);
                   8554:                                 push(@to_test,$res);
                   8555:                             }
1.1162    raeburn  8556:                         } else {
1.1172.2.66  raeburn  8557:                             my $mapsymb = &symbread($item,1);
                   8558:                             if ($mapsymb) {
                   8559:                                 if (ref($navmap)) {
                   8560:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.118.  .11(raeb 8561:-20):                                     if (ref($mapres)) {
                   8562:-20):                                         my $first = $mapres->map_start();
                   8563:-20):                                         my $finish = $mapres->map_finish();
                   8564:-20):                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8565:-20):                                         if (ref($it)) {
                   8566:-20):                                             my $res;
                   8567:-20):                                             while ($res = $it->next(undef,1)) {
                   8568:-20):                                                 next unless (ref($res));
                   8569:-20):                                                 my $symb = $res->symb();
                   8570:-20):                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8571:-20):                                                 @interval=&EXT("resource.0.interval",$symb);
                   8572:-20):                                                 if ($interval[1] eq 'map') {
                   8573:-20):                                                     if ($res->answerable()) {
                   8574:-20):                                                         push(@to_test,$res);
                   8575:-20):                                                         last;
                   8576:-20):                                                     }
                   8577:-20):                                                 }
1.1162    raeburn  8578:                                             }
                   8579:                                         }
                   8580:                                     }
                   8581:                                 }
                   8582:                             }
                   8583:                         }
1.1172.2.66  raeburn  8584:                     }
1.1172.2.118.  .1(raebu 8585:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8586:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8587:                         my $first_access;
                   8588:                         if ($type eq 'resource') {
                   8589:                             $first_access=&get_first_access($interval[1],$item);
                   8590:                         } elsif ($type eq 'map') {
                   8591:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8592:                         } else {
                   8593:                             $first_access=&get_first_access($interval[1]);
                   8594:                         }
                   8595:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8596:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8597:                             if ($timesup > $now) {
                   8598:                                 my $activeblock;
                   8599:                                 foreach my $res (@to_test) {
                   8600:                                     if ($res->answerable()) {
                   8601:                                         $activeblock = 1;
                   8602:                                         last;
                   8603:                                     }
                   8604:                                 }
                   8605:                                 if ($activeblock) {
                   8606:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8607:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8608:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8609:                                          }
                   8610:                                     }
                   8611:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8612:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8613:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8614:                                         }
1.1162    raeburn  8615:                                     }
                   8616:                                 }
                   8617:                             }
                   8618:                         }
                   8619:                     }
                   8620:                 }
                   8621:             }
                   8622:         }
                   8623:     }
1.1172.2.66  raeburn  8624:     return %blockers;
1.1162    raeburn  8625: }
                   8626: 
1.1172.2.66  raeburn  8627: sub has_comm_blocking {
1.1172.2.118.  .9(raebu 8628:20):     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8629:     my @blockers;
                   8630:     return unless ($env{'request.course.id'});
                   8631:     return unless ($priv eq 'bre');
                   8632:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8633:     return if ($env{'request.state'} eq 'construct');
1.1172.2.118.  .9(raebu 8634:20):     my %blockinfo;
                   8635:20):     if (ref($blocks) eq 'HASH') {
                   8636:20):         %blockinfo = &get_commblock_resources($blocks);
                   8637:20):     } else {
                   8638:20):         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8639:20):         %blockinfo = %cachedblockers;
                   8640:20):     }
                   8641:20):     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8642:     my (%possibles,@symbs);
                   8643:     if (!$symb) {
1.1172.2.118.  .9(raebu 8644:20):         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8645:     }
1.1172.2.66  raeburn  8646:     if ($symb) {
                   8647:         @symbs = ($symb);
                   8648:     } elsif (keys(%possibles)) {
                   8649:         @symbs = keys(%possibles);
                   8650:     }
                   8651:     my $noblock;
                   8652:     foreach my $symb (@symbs) {
                   8653:         last if ($noblock);
                   8654:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.118.  .9(raebu 8655:20):         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8656:             if ($block =~ /^firstaccess____(.+)$/) {
                   8657:                 my $item = $1;
1.1172.2.118.  .8(raebu 8658:20):                 unless ($blocked) {
                   8659:20):                     if (($item eq $map) || ($item eq $symb)) {
                   8660:20):                         $noblock = 1;
                   8661:20):                         last;
                   8662:20):                     }
1.1172.2.66  raeburn  8663:                 }
1.1162    raeburn  8664:             }
1.1172.2.118.  .9(raebu 8665:20):             if (ref($blockinfo{$block}) eq 'HASH') {
                   8666:20):                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8667:20):                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8668:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8669:                             push(@blockers,$block);
                   8670:                         }
                   8671:                     }
                   8672:                 }
1.1172.2.118.  .9(raebu 8673:20):                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8674:20):                     if ($blockinfo{$block}{'maps'}{$map}) {
          .8(raebu 8675:20):                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8676:20):                             push(@blockers,$block);
                   8677:20):                         }
1.1172.2.66  raeburn  8678:                     }
                   8679:                 }
1.1162    raeburn  8680:             }
                   8681:         }
                   8682:     }
1.1172.2.118.  .8(raebu 8683:20):     unless ($noblock) {
                   8684:20):         return @blockers;
                   8685:20):     }
                   8686:20):     return;
1.1172.2.66  raeburn  8687: }
1.1162    raeburn  8688: }
                   8689: 
1.1172.2.66  raeburn  8690: # -------------------------------- Deversion and split uri into path an filename
                   8691: 
1.1133    foxr     8692: #
1.1172.2.66  raeburn  8693: #   Removes the version from a URI and
1.1133    foxr     8694: #   splits it in to its filename and path to the filename.
                   8695: #   Seems like File::Basename could have done this more clearly.
                   8696: #   Parameters:
                   8697: #      $uri   - input URI
                   8698: #   Returns:
                   8699: #     Two element list consisting of 
                   8700: #     $pathname  - the URI up to and excluding the trailing /
                   8701: #     $filename  - The part of the URI following the last /
                   8702: #  NOTE:
                   8703: #    Another realization of this is simply:
                   8704: #    use File::Basename;
                   8705: #    ...
                   8706: #    $uri = shift;
                   8707: #    $filename = basename($uri);
                   8708: #    $path     = dirname($uri);
                   8709: #    return ($filename, $path);
                   8710: #
                   8711: #     The implementation below is probably faster however.
                   8712: #
1.710     albertel 8713: sub split_uri_for_cond {
                   8714:     my $uri=&deversion(&declutter(shift));
                   8715:     my @uriparts=split(/\//,$uri);
                   8716:     my $filename=pop(@uriparts);
                   8717:     my $pathname=join('/',@uriparts);
                   8718:     return ($pathname,$filename);
                   8719: }
1.232     www      8720: # --------------------------------------------------- Is a resource on the map?
                   8721: 
                   8722: sub is_on_map {
1.710     albertel 8723:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8724:     #Trying to find the conditional for the file
1.620     albertel 8725:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8726: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8727:     if ($match) {
1.289     bowersj2 8728: 	return (1,$1);
                   8729:     } else {
1.434     www      8730: 	return (0,0);
1.289     bowersj2 8731:     }
1.12      www      8732: }
                   8733: 
1.427     www      8734: # --------------------------------------------------------- Get symb from alias
                   8735: 
                   8736: sub get_symb_from_alias {
                   8737:     my $symb=shift;
                   8738:     my ($map,$resid,$url)=&decode_symb($symb);
                   8739: # Already is a symb
                   8740:     if ($url) { return $symb; }
                   8741: # Must be an alias
                   8742:     my $aliassymb='';
                   8743:     my %bighash;
1.620     albertel 8744:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8745:                             &GDBM_READER(),0640)) {
                   8746:         my $rid=$bighash{'mapalias_'.$symb};
                   8747: 	if ($rid) {
                   8748: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8749: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8750: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8751: 	}
                   8752:         untie %bighash;
                   8753:     }
                   8754:     return $aliassymb;
                   8755: }
                   8756: 
1.12      www      8757: # ----------------------------------------------------------------- Define Role
                   8758: 
                   8759: sub definerole {
                   8760:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8761:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8762:     foreach my $role (split(':',$sysrole)) {
                   8763: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8764:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8765:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8766: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8767:                return "refused:s:$crole&$cqual"; 
                   8768:             }
                   8769:         }
1.191     harris41 8770:     }
1.800     albertel 8771:     foreach my $role (split(':',$domrole)) {
                   8772: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8773:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8774:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8775: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8776:                return "refused:d:$crole&$cqual"; 
                   8777:             }
                   8778:         }
1.191     harris41 8779:     }
1.800     albertel 8780:     foreach my $role (split(':',$courole)) {
                   8781: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8782:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8783:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8784: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8785:                return "refused:c:$crole&$cqual"; 
                   8786:             }
                   8787:         }
1.191     harris41 8788:     }
1.1172.2.84  raeburn  8789:     my $uhome;
                   8790:     if (($uname ne '') && ($udom ne '')) {
                   8791:         $uhome = &homeserver($uname,$udom);
                   8792:         return $uhome if ($uhome eq 'no_host');
                   8793:     } else {
                   8794:         $uname = $env{'user.name'};
                   8795:         $udom = $env{'user.domain'};
                   8796:         $uhome = $env{'user.home'};
                   8797:     }
1.620     albertel 8798:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8799:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8800:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8801:     return reply($command,$uhome);
1.12      www      8802:   } else {
                   8803:     return 'refused';
                   8804:   }
1.105     harris41 8805: }
                   8806: 
                   8807: # ---------------- Make a metadata query against the network of library servers
                   8808: 
                   8809: sub metadata_query {
1.1172.2.33  raeburn  8810:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8811:     my %rhash;
1.845     albertel 8812:     my %libserv = &all_library();
1.244     matthew  8813:     my @server_list = (defined($server_array) ? @$server_array
                   8814:                                               : keys(%libserv) );
                   8815:     for my $server (@server_list) {
1.1172.2.33  raeburn  8816:         my $domains = '';
                   8817:         if (ref($domains_hash) eq 'HASH') {
                   8818:             $domains = $domains_hash->{$server};    
                   8819:         }
1.118     harris41 8820: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8821: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8822: 	    $rhash{$server}=$reply;
                   8823: 	}
                   8824: 	else {
                   8825: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8826: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8827: 			     $server);
                   8828: 	    $rhash{$server}=$reply;
                   8829: 	}
1.112     harris41 8830:     }
1.118     harris41 8831:     return \%rhash;
1.240     www      8832: }
                   8833: 
                   8834: # ----------------------------------------- Send log queries and wait for reply
                   8835: 
                   8836: sub log_query {
                   8837:     my ($uname,$udom,$query,%filters)=@_;
                   8838:     my $uhome=&homeserver($uname,$udom);
                   8839:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8840:     my $uhost=&hostname($uhome);
1.800     albertel 8841:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8842:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8843:                        $uhome);
1.479     albertel 8844:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8845:     return get_query_reply($queryid);
                   8846: }
                   8847: 
1.818     raeburn  8848: # -------------------------- Update MySQL table for portfolio file
                   8849: 
                   8850: sub update_portfolio_table {
1.821     raeburn  8851:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8852:     if ($group ne '') {
                   8853:         $file_name =~s /^\Q$group\E//;
                   8854:     }
1.818     raeburn  8855:     my $homeserver = &homeserver($uname,$udom);
                   8856:     my $queryid=
1.821     raeburn  8857:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8858:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8859:     my $reply = &get_query_reply($queryid);
                   8860:     return $reply;
                   8861: }
                   8862: 
1.899     raeburn  8863: # -------------------------- Update MySQL allusers table
                   8864: 
                   8865: sub update_allusers_table {
                   8866:     my ($uname,$udom,$names) = @_;
                   8867:     my $homeserver = &homeserver($uname,$udom);
                   8868:     my $queryid=
                   8869:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8870:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8871:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8872:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8873:                'generation='.&escape($names->{'generation'}).'%%'.
                   8874:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8875:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8876:     return;
1.899     raeburn  8877: }
                   8878: 
1.508     raeburn  8879: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8880: 
                   8881: sub fetch_enrollment_query {
1.511     raeburn  8882:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8883:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8884:     my $maxtries = 1;
1.508     raeburn  8885:     if ($context eq 'automated') {
                   8886:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8887:         $sleep = 2;
                   8888:         $loopmax = 100;
1.547     raeburn  8889:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8890:     } else {
                   8891:         $homeserver = &homeserver($cnum,$dom);
                   8892:     }
1.838     albertel 8893:     my $host=&hostname($homeserver);
1.506     raeburn  8894:     my $cmd = '';
1.1000    raeburn  8895:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8896:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8897:     }
                   8898:     $cmd =~ s/%%$//;
                   8899:     $cmd = &escape($cmd);
                   8900:     my $query = 'fetchenrollment';
1.620     albertel 8901:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8902:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8903:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8904:         return 'error: '.$queryid;
                   8905:     }
1.1172.2.93  raeburn  8906:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8907:     my $tries = 1;
                   8908:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8909:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8910:         $tries ++;
                   8911:     }
1.526     raeburn  8912:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8913:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8914:     } else {
1.901     albertel 8915:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8916:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8917:             foreach my $line (@responses) {
                   8918:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8919:                 $$replyref{$key} = $value;
                   8920:             }
                   8921:         } else {
1.1117    foxr     8922:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8923:             foreach my $line (@responses) {
                   8924:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8925:                 $$replyref{$key} = $value;
                   8926:                 if ($value > 0) {
1.800     albertel 8927:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8928:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8929:                         my $destname = $pathname.'/'.$filename;
                   8930:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8931:                         if ($xml_classlist =~ /^error/) {
                   8932:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8933:                         } else {
1.1172.2.96  raeburn  8934:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8935:                                 print FILE &unescape($xml_classlist);
                   8936:                                 close(FILE);
1.526     raeburn  8937:                             } else {
                   8938:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8939:                             }
                   8940:                         }
                   8941:                     }
                   8942:                 }
                   8943:             }
                   8944:         }
                   8945:         return 'ok';
                   8946:     }
                   8947:     return 'error';
                   8948: }
                   8949: 
1.242     www      8950: sub get_query_reply {
1.1172.2.79  raeburn  8951:     my ($queryid,$sleep,$loopmax) = @_;
                   8952:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8953:         $sleep = 0.2;
                   8954:     }
                   8955:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8956:         $loopmax = 100;
                   8957:     }
1.1117    foxr     8958:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8959:     my $reply='';
1.1172.2.79  raeburn  8960:     for (1..$loopmax) {
                   8961: 	sleep($sleep);
1.240     www      8962:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8963: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8964: 		$reply = join('',<$fh>);
                   8965: 		close($fh);
1.240     www      8966: 	   } else { return 'error: reply_file_error'; }
1.242     www      8967:            return &unescape($reply);
                   8968: 	}
1.240     www      8969:     }
1.242     www      8970:     return 'timeout:'.$queryid;
1.240     www      8971: }
                   8972: 
                   8973: sub courselog_query {
1.241     www      8974: #
                   8975: # possible filters:
                   8976: # url: url or symb
                   8977: # username
                   8978: # domain
                   8979: # action: view, submit, grade
                   8980: # start: timestamp
                   8981: # end: timestamp
                   8982: #
1.240     www      8983:     my (%filters)=@_;
1.620     albertel 8984:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8985:     if ($filters{'url'}) {
                   8986: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8987:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8988:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8989:     }
1.620     albertel 8990:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8991:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8992:     return &log_query($cname,$cdom,'courselog',%filters);
                   8993: }
                   8994: 
                   8995: sub userlog_query {
1.858     raeburn  8996: #
                   8997: # possible filters:
                   8998: # action: log check role
                   8999: # start: timestamp
                   9000: # end: timestamp
                   9001: #
1.240     www      9002:     my ($uname,$udom,%filters)=@_;
                   9003:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9004: }
                   9005: 
1.506     raeburn  9006: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9007: 
                   9008: sub auto_run {
1.508     raeburn  9009:     my ($cnum,$cdom) = @_;
1.876     raeburn  9010:     my $response = 0;
                   9011:     my $settings;
                   9012:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9013:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9014:         $settings = $domconfig{'autoenroll'};
                   9015:         if ($settings->{'run'} eq '1') {
                   9016:             $response = 1;
                   9017:         }
                   9018:     } else {
1.934     raeburn  9019:         my $homeserver;
                   9020:         if (&is_course($cdom,$cnum)) {
                   9021:             $homeserver = &homeserver($cnum,$cdom);
                   9022:         } else {
                   9023:             $homeserver = &domain($cdom,'primary');
                   9024:         }
                   9025:         if ($homeserver ne 'no_host') {
                   9026:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9027:         }
1.876     raeburn  9028:     }
1.506     raeburn  9029:     return $response;
                   9030: }
1.776     albertel 9031: 
1.506     raeburn  9032: sub auto_get_sections {
1.508     raeburn  9033:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9034:     my $homeserver;
                   9035:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9036:         $homeserver = &homeserver($cnum,$cdom);
                   9037:     }
                   9038:     if (!defined($homeserver)) { 
                   9039:         if ($cdom =~ /^$match_domain$/) {
                   9040:             $homeserver = &domain($cdom,'primary');
                   9041:         }
                   9042:     }
                   9043:     my @secs;
                   9044:     if (defined($homeserver)) {
                   9045:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9046:         unless ($response eq 'refused') {
                   9047:             @secs = split(/:/,$response);
                   9048:         }
1.506     raeburn  9049:     }
                   9050:     return @secs;
                   9051: }
1.776     albertel 9052: 
1.506     raeburn  9053: sub auto_new_course {
1.1099    raeburn  9054:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9055:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9056:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9057:     return $response;
                   9058: }
1.776     albertel 9059: 
1.506     raeburn  9060: sub auto_validate_courseID {
1.508     raeburn  9061:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9062:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9063:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9064:     return $response;
                   9065: }
1.776     albertel 9066: 
1.1007    raeburn  9067: sub auto_validate_instcode {
1.1020    raeburn  9068:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9069:     my ($homeserver,$response);
                   9070:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9071:         $homeserver = &homeserver($cnum,$cdom);
                   9072:     }
                   9073:     if (!defined($homeserver)) {
                   9074:         if ($cdom =~ /^$match_domain$/) {
                   9075:             $homeserver = &domain($cdom,'primary');
                   9076:         }
                   9077:     }
1.1065    raeburn  9078:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9079:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9080:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9081:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9082: }
                   9083: 
1.506     raeburn  9084: sub auto_create_password {
1.873     raeburn  9085:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9086:     my ($homeserver,$response);
1.506     raeburn  9087:     my $create_passwd = 0;
                   9088:     my $authchk = '';
1.873     raeburn  9089:     if ($udom =~ /^$match_domain$/) {
                   9090:         $homeserver = &domain($udom,'primary');
                   9091:     }
                   9092:     if ($homeserver eq '') {
                   9093:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9094:             $homeserver = &homeserver($cnum,$cdom);
                   9095:         }
                   9096:     }
                   9097:     if ($homeserver eq '') {
                   9098:         $authchk = 'nodomain';
1.506     raeburn  9099:     } else {
1.873     raeburn  9100:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9101:         if ($response eq 'refused') {
                   9102:             $authchk = 'refused';
                   9103:         } else {
1.901     albertel 9104:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9105:         }
1.506     raeburn  9106:     }
                   9107:     return ($authparam,$create_passwd,$authchk);
                   9108: }
                   9109: 
1.706     raeburn  9110: sub auto_photo_permission {
                   9111:     my ($cnum,$cdom,$students) = @_;
                   9112:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9113:     my ($outcome,$perm_reqd,$conditions) = 
                   9114: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9115:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9116: 	return (undef,undef);
                   9117:     }
1.706     raeburn  9118:     return ($outcome,$perm_reqd,$conditions);
                   9119: }
                   9120: 
                   9121: sub auto_checkphotos {
                   9122:     my ($uname,$udom,$pid) = @_;
                   9123:     my $homeserver = &homeserver($uname,$udom);
                   9124:     my ($result,$resulttype);
                   9125:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9126: 				   &escape($uname).':'.&escape($pid),
                   9127: 				   $homeserver));
1.709     albertel 9128:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9129: 	return (undef,undef);
                   9130:     }
1.706     raeburn  9131:     if ($outcome) {
                   9132:         ($result,$resulttype) = split(/:/,$outcome);
                   9133:     } 
                   9134:     return ($result,$resulttype);
                   9135: }
                   9136: 
                   9137: sub auto_photochoice {
                   9138:     my ($cnum,$cdom) = @_;
                   9139:     my $homeserver = &homeserver($cnum,$cdom);
                   9140:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9141: 						       &escape($cdom),
                   9142: 						       $homeserver)));
1.709     albertel 9143:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9144: 	return (undef,undef);
                   9145:     }
1.706     raeburn  9146:     return ($update,$comment);
                   9147: }
                   9148: 
                   9149: sub auto_photoupdate {
                   9150:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9151:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9152:     my $host=&hostname($homeserver);
1.706     raeburn  9153:     my $cmd = '';
                   9154:     my $maxtries = 1;
1.800     albertel 9155:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9156:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9157:     }
                   9158:     $cmd =~ s/%%$//;
                   9159:     $cmd = &escape($cmd);
                   9160:     my $query = 'institutionalphotos';
                   9161:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9162:     unless ($queryid=~/^\Q$host\E\_/) {
                   9163:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9164:         return 'error: '.$queryid;
                   9165:     }
                   9166:     my $reply = &get_query_reply($queryid);
                   9167:     my $tries = 1;
                   9168:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9169:         $reply = &get_query_reply($queryid);
                   9170:         $tries ++;
                   9171:     }
                   9172:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9173:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9174:     } else {
                   9175:         my @responses = split(/:/,$reply);
                   9176:         my $outcome = shift(@responses); 
                   9177:         foreach my $item (@responses) {
                   9178:             my ($key,$value) = split(/=/,$item);
                   9179:             $$photo{$key} = $value;
                   9180:         }
                   9181:         return $outcome;
                   9182:     }
                   9183:     return 'error';
                   9184: }
                   9185: 
1.521     raeburn  9186: sub auto_instcode_format {
1.793     albertel 9187:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9188: 	$cat_order) = @_;
1.521     raeburn  9189:     my $courses = '';
1.772     raeburn  9190:     my @homeservers;
1.521     raeburn  9191:     if ($caller eq 'global') {
1.841     albertel 9192: 	my %servers = &get_servers($codedom,'library');
                   9193: 	foreach my $tryserver (keys(%servers)) {
                   9194: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9195: 		push(@homeservers,$tryserver);
                   9196: 	    }
1.584     raeburn  9197:         }
1.1022    raeburn  9198:     } elsif ($caller eq 'requests') {
                   9199:         if ($codedom =~ /^$match_domain$/) {
                   9200:             my $chome = &domain($codedom,'primary');
                   9201:             unless ($chome eq 'no_host') {
                   9202:                 push(@homeservers,$chome);
                   9203:             }
                   9204:         }
1.521     raeburn  9205:     } else {
1.772     raeburn  9206:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9207:     }
1.793     albertel 9208:     foreach my $code (keys(%{$instcodes})) {
                   9209:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9210:     }
                   9211:     chop($courses);
1.772     raeburn  9212:     my $ok_response = 0;
                   9213:     my $response;
                   9214:     while (@homeservers > 0 && $ok_response == 0) {
                   9215:         my $server = shift(@homeservers); 
                   9216:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9217:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9218:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9219: 		split(/:/,$response);
1.772     raeburn  9220:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9221:             push(@{$codetitles},&str2array($codetitles_str));
                   9222:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9223:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9224:             $ok_response = 1;
                   9225:         }
                   9226:     }
                   9227:     if ($ok_response) {
1.521     raeburn  9228:         return 'ok';
1.772     raeburn  9229:     } else {
                   9230:         return $response;
1.521     raeburn  9231:     }
                   9232: }
                   9233: 
1.792     raeburn  9234: sub auto_instcode_defaults {
                   9235:     my ($domain,$returnhash,$code_order) = @_;
                   9236:     my @homeservers;
1.841     albertel 9237: 
                   9238:     my %servers = &get_servers($domain,'library');
                   9239:     foreach my $tryserver (keys(%servers)) {
                   9240: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9241: 	    push(@homeservers,$tryserver);
                   9242: 	}
1.792     raeburn  9243:     }
1.841     albertel 9244: 
1.792     raeburn  9245:     my $response;
1.841     albertel 9246:     foreach my $server (@homeservers) {
1.792     raeburn  9247:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9248:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9249: 	
                   9250: 	foreach my $pair (split(/\&/,$response)) {
                   9251: 	    my ($name,$value)=split(/\=/,$pair);
                   9252: 	    if ($name eq 'code_order') {
                   9253: 		@{$code_order} = split(/\&/,&unescape($value));
                   9254: 	    } else {
                   9255: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9256: 	    }
                   9257: 	}
                   9258: 	return 'ok';
1.792     raeburn  9259:     }
1.841     albertel 9260: 
                   9261:     return $response;
1.1003    raeburn  9262: }
                   9263: 
                   9264: sub auto_possible_instcodes {
1.1007    raeburn  9265:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9266:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9267:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9268:         return;
                   9269:     }
1.1003    raeburn  9270:     my (@homeservers,$uhome);
                   9271:     if (defined(&domain($domain,'primary'))) {
                   9272:         $uhome=&domain($domain,'primary');
                   9273:         push(@homeservers,&domain($domain,'primary'));
                   9274:     } else {
                   9275:         my %servers = &get_servers($domain,'library');
                   9276:         foreach my $tryserver (keys(%servers)) {
                   9277:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9278:                 push(@homeservers,$tryserver);
                   9279:             }
                   9280:         }
                   9281:     }
                   9282:     my $response;
                   9283:     foreach my $server (@homeservers) {
                   9284:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9285:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9286:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9287:             split(':',$response);
                   9288:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9289:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9290:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9291:             my ($name,$value)=split('=',$item);
                   9292:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9293:         }
                   9294:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9295:             my ($name,$value)=split('=',$item);
                   9296:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9297:         }
                   9298:         return 'ok';
                   9299:     }
                   9300:     return $response;
                   9301: }
1.792     raeburn  9302: 
1.1010    raeburn  9303: sub auto_courserequest_checks {
                   9304:     my ($dom) = @_;
1.1020    raeburn  9305:     my ($homeserver,%validations);
                   9306:     if ($dom =~ /^$match_domain$/) {
                   9307:         $homeserver = &domain($dom,'primary');
                   9308:     }
                   9309:     unless ($homeserver eq 'no_host') {
                   9310:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9311:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9312:             my @items = split(/&/,$response);
                   9313:             foreach my $item (@items) {
                   9314:                 my ($key,$value) = split('=',$item);
                   9315:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9316:             }
                   9317:         }
                   9318:     }
1.1010    raeburn  9319:     return %validations; 
                   9320: }
                   9321: 
1.1020    raeburn  9322: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9323:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9324:     my ($homeserver,$response);
                   9325:     if ($dom =~ /^$match_domain$/) {
                   9326:         $homeserver = &domain($dom,'primary');
                   9327:     }
1.1172.2.43  raeburn  9328:     unless ($homeserver eq 'no_host') {
                   9329:         my $customdata;
                   9330:         if (ref($custominfo) eq 'HASH') {
                   9331:             $customdata = &freeze_escape($custominfo);
                   9332:         }
1.1020    raeburn  9333:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9334:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9335:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9336:                                     $customdata,$homeserver));
1.1020    raeburn  9337:     }
                   9338:     return $response;
                   9339: }
                   9340: 
1.777     albertel 9341: sub auto_validate_class_sec {
1.918     raeburn  9342:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9343:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9344:     my $ownerlist;
                   9345:     if (ref($owners) eq 'ARRAY') {
                   9346:         $ownerlist = join(',',@{$owners});
                   9347:     } else {
                   9348:         $ownerlist = $owners;
                   9349:     }
1.773     raeburn  9350:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9351:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9352:     return $response;
                   9353: }
                   9354: 
1.1172.2.94  raeburn  9355: sub auto_validate_instclasses {
                   9356:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9357:     my ($homeserver,%validations);
                   9358:     $homeserver = &homeserver($cnum,$cdom);
                   9359:     unless ($homeserver eq 'no_host') {
                   9360:         my $ownerlist;
                   9361:         if (ref($owners) eq 'ARRAY') {
                   9362:             $ownerlist = join(',',@{$owners});
                   9363:         } else {
                   9364:             $ownerlist = $owners;
                   9365:         }
                   9366:         if (ref($classesref) eq 'HASH') {
                   9367:             my $classes = &freeze_escape($classesref);
                   9368:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9369:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9370:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9371:                 my @items = split(/&/,$response);
                   9372:                 foreach my $item (@items) {
                   9373:                     my ($key,$value) = split('=',$item);
                   9374:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9375:                 }
                   9376:             }
                   9377:         }
                   9378:     }
                   9379:     return %validations;
                   9380: }
                   9381: 
1.1172.2.38  raeburn  9382: sub auto_crsreq_update {
                   9383:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9384:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9385:     my ($homeserver,%crsreqresponse);
                   9386:     if ($cdom =~ /^$match_domain$/) {
                   9387:         $homeserver = &domain($cdom,'primary');
                   9388:     }
                   9389:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9390:         my $info;
                   9391:         if (ref($inbound) eq 'HASH') {
                   9392:             $info = &freeze_escape($inbound);
                   9393:         }
                   9394:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9395:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9396:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9397:                             &escape($title).':'.&escape($code).':'.
                   9398:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9399:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9400:             my @items = split(/&/,$response);
                   9401:             foreach my $item (@items) {
                   9402:                 my ($key,$value) = split('=',$item);
                   9403:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9404:             }
                   9405:         }
                   9406:     }
                   9407:     return \%crsreqresponse;
                   9408: }
                   9409: 
1.1172.2.78  raeburn  9410: sub auto_export_grades {
                   9411:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9412:     my ($homeserver,%exportresponse);
                   9413:     if ($cdom =~ /^$match_domain$/) {
                   9414:         $homeserver = &domain($cdom,'primary');
                   9415:     }
                   9416:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9417:         my $info;
                   9418:         if (ref($inforef) eq 'HASH') {
                   9419:             $info = &freeze_escape($inforef);
                   9420:         }
                   9421:         if (ref($gradesref) eq 'HASH') {
                   9422:             my $grades = &freeze_escape($gradesref);
                   9423:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9424:                                 $info.':'.$grades,$homeserver);
                   9425:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9426:                 my @items = split(/&/,$response);
                   9427:                 foreach my $item (@items) {
                   9428:                     my ($key,$value) = split('=',$item);
                   9429:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9430:                 }
                   9431:             }
                   9432:         }
                   9433:     }
                   9434:     return \%exportresponse;
                   9435: }
                   9436: 
1.1172.2.68  raeburn  9437: sub check_instcode_cloning {
                   9438:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9439:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9440:         return;
                   9441:     }
                   9442:     my $canclone;
                   9443:     if (@{$code_order} > 0) {
                   9444:         my $instcoderegexp ='^';
                   9445:         my @clonecodes = split(/\&/,$cloner);
                   9446:         foreach my $item (@{$code_order}) {
                   9447:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9448:                 foreach my $pair (@clonecodes) {
                   9449:                     my ($key,$val) = split(/\=/,$pair,2);
                   9450:                     $val = &unescape($val);
                   9451:                     if ($key eq $item) {
                   9452:                         $instcoderegexp .= '('.$val.')';
                   9453:                         last;
                   9454:                     }
                   9455:                 }
                   9456:             } else {
                   9457:                 $instcoderegexp .= $codedefaults->{$item};
                   9458:             }
                   9459:         }
                   9460:         $instcoderegexp .= '$';
                   9461:         my (@from,@to);
                   9462:         eval {
                   9463:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9464:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9465:         };
                   9466:         if ((@from > 0) && (@to > 0)) {
                   9467:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9468:             if (!@diffs) {
                   9469:                 $canclone = 1;
                   9470:             }
                   9471:         }
                   9472:     }
                   9473:     return $canclone;
                   9474: }
                   9475: 
                   9476: sub default_instcode_cloning {
                   9477:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9478:     my (%codedefaults,@code_order,$canclone);
                   9479:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9480:         %codedefaults = %{$codedefaultsref};
                   9481:         @code_order = @{$codeorderref};
                   9482:     } elsif ($clonedom) {
                   9483:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9484:     }
                   9485:     if (($domdefclone) && (@code_order)) {
                   9486:         my @clonecodes = split(/\+/,$domdefclone);
                   9487:         my $instcoderegexp ='^';
                   9488:         foreach my $item (@code_order) {
                   9489:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9490:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9491:             } else {
                   9492:                 $instcoderegexp .= $codedefaults{$item};
                   9493:             }
                   9494:         }
                   9495:         $instcoderegexp .= '$';
                   9496:         my (@from,@to);
                   9497:         eval {
                   9498:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9499:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9500:         };
                   9501:         if ((@from > 0) && (@to > 0)) {
                   9502:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9503:             if (!@diffs) {
                   9504:                 $canclone = 1;
                   9505:             }
                   9506:         }
                   9507:     }
                   9508:     return $canclone;
                   9509: }
                   9510: 
1.679     raeburn  9511: # ------------------------------------------------------- Course Group routines
                   9512: 
                   9513: sub get_coursegroups {
1.809     raeburn  9514:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9515:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9516: }
                   9517: 
1.679     raeburn  9518: sub modify_coursegroup {
                   9519:     my ($cdom,$cnum,$groupsettings) = @_;
                   9520:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9521: }
                   9522: 
1.809     raeburn  9523: sub toggle_coursegroup_status {
                   9524:     my ($cdom,$cnum,$group,$action) = @_;
                   9525:     my ($from_namespace,$to_namespace);
                   9526:     if ($action eq 'delete') {
                   9527:         $from_namespace = 'coursegroups';
                   9528:         $to_namespace = 'deleted_groups';
                   9529:     } else {
                   9530:         $from_namespace = 'deleted_groups';
                   9531:         $to_namespace = 'coursegroups';
                   9532:     }
                   9533:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9534:     if (my $tmp = &error(%curr_group)) {
                   9535:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9536:         return ('read error',$tmp);
                   9537:     } else {
                   9538:         my %savedsettings = %curr_group; 
1.809     raeburn  9539:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9540:         my $deloutcome;
                   9541:         if ($result eq 'ok') {
1.809     raeburn  9542:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9543:         } else {
                   9544:             return ('write error',$result);
                   9545:         }
                   9546:         if ($deloutcome eq 'ok') {
                   9547:             return 'ok';
                   9548:         } else {
                   9549:             return ('delete error',$deloutcome);
                   9550:         }
                   9551:     }
                   9552: }
                   9553: 
1.679     raeburn  9554: sub modify_group_roles {
1.957     raeburn  9555:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9556:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9557:     my $role = 'gr/'.&escape($userprivs);
                   9558:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9559:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9560:     if ($result eq 'ok') {
                   9561:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9562:     }
1.679     raeburn  9563:     return $result;
                   9564: }
                   9565: 
                   9566: sub modify_coursegroup_membership {
                   9567:     my ($cdom,$cnum,$membership) = @_;
                   9568:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9569:     return $result;
                   9570: }
                   9571: 
1.682     raeburn  9572: sub get_active_groups {
                   9573:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9574:     my $now = time;
                   9575:     my %groups = ();
                   9576:     foreach my $key (keys(%env)) {
1.811     albertel 9577:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9578:             my ($start,$end) = split(/\./,$env{$key});
                   9579:             if (($end!=0) && ($end<$now)) { next; }
                   9580:             if (($start!=0) && ($start>$now)) { next; }
                   9581:             if ($1 eq $cdom && $2 eq $cnum) {
                   9582:                 $groups{$3} = $env{$key} ;
                   9583:             }
                   9584:         }
                   9585:     }
                   9586:     return %groups;
                   9587: }
                   9588: 
1.683     raeburn  9589: sub get_group_membership {
                   9590:     my ($cdom,$cnum,$group) = @_;
                   9591:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9592: }
                   9593: 
                   9594: sub get_users_groups {
                   9595:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9596:     my @usersgroups;
1.683     raeburn  9597:     my $cachetime=1800;
                   9598: 
                   9599:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9600:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9601:     if (defined($cached)) {
1.734     albertel 9602:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9603:     } else {  
                   9604:         $grouplist = '';
1.816     raeburn  9605:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9606:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9607:         my $access_end = $env{'course.'.$courseid.
                   9608:                               '.default_enrollment_end_date'};
                   9609:         my $now = time;
                   9610:         foreach my $key (keys(%roleshash)) {
                   9611:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9612:                 my $group = $1;
                   9613:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9614:                     my $start = $2;
                   9615:                     my $end = $1;
                   9616:                     if ($start == -1) { next; } # deleted from group
                   9617:                     if (($start!=0) && ($start>$now)) { next; }
                   9618:                     if (($end!=0) && ($end<$now)) {
                   9619:                         if ($access_end && $access_end < $now) {
                   9620:                             if ($access_end - $end < 86400) {
                   9621:                                 push(@usersgroups,$group);
1.733     raeburn  9622:                             }
                   9623:                         }
1.817     raeburn  9624:                         next;
1.733     raeburn  9625:                     }
1.817     raeburn  9626:                     push(@usersgroups,$group);
1.683     raeburn  9627:                 }
                   9628:             }
                   9629:         }
1.817     raeburn  9630:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9631:         $grouplist = join(':',@usersgroups);
                   9632:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9633:     }
1.733     raeburn  9634:     return @usersgroups;
1.683     raeburn  9635: }
                   9636: 
                   9637: sub devalidate_getgroups_cache {
                   9638:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9639:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9640: 
1.683     raeburn  9641:     my $hashid="$udom:$uname:$courseid";
                   9642:     &devalidate_cache_new('getgroups',$hashid);
                   9643: }
                   9644: 
1.12      www      9645: # ------------------------------------------------------------------ Plain Text
                   9646: 
                   9647: sub plaintext {
1.988     raeburn  9648:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9649:     if ($short =~ m{^cr/}) {
1.758     albertel 9650: 	return (split('/',$short))[-1];
                   9651:     }
1.742     raeburn  9652:     if (!defined($cid)) {
                   9653:         $cid = $env{'request.course.id'};
                   9654:     }
                   9655:     my %rolenames = (
1.1008    raeburn  9656:                       Course    => 'std',
                   9657:                       Community => 'alt1',
1.742     raeburn  9658:                     );
1.1037    raeburn  9659:     if ($cid ne '') {
                   9660:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9661:             unless ($forcedefault) {
                   9662:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9663:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9664:                 return &Apache::lonlocal::mt($roletext);
                   9665:             }
                   9666:         }
                   9667:     }
                   9668:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9669:         (defined($rolenames{$type})) && 
                   9670:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9671:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9672:     } elsif ($cid ne '') {
                   9673:         my $crstype = $env{'course.'.$cid.'.type'};
                   9674:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9675:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9676:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9677:         }
1.742     raeburn  9678:     }
1.1037    raeburn  9679:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9680: }
                   9681: 
                   9682: # ----------------------------------------------------------------- Assign Role
                   9683: 
                   9684: sub assignrole {
1.957     raeburn  9685:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9686:         $context)=@_;
1.21      www      9687:     my $mrole;
                   9688:     if ($role =~ /^cr\//) {
1.393     www      9689:         my $cwosec=$url;
1.811     albertel 9690:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9691: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9692:            my $refused = 1;
                   9693:            if ($context eq 'requestcourses') {
                   9694:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9695:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9696:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9697:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9698:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9699:                            if ($crsenv{'internal.courseowner'} eq
                   9700:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9701:                                $refused = '';
                   9702:                            }
                   9703:                        }
                   9704:                    }
                   9705:                }
                   9706:            }
                   9707:            if ($refused) {
                   9708:                &logthis('Refused custom assignrole: '.
                   9709:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9710:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9711:                return 'refused';
                   9712:            }
1.104     www      9713:         }
1.21      www      9714:         $mrole='cr';
1.678     raeburn  9715:     } elsif ($role =~ /^gr\//) {
                   9716:         my $cwogrp=$url;
1.811     albertel 9717:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9718:         unless (&allowed('mdg',$cwogrp)) {
                   9719:             &logthis('Refused group assignrole: '.
                   9720:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9721:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9722:             return 'refused';
                   9723:         }
                   9724:         $mrole='gr';
1.21      www      9725:     } else {
1.82      www      9726:         my $cwosec=$url;
1.811     albertel 9727:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9728:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9729:             my $refused;
                   9730:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9731:                 if (!(&allowed('c'.$role,$url))) {
                   9732:                     $refused = 1;
                   9733:                 }
                   9734:             } else {
                   9735:                 $refused = 1;
                   9736:             }
1.947     raeburn  9737:             if ($refused) {
1.1045    raeburn  9738:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9739:                 if (!$selfenroll && $context eq 'course') {
                   9740:                     my %crsenv;
                   9741:                     if ($role eq 'cc' || $role eq 'co') {
                   9742:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9743:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9744:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9745:                                 if ($crsenv{'internal.courseowner'} eq 
                   9746:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9747:                                     $refused = '';
                   9748:                                 }
                   9749:                             }
                   9750:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9751:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9752:                                 if ($crsenv{'internal.courseowner'} eq 
                   9753:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9754:                                     $refused = '';
                   9755:                                 }
                   9756:                             }
                   9757:                         }
                   9758:                     }
                   9759:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9760:                     $refused = '';
1.1017    raeburn  9761:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9762:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9763:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9764:                         my $wrongcc;
                   9765:                         if ($cnum =~ /^$match_community$/) {
                   9766:                             $wrongcc = 1 if ($role eq 'cc');
                   9767:                         } else {
                   9768:                             $wrongcc = 1 if ($role eq 'co');
                   9769:                         }
                   9770:                         unless ($wrongcc) {
                   9771:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9772:                             if ($crsenv{'internal.courseowner'} eq 
                   9773:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9774:                                 $refused = '';
                   9775:                             }
1.1017    raeburn  9776:                         }
                   9777:                     }
1.1172.2.9  raeburn  9778:                 } elsif ($context eq 'requestauthor') {
                   9779:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9780:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9781:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9782:                             $refused = '';
                   9783:                         } else {
                   9784:                             my %domdefaults = &get_domain_defaults($udom);
                   9785:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9786:                                 my $checkbystatus;
                   9787:                                 if ($env{'user.adv'}) {
                   9788:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9789:                                     if ($disposition eq 'automatic') {
                   9790:                                         $refused = '';
                   9791:                                     } elsif ($disposition eq '') {
                   9792:                                         $checkbystatus = 1;
                   9793:                                     }
                   9794:                                 } else {
                   9795:                                     $checkbystatus = 1;
                   9796:                                 }
                   9797:                                 if ($checkbystatus) {
                   9798:                                     if ($env{'environment.inststatus'}) {
                   9799:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9800:                                         foreach my $type (@inststatuses) {
                   9801:                                             if (($type ne '') &&
                   9802:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9803:                                                 $refused = '';
                   9804:                                             }
                   9805:                                         }
                   9806:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9807:                                         $refused = '';
                   9808:                                     }
                   9809:                                 }
                   9810:                             }
                   9811:                         }
                   9812:                     }
1.1017    raeburn  9813:                 }
                   9814:                 if ($refused) {
1.947     raeburn  9815:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9816:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9817: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9818:                     return 'refused';
                   9819:                 }
1.932     raeburn  9820:             }
1.1131    raeburn  9821:         } elsif ($role eq 'au') {
                   9822:             if ($url ne '/'.$udom.'/') {
                   9823:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9824:                          ' to assign author role for '.$uname.':'.$udom.
                   9825:                          ' in domain: '.$url.' refused (wrong domain).');
                   9826:                 return 'refused';
                   9827:             }
1.104     www      9828:         }
1.21      www      9829:         $mrole=$role;
                   9830:     }
1.620     albertel 9831:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9832:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9833:     if ($end) { $command.='_'.$end; }
1.21      www      9834:     if ($start) {
                   9835: 	if ($end) { 
1.81      www      9836:            $command.='_'.$start; 
1.21      www      9837:         } else {
1.81      www      9838:            $command.='_0_'.$start;
1.21      www      9839:         }
                   9840:     }
1.739     raeburn  9841:     my $origstart = $start;
                   9842:     my $origend = $end;
1.957     raeburn  9843:     my $delflag;
1.357     www      9844: # actually delete
                   9845:     if ($deleteflag) {
1.373     www      9846: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9847: # modify command to delete the role
1.620     albertel 9848:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9849:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9850: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9851: # set start and finish to negative values for userrolelog
                   9852:            $start=-1;
                   9853:            $end=-1;
1.957     raeburn  9854:            $delflag = 1;
1.357     www      9855:         }
                   9856:     }
                   9857: # send command
1.349     www      9858:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9859: # log new user role if status is ok
1.349     www      9860:     if ($answer eq 'ok') {
1.663     raeburn  9861: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9862:         if (($role eq 'cc') || ($role eq 'in') ||
                   9863:             ($role eq 'ep') || ($role eq 'ad') ||
                   9864:             ($role eq 'ta') || ($role eq 'st') ||
                   9865:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9866:             ($role eq 'co')) {
1.1172.2.13  raeburn  9867: # for course roles, perform group memberships changes triggered by role change.
                   9868:             unless ($role =~ /^gr/) {
                   9869:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9870:                                                  $origstart,$selfenroll,$context);
                   9871:             }
1.1172.2.9  raeburn  9872:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9873:                            $selfenroll,$context);
                   9874:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9875:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9876:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9877:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9878:                            $context);
                   9879:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9880:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9881:                              $context);
                   9882:         }
1.1053    raeburn  9883:         if ($role eq 'cc') {
                   9884:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9885:         }
1.349     www      9886:     }
                   9887:     return $answer;
1.169     harris41 9888: }
                   9889: 
1.1053    raeburn  9890: sub autoupdate_coowners {
                   9891:     my ($url,$end,$start,$uname,$udom) = @_;
                   9892:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9893:     if (($cdom ne '') && ($cnum ne '')) {
                   9894:         my $now = time;
                   9895:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9896:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9897:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9898:             my $instcode = $coursehash{'internal.coursecode'};
                   9899:             if ($instcode ne '') {
1.1056    raeburn  9900:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9901:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9902:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9903:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9904:                         if ($result eq 'valid') {
                   9905:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9906:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9907:                                     push(@newcoowners,$coowner);
                   9908:                                 }
                   9909:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9910:                                     push(@newcoowners,$uname.':'.$udom);
                   9911:                                 }
                   9912:                                 @newcoowners = sort(@newcoowners);
                   9913:                             } else {
                   9914:                                 push(@newcoowners,$uname.':'.$udom);
                   9915:                             }
                   9916:                         } else {
                   9917:                             if ($coursehash{'internal.co-owners'}) {
                   9918:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9919:                                     unless ($coowner eq $uname.':'.$udom) {
                   9920:                                         push(@newcoowners,$coowner);
                   9921:                                     }
                   9922:                                 }
                   9923:                                 unless (@newcoowners > 0) {
                   9924:                                     $delcoowners = 1;
                   9925:                                     $coowners = '';
                   9926:                                 }
                   9927:                             }
                   9928:                         }
                   9929:                         if (@newcoowners || $delcoowners) {
                   9930:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9931:                                             $delcoowners,@newcoowners);
                   9932:                         }
                   9933:                     }
                   9934:                 }
                   9935:             }
                   9936:         }
                   9937:     }
                   9938: }
                   9939: 
                   9940: sub store_coowners {
                   9941:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9942:     my $cid = $cdom.'_'.$cnum;
                   9943:     my ($coowners,$delresult,$putresult);
                   9944:     if (@newcoowners) {
                   9945:         $coowners = join(',',@newcoowners);
                   9946:         my %coownershash = (
                   9947:                             'internal.co-owners' => $coowners,
                   9948:                            );
                   9949:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9950:         if ($putresult eq 'ok') {
                   9951:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9952:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9953:             }
                   9954:         }
                   9955:     }
                   9956:     if ($delcoowners) {
                   9957:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9958:         if ($delresult eq 'ok') {
                   9959:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9960:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9961:             }
                   9962:         }
                   9963:     }
                   9964:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9965:         my %crsinfo =
                   9966:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9967:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9968:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9969:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9970:         }
                   9971:     }
                   9972: }
                   9973: 
1.169     harris41 9974: # -------------------------------------------------- Modify user authentication
1.197     www      9975: # Overrides without validation
                   9976: 
1.169     harris41 9977: sub modifyuserauth {
                   9978:     my ($udom,$uname,$umode,$upass)=@_;
                   9979:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9980:     my $allowed;
                   9981:     if (&allowed('mau',$udom)) {
                   9982:         $allowed = 1;
                   9983:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9984:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9985:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9986:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9987:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9988:         if (($cdom ne '') && ($cnum ne '')) {
                   9989:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9990:             if ($is_owner) {
                   9991:                 $allowed = 1;
                   9992:             }
                   9993:         }
                   9994:     }
                   9995:     unless ($allowed) { return 'refused'; }
1.197     www      9996:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9997:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9998:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9999:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10000: 		     &escape($upass),$uhome);
1.1172.2.118.  .14(raeb 10001:-21):     my $ip = &get_requestor_ip();
1.620     albertel 10002:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10003:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.118.  .14(raeb 10004:-21):          '(Remote '.$ip.'): '.$reply);
1.197     www      10005:     &log($udom,,$uname,$uhome,
1.620     albertel 10006:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10007:                                      $env{'user.name'}.', '.$umode.
1.1172.2.118.  .14(raeb 10008:-21):          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10009:     unless ($reply eq 'ok') {
1.197     www      10010:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10011: 	return 'error: '.$reply;
                   10012:     }   
1.170     harris41 10013:     return 'ok';
1.80      www      10014: }
                   10015: 
1.81      www      10016: # --------------------------------------------------------------- Modify a user
1.80      www      10017: 
1.81      www      10018: sub modifyuser {
1.206     matthew  10019:     my ($udom,    $uname, $uid,
                   10020:         $umode,   $upass, $first,
                   10021:         $middle,  $last,  $gene,
1.1058    raeburn  10022:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10023:     $udom= &LONCAPA::clean_domain($udom);
                   10024:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10025:     my $showcandelete = 'none';
                   10026:     if (ref($candelete) eq 'ARRAY') {
                   10027:         if (@{$candelete} > 0) {
                   10028:             $showcandelete = join(', ',@{$candelete});
                   10029:         }
                   10030:     }
1.81      www      10031:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10032:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10033: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10034:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10035:                                      ' desiredhome not specified'). 
1.620     albertel 10036:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10037:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10038:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10039:     my $newuser;
                   10040:     if ($uhome eq 'no_host') {
                   10041:         $newuser = 1;
                   10042:     }
1.80      www      10043: # ----------------------------------------------------------------- Create User
1.406     albertel 10044:     if (($uhome eq 'no_host') && 
                   10045: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10046:         my $unhome='';
1.844     albertel 10047:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10048:             $unhome = $desiredhome;
1.620     albertel 10049: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10050: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10051:         } else { # load balancing routine for determining $unhome
1.81      www      10052:             my $loadm=10000000;
1.841     albertel 10053: 	    my %servers = &get_servers($udom,'library');
                   10054: 	    foreach my $tryserver (keys(%servers)) {
                   10055: 		my $answer=reply('load',$tryserver);
                   10056: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10057: 		    $loadm=$answer;
                   10058: 		    $unhome=$tryserver;
                   10059: 		}
1.80      www      10060: 	    }
                   10061:         }
                   10062:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10063: 	    return 'error: unable to find a home server for '.$uname.
                   10064:                    ' in domain '.$udom;
1.80      www      10065:         }
                   10066:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10067:                          &escape($upass),$unhome);
                   10068: 	unless ($reply eq 'ok') {
                   10069:             return 'error: '.$reply;
                   10070:         }   
1.230     stredwic 10071:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10072:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10073: 	    return 'error: unable verify users home machine.';
1.80      www      10074:         }
1.209     matthew  10075:     }   # End of creation of new user
1.80      www      10076: # ---------------------------------------------------------------------- Add ID
                   10077:     if ($uid) {
                   10078:        $uid=~tr/A-Z/a-z/;
                   10079:        my %uidhash=&idrget($udom,$uname);
1.196     www      10080:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10081:          && (!$forceid)) {
1.80      www      10082: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10083: 	      return 'error: user id "'.$uid.'" does not match '.
                   10084:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10085:           }
                   10086:        } else {
                   10087: 	  &idput($udom,($uname => $uid));
                   10088:        }
                   10089:     }
                   10090: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10091:     my @tmp=&get('environment',
1.899     raeburn  10092: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10093:                     'permanentemail','inststatus'],
1.134     albertel 10094: 		   $udom,$uname);
1.1075    raeburn  10095:     my (%names,%oldnames);
1.313     matthew  10096:     if ($tmp[0] =~ m/^error:.*/) { 
                   10097:         %names=(); 
                   10098:     } else {
                   10099:         %names = @tmp;
1.1075    raeburn  10100:         %oldnames = %names;
1.313     matthew  10101:     }
1.388     www      10102: #
1.1058    raeburn  10103: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10104: # of users did not contain them), do not overwrite existing values
                   10105: # unless field is in $candelete array ref.  
                   10106: #
                   10107: 
                   10108:     my @fields = ('firstname','middlename','lastname','generation',
                   10109:                   'permanentemail','id');
                   10110:     my %newvalues;
                   10111:     if (ref($candelete) eq 'ARRAY') {
                   10112:         foreach my $field (@fields) {
                   10113:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10114:                 if ($field eq 'firstname') {
                   10115:                     $names{$field} = $first;
                   10116:                 } elsif ($field eq 'middlename') {
                   10117:                     $names{$field} = $middle;
                   10118:                 } elsif ($field eq 'lastname') {
                   10119:                     $names{$field} = $last;
                   10120:                 } elsif ($field eq 'generation') { 
                   10121:                     $names{$field} = $gene;
                   10122:                 } elsif ($field eq 'permanentemail') {
                   10123:                     $names{$field} = $email;
                   10124:                 } elsif ($field eq 'id') {
                   10125:                     $names{$field}  = $uid;
                   10126:                 }
                   10127:             }
                   10128:         }
                   10129:     }
1.388     www      10130:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10131:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10132:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10133:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10134:     if ($email) {
                   10135:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10136:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10137:     }
1.899     raeburn  10138:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10139:     if (defined($inststatus)) {
                   10140:         $names{'inststatus'} = '';
                   10141:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10142:         if (ref($usertypes) eq 'HASH') {
                   10143:             my @okstatuses; 
                   10144:             foreach my $item (split(/:/,$inststatus)) {
                   10145:                 if (defined($usertypes->{$item})) {
                   10146:                     push(@okstatuses,$item);  
                   10147:                 }
                   10148:             }
                   10149:             if (@okstatuses) {
                   10150:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10151:             }
                   10152:         }
                   10153:     }
1.1075    raeburn  10154:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10155:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10156:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10157:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10158:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10159:     } else {
                   10160:         $logmsg .= ' during self creation';
                   10161:     }
1.1075    raeburn  10162:     my $changed;
                   10163:     if ($newuser) {
                   10164:         $changed = 1;
                   10165:     } else {
                   10166:         foreach my $field (@fields) {
                   10167:             if ($names{$field} ne $oldnames{$field}) {
                   10168:                 $changed = 1;
                   10169:                 last;
                   10170:             }
                   10171:         }
                   10172:     }
                   10173:     unless ($changed) {
                   10174:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10175:         &logthis($logmsg);
                   10176:         return 'ok';
                   10177:     }
                   10178:     my $reply = &put('environment', \%names, $udom,$uname);
                   10179:     if ($reply ne 'ok') { 
                   10180:         return 'error: '.$reply;
                   10181:     }
1.1087    raeburn  10182:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10183:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10184:     }
1.1075    raeburn  10185:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10186:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10187:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10188:     &logthis($logmsg);
1.134     albertel 10189:     return 'ok';
1.80      www      10190: }
                   10191: 
1.81      www      10192: # -------------------------------------------------------------- Modify student
1.80      www      10193: 
1.81      www      10194: sub modifystudent {
                   10195:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10196:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10197:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10198:     if (!$cid) {
1.620     albertel 10199: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10200: 	    return 'not_in_class';
                   10201: 	}
1.80      www      10202:     }
                   10203: # --------------------------------------------------------------- Make the user
1.81      www      10204:     my $reply=&modifyuser
1.209     matthew  10205: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10206:          $desiredhome,$email,$inststatus);
1.80      www      10207:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10208:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10209:     # student's environment
1.297     matthew  10210:     $uid = undef if (!$forceid);
1.455     albertel 10211:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10212: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10213:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10214:     return $reply;
                   10215: }
                   10216: 
                   10217: sub modify_student_enrollment {
1.1172.2.23  raeburn  10218:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10219:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10220:     my ($cdom,$cnum,$chome);
                   10221:     if (!$cid) {
1.620     albertel 10222: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10223: 	    return 'not_in_class';
                   10224: 	}
1.620     albertel 10225: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10226: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10227:     } else {
                   10228: 	($cdom,$cnum)=split(/_/,$cid);
                   10229:     }
1.620     albertel 10230:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10231:     if (!$chome) {
1.457     raeburn  10232: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10233:     }
1.455     albertel 10234:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10235:     # Make sure the user exists
1.81      www      10236:     my $uhome=&homeserver($uname,$udom);
                   10237:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10238: 	return 'error: no such user';
                   10239:     }
1.297     matthew  10240:     # Get student data if we were not given enough information
                   10241:     if (!defined($first)  || $first  eq '' || 
                   10242:         !defined($last)   || $last   eq '' || 
                   10243:         !defined($uid)    || $uid    eq '' || 
                   10244:         !defined($middle) || $middle eq '' || 
                   10245:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10246:         # They did not supply us with enough data to enroll the student, so
                   10247:         # we need to pick up more information.
1.297     matthew  10248:         my %tmp = &get('environment',
1.294     matthew  10249:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10250:                        ,$udom,$uname);
                   10251: 
1.800     albertel 10252:         #foreach my $key (keys(%tmp)) {
                   10253:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10254:         #}
1.294     matthew  10255:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10256:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10257:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10258:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10259:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10260:     }
1.556     albertel 10261:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10262:     my $user = "$uname:$udom";
                   10263:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10264:     my $reply=cput('classlist',
1.1148    raeburn  10265: 		   {$user => 
1.1172.2.76  raeburn  10266: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10267: 		   $cdom,$cnum);
1.1148    raeburn  10268:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10269:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10270:     } else { 
1.81      www      10271: 	return 'error: '.$reply;
                   10272:     }
1.297     matthew  10273:     # Add student role to user
1.83      www      10274:     my $uurl='/'.$cid;
1.81      www      10275:     $uurl=~s/\_/\//g;
                   10276:     if ($usec) {
                   10277: 	$uurl.='/'.$usec;
                   10278:     }
1.1148    raeburn  10279:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10280:                              $selfenroll,$context);
                   10281:     if ($result ne 'ok') {
                   10282:         if ($old_entry{$user} ne '') {
                   10283:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10284:         } else {
                   10285:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10286:         }
                   10287:     }
                   10288:     return $result; 
1.21      www      10289: }
                   10290: 
1.556     albertel 10291: sub format_name {
                   10292:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10293:     my $name;
                   10294:     if ($first ne 'lastname') {
                   10295: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10296:     } else {
                   10297: 	if ($lastname=~/\S/) {
                   10298: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10299: 	    $name=~s/\s+,/,/;
                   10300: 	} else {
                   10301: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10302: 	}
                   10303:     }
                   10304:     $name=~s/^\s+//;
                   10305:     $name=~s/\s+$//;
                   10306:     $name=~s/\s+/ /g;
                   10307:     return $name;
                   10308: }
                   10309: 
1.84      www      10310: # ------------------------------------------------- Write to course preferences
                   10311: 
                   10312: sub writecoursepref {
                   10313:     my ($courseid,%prefs)=@_;
                   10314:     $courseid=~s/^\///;
                   10315:     $courseid=~s/\_/\//g;
                   10316:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10317:     my $chome=homeserver($cnum,$cdomain);
                   10318:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10319: 	return 'error: no such course';
                   10320:     }
                   10321:     my $cstring='';
1.800     albertel 10322:     foreach my $pref (keys(%prefs)) {
                   10323: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10324:     }
1.84      www      10325:     $cstring=~s/\&$//;
                   10326:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10327: }
                   10328: 
                   10329: # ---------------------------------------------------------- Make/modify course
                   10330: 
                   10331: sub createcourse {
1.741     raeburn  10332:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118.  .6(raebu 10333:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10334:     $url=&declutter($url);
                   10335:     my $cid='';
1.1028    raeburn  10336:     if ($context eq 'requestcourses') {
                   10337:         my $can_create = 0;
                   10338:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10339:         if ($udom eq $ownerdom) {
1.1172.2.118.  .6(raebu 10340:20):             my $reload;
                   10341:20):             if (($callercontext eq 'auto') &&
                   10342:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10343:20):                 $reload = 'reload';
                   10344:20):             }
                   10345:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10346:                                   $context)) {
                   10347:                 $can_create = 1;
                   10348:             }
                   10349:         } else {
                   10350:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10351:                                            $category);
                   10352:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10353:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10354:                 if (@curr > 0) {
                   10355:                     my @options = qw(approval validate autolimit);
                   10356:                     my $optregex = join('|',@options);
                   10357:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10358:                         $can_create = 1;
                   10359:                     }
                   10360:                 }
                   10361:             }
                   10362:         }
                   10363:         if ($can_create) {
                   10364:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10365:                 unless (&allowed('ccc',$udom)) {
                   10366:                     return 'refused'; 
                   10367:                 }
1.1017    raeburn  10368:             }
                   10369:         } else {
                   10370:             return 'refused';
                   10371:         }
1.1028    raeburn  10372:     } elsif (!&allowed('ccc',$udom)) {
                   10373:         return 'refused';
1.84      www      10374:     }
1.1011    raeburn  10375: # --------------------------------------------------------------- Get Unique ID
                   10376:     my $uname;
                   10377:     if ($cnum =~ /^$match_courseid$/) {
                   10378:         my $chome=&homeserver($cnum,$udom,'true');
                   10379:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10380:             $uname = $cnum;
                   10381:         } else {
1.1038    raeburn  10382:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10383:         }
                   10384:     } else {
1.1038    raeburn  10385:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10386:     }
                   10387:     return $uname if ($uname =~ /^error/);
                   10388: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10389:     if (!defined($course_server)) {
                   10390:         if (defined(&domain($udom,'primary'))) {
                   10391:             $course_server = &domain($udom,'primary');
                   10392:         } else {
                   10393:             $course_server = $env{'user.home'}; 
                   10394:         }
                   10395:     }
                   10396:     my %host_servers =
                   10397:         &Apache::lonnet::get_servers($udom,'library');
                   10398:     unless ($host_servers{$course_server}) {
                   10399:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10400:     }
1.84      www      10401: # ------------------------------------------------------------- Make the course
                   10402:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10403:                       $course_server);
1.84      www      10404:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10405:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10406:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10407: 	return 'error: no such course';
                   10408:     }
1.271     www      10409: # ----------------------------------------------------------------- Course made
1.516     raeburn  10410: # log existence
1.1029    raeburn  10411:     my $now = time;
1.918     raeburn  10412:     my $newcourse = {
                   10413:                     $udom.'_'.$uname => {
1.921     raeburn  10414:                                      description => $description,
                   10415:                                      inst_code   => $inst_code,
                   10416:                                      owner       => $course_owner,
                   10417:                                      type        => $crstype,
1.1029    raeburn  10418:                                      creator     => $env{'user.name'}.':'.
                   10419:                                                     $env{'user.domain'},
                   10420:                                      created     => $now,
                   10421:                                      context     => $context,
1.918     raeburn  10422:                                                 },
                   10423:                     };
1.921     raeburn  10424:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10425: # set toplevel url
1.271     www      10426:     my $topurl=$url;
                   10427:     unless ($nonstandard) {
                   10428: # ------------------------------------------ For standard courses, make top url
                   10429:         my $mapurl=&clutter($url);
1.278     www      10430:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10431:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10432: <map>
                   10433: <resource id="1" type="start"></resource>
                   10434: <resource id="2" src="$mapurl"></resource>
                   10435: <resource id="3" type="finish"></resource>
                   10436: <link index="1" from="1" to="2"></link>
                   10437: <link index="2" from="2" to="3"></link>
                   10438: </map>
                   10439: ENDINITMAP
                   10440:         $topurl=&declutter(
1.638     albertel 10441:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10442:                           );
                   10443:     }
                   10444: # ----------------------------------------------------------- Write preferences
1.84      www      10445:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10446:                      ('description'              => $description,
                   10447:                       'url'                      => $topurl,
                   10448:                       'internal.creator'         => $env{'user.name'}.':'.
                   10449:                                                     $env{'user.domain'},
                   10450:                       'internal.created'         => $now,
                   10451:                       'internal.creationcontext' => $context)
                   10452:                     );
1.84      www      10453:     return '/'.$udom.'/'.$uname;
                   10454: }
                   10455: 
1.1011    raeburn  10456: # ------------------------------------------------------------------- Create ID
                   10457: sub generate_coursenum {
1.1038    raeburn  10458:     my ($udom,$crstype) = @_;
1.1011    raeburn  10459:     my $domdesc = &domain($udom);
                   10460:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10461:     my $first;
                   10462:     if ($crstype eq 'Community') {
                   10463:         $first = '0';
                   10464:     } else {
                   10465:         $first = int(1+rand(9)); 
                   10466:     } 
                   10467:     my $uname=$first.
1.1011    raeburn  10468:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10469:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10470:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10471: # ----------------------------------------------- Make sure that does not exist
                   10472:     my $uhome=&homeserver($uname,$udom,'true');
                   10473:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10474:         if ($crstype eq 'Community') {
                   10475:             $first = '0';
                   10476:         } else {
                   10477:             $first = int(1+rand(9));
                   10478:         }
                   10479:         $uname=$first.
1.1011    raeburn  10480:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10481:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10482:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10483:         $uhome=&homeserver($uname,$udom,'true');
                   10484:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10485:             return 'error: unable to generate unique course-ID';
                   10486:         }
                   10487:     }
                   10488:     return $uname;
                   10489: }
                   10490: 
1.813     albertel 10491: sub is_course {
1.1167    droeschl 10492:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10493:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10494:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10495:     my $uhome=&homeserver($cnum,$cdom);
                   10496:     my $iscourse;
                   10497:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10498:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10499:     } else {
                   10500:         my $hashid = $cdom.':'.$cnum;
                   10501:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10502:         unless (defined($cached)) {
                   10503:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10504:                                         $cnum,undef,undef,'.');
                   10505:             $iscourse = 0;
                   10506:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10507:                 $iscourse = 1;
                   10508:             }
                   10509:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10510:         }
                   10511:     }
                   10512:     return unless($iscourse);
1.1167    droeschl 10513:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10514: }
                   10515: 
1.1015    raeburn  10516: sub store_userdata {
                   10517:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10518:     my $result;
1.1016    raeburn  10519:     if ($datakey ne '') {
1.1013    raeburn  10520:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10521:             if ($udom eq '' || $uname eq '') {
                   10522:                 $udom = $env{'user.domain'};
                   10523:                 $uname = $env{'user.name'};
                   10524:             }
                   10525:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10526:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10527:                 $result = 'error: no_host';
                   10528:             } else {
1.1172.2.118.  .14(raeb 10529:-21):                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10530:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10531: 
                   10532:                 my $namevalue='';
                   10533:                 foreach my $key (keys(%{$storehash})) {
                   10534:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10535:                 }
                   10536:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10537:                 unless ($namespace eq 'courserequests') {
                   10538:                     $datakey = &escape($datakey);
                   10539:                 }
1.1105    raeburn  10540:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10541:                                   $namevalue,$uhome);
1.1013    raeburn  10542:             }
                   10543:         } else {
                   10544:             $result = 'error: data to store was not a hash reference'; 
                   10545:         }
                   10546:     } else {
                   10547:         $result= 'error: invalid requestkey'; 
                   10548:     }
                   10549:     return $result;
                   10550: }
                   10551: 
1.21      www      10552: # ---------------------------------------------------------- Assign Custom Role
                   10553: 
                   10554: sub assigncustomrole {
1.957     raeburn  10555:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10556:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10557:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10558: }
                   10559: 
                   10560: # ----------------------------------------------------------------- Revoke Role
                   10561: 
                   10562: sub revokerole {
1.957     raeburn  10563:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10564:     my $now=time;
1.965     raeburn  10565:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10566: }
                   10567: 
                   10568: # ---------------------------------------------------------- Revoke Custom Role
                   10569: 
                   10570: sub revokecustomrole {
1.957     raeburn  10571:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10572:     my $now=time;
1.357     www      10573:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10574:            $deleteflag,$selfenroll,$context);
1.17      www      10575: }
                   10576: 
1.533     banghart 10577: # ------------------------------------------------------------ Disk usage
1.535     albertel 10578: sub diskusage {
1.955     raeburn  10579:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10580:     $directorypath =~ s/\/$//;
                   10581:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10582:                        .&escape($getpropath).':'.&escape($uname).':'
                   10583:                        .&escape($udom),homeserver($uname,$udom));
                   10584:     if ($listing eq 'unknown_cmd') {
                   10585:         if ($getpropath) {
                   10586:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10587:         }
                   10588:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10589:     }
1.514     albertel 10590:     return $listing;
1.512     banghart 10591: }
                   10592: 
1.566     banghart 10593: sub is_locked {
1.1096    raeburn  10594:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10595:     my @check;
                   10596:     my $is_locked;
1.1093    raeburn  10597:     push (@check,$file_name);
1.613     albertel 10598:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10599: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10600:     my ($tmp)=keys(%locked);
                   10601:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10602:     
1.566     banghart 10603:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10604:         $is_locked = 'false';
                   10605:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10606:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10607:                $is_locked = 'true';
1.1096    raeburn  10608:                if (ref($which) eq 'ARRAY') {
                   10609:                    push(@{$which},$entry);
                   10610:                } else {
                   10611:                    last;
                   10612:                }
1.745     raeburn  10613:            }
                   10614:        }
1.566     banghart 10615:     } else {
                   10616:         $is_locked = 'false';
                   10617:     }
1.1093    raeburn  10618:     return $is_locked;
1.566     banghart 10619: }
                   10620: 
1.759     albertel 10621: sub declutter_portfile {
                   10622:     my ($file) = @_;
1.833     albertel 10623:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10624:     return $file;
                   10625: }
                   10626: 
1.559     banghart 10627: # ------------------------------------------------------------- Mark as Read Only
                   10628: 
                   10629: sub mark_as_readonly {
                   10630:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10631:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10632:     my ($tmp)=keys(%current_permissions);
                   10633:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10634:     foreach my $file (@{$files}) {
1.759     albertel 10635: 	$file = &declutter_portfile($file);
1.561     banghart 10636:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10637:     }
1.613     albertel 10638:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10639:     return;
                   10640: }
                   10641: 
1.572     banghart 10642: # ------------------------------------------------------------Save Selected Files
                   10643: 
                   10644: sub save_selected_files {
                   10645:     my ($user, $path, @files) = @_;
                   10646:     my $filename = $user."savedfiles";
1.573     banghart 10647:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10648:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10649:     foreach my $file (@files) {
1.620     albertel 10650:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10651:     }
                   10652:     foreach my $file (@other_files) {
1.574     banghart 10653:         print (OUT $file."\n");
1.572     banghart 10654:     }
1.574     banghart 10655:     close (OUT);
1.572     banghart 10656:     return 'ok';
                   10657: }
                   10658: 
1.574     banghart 10659: sub clear_selected_files {
                   10660:     my ($user) = @_;
                   10661:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10662:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10663:     print (OUT undef);
                   10664:     close (OUT);
                   10665:     return ("ok");    
                   10666: }
                   10667: 
1.572     banghart 10668: sub files_in_path {
                   10669:     my ($user, $path) = @_;
                   10670:     my $filename = $user."savedfiles";
                   10671:     my %return_files;
1.1172.2.96  raeburn  10672:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10673:     while (my $line_in = <IN>) {
1.574     banghart 10674:         chomp ($line_in);
                   10675:         my @paths_and_file = split (m!/!, $line_in);
                   10676:         my $file_part = pop (@paths_and_file);
                   10677:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10678:         $path_part.='/';
                   10679:         my $path_and_file = $path_part.$file_part;
                   10680:         if ($path_part eq $path) {
                   10681:             $return_files{$file_part}= 'selected';
                   10682:         }
                   10683:     }
1.574     banghart 10684:     close (IN);
                   10685:     return (\%return_files);
1.572     banghart 10686: }
                   10687: 
                   10688: # called in portfolio select mode, to show files selected NOT in current directory
                   10689: sub files_not_in_path {
                   10690:     my ($user, $path) = @_;
                   10691:     my $filename = $user."savedfiles";
                   10692:     my @return_files;
                   10693:     my $path_part;
1.1172.2.96  raeburn  10694:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10695:     while (my $line = <IN>) {
1.572     banghart 10696:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10697:         my @paths_and_file = split(m|/|, $line);
                   10698:         my $file_part = pop(@paths_and_file);
                   10699:         chomp($file_part);
                   10700:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10701:         $path_part .= '/';
                   10702:         my $path_and_file = $path_part.$file_part;
                   10703:         if ($path_part ne $path) {
1.800     albertel 10704:             push(@return_files, ($path_and_file));
1.572     banghart 10705:         }
                   10706:     }
1.800     albertel 10707:     close(OUT);
1.574     banghart 10708:     return (@return_files);
1.572     banghart 10709: }
                   10710: 
1.745     raeburn  10711: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10712: 
1.745     raeburn  10713: sub get_portfile_permissions {
                   10714:     my ($domain,$user) = @_;
1.613     albertel 10715:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10716:     my ($tmp)=keys(%current_permissions);
                   10717:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10718:     return \%current_permissions;
                   10719: }
                   10720: 
                   10721: #---------------------------------------------Get portfolio file access controls
                   10722: 
1.749     raeburn  10723: sub get_access_controls {
1.745     raeburn  10724:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10725:     my %access;
                   10726:     my $real_file = $file;
                   10727:     $file =~ s/\.meta$//;
1.745     raeburn  10728:     if (defined($file)) {
1.749     raeburn  10729:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10730:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10731:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10732:             }
                   10733:         }
1.745     raeburn  10734:     } else {
1.749     raeburn  10735:         foreach my $key (keys(%{$current_permissions})) {
                   10736:             if ($key =~ /\0accesscontrol$/) {
                   10737:                 if (defined($group)) {
                   10738:                     if ($key !~ m-^\Q$group\E/-) {
                   10739:                         next;
                   10740:                     }
                   10741:                 }
                   10742:                 my ($fullpath) = split(/\0/,$key);
                   10743:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10744:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10745:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10746:                     }
                   10747:                 }
                   10748:             }
                   10749:         }
                   10750:     }
                   10751:     return %access;
                   10752: }
                   10753: 
                   10754: sub modify_access_controls {
                   10755:     my ($file_name,$changes,$domain,$user)=@_;
                   10756:     my ($outcome,$deloutcome);
                   10757:     my %store_permissions;
                   10758:     my %new_values;
                   10759:     my %new_control;
                   10760:     my %translation;
                   10761:     my @deletions = ();
                   10762:     my $now = time;
                   10763:     if (exists($$changes{'activate'})) {
                   10764:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10765:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10766:             my $numnew = scalar(@newitems);
                   10767:             for (my $i=0; $i<$numnew; $i++) {
                   10768:                 my $newkey = $newitems[$i];
                   10769:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10770:                 if ($newkey =~ /^\d+:/) { 
                   10771:                     $newkey =~ s/^(\d+)/$newid/;
                   10772:                     $translation{$1} = $newid;
                   10773:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10774:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10775:                     $translation{$1} = $newid;
                   10776:                 }
1.749     raeburn  10777:                 $new_values{$file_name."\0".$newkey} = 
                   10778:                                           $$changes{'activate'}{$newitems[$i]};
                   10779:                 $new_control{$newkey} = $now;
                   10780:             }
                   10781:         }
                   10782:     }
                   10783:     my %todelete;
                   10784:     my %changed_items;
                   10785:     foreach my $action ('delete','update') {
                   10786:         if (exists($$changes{$action})) {
                   10787:             if (ref($$changes{$action}) eq 'HASH') {
                   10788:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10789:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10790:                     if ($action eq 'delete') { 
                   10791:                         $todelete{$itemnum} = 1;
                   10792:                     } else {
                   10793:                         $changed_items{$itemnum} = $key;
                   10794:                     }
                   10795:                 }
1.745     raeburn  10796:             }
                   10797:         }
1.749     raeburn  10798:     }
                   10799:     # get lock on access controls for file.
                   10800:     my $lockhash = {
                   10801:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10802:                                                        ':'.$env{'user.domain'},
                   10803:                    }; 
                   10804:     my $tries = 0;
                   10805:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10806:    
1.1172.2.79  raeburn  10807:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10808:         $tries ++;
1.1172.2.79  raeburn  10809:         sleep(0.1);
1.749     raeburn  10810:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10811:     }
                   10812:     if ($gotlock eq 'ok') {
                   10813:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10814:         my ($tmp)=keys(%curr_permissions);
                   10815:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10816:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10817:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10818:             if (ref($curr_controls) eq 'HASH') {
                   10819:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10820:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10821:                     if (defined($todelete{$itemnum})) {
                   10822:                         push(@deletions,$file_name."\0".$control_item);
                   10823:                     } else {
                   10824:                         if (defined($changed_items{$itemnum})) {
                   10825:                             $new_control{$changed_items{$itemnum}} = $now;
                   10826:                             push(@deletions,$file_name."\0".$control_item);
                   10827:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10828:                         } else {
                   10829:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10830:                         }
                   10831:                     }
1.745     raeburn  10832:                 }
                   10833:             }
                   10834:         }
1.970     raeburn  10835:         my ($group);
                   10836:         if (&is_course($domain,$user)) {
                   10837:             ($group,my $file) = split(/\//,$file_name,2);
                   10838:         }
1.749     raeburn  10839:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10840:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10841:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10842:         #  remove lock
                   10843:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10844:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10845:         my $sqlresult =
1.970     raeburn  10846:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10847:                                     $group);
1.749     raeburn  10848:     } else {
                   10849:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10850:     }
1.749     raeburn  10851:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10852: }
                   10853: 
1.827     raeburn  10854: sub make_public_indefinitely {
                   10855:     my ($requrl) = @_;
                   10856:     my $now = time;
                   10857:     my $action = 'activate';
                   10858:     my $aclnum = 0;
                   10859:     if (&is_portfolio_url($requrl)) {
                   10860:         my (undef,$udom,$unum,$file_name,$group) =
                   10861:             &parse_portfolio_url($requrl);
                   10862:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10863:         my %access_controls = &get_access_controls($current_perms,
                   10864:                                                    $group,$file_name);
                   10865:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10866:             my ($num,$scope,$end,$start) = 
                   10867:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10868:             if ($scope eq 'public') {
                   10869:                 if ($start <= $now && $end == 0) {
                   10870:                     $action = 'none';
                   10871:                 } else {
                   10872:                     $action = 'update';
                   10873:                     $aclnum = $num;
                   10874:                 }
                   10875:                 last;
                   10876:             }
                   10877:         }
                   10878:         if ($action eq 'none') {
                   10879:              return 'ok';
                   10880:         } else {
                   10881:             my %changes;
                   10882:             my $newend = 0;
                   10883:             my $newstart = $now;
                   10884:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10885:             $changes{$action}{$newkey} = {
                   10886:                 type => 'public',
                   10887:                 time => {
                   10888:                     start => $newstart,
                   10889:                     end   => $newend,
                   10890:                 },
                   10891:             };
                   10892:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10893:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10894:             return $outcome;
                   10895:         }
                   10896:     } else {
                   10897:         return 'invalid';
                   10898:     }
                   10899: }
                   10900: 
1.745     raeburn  10901: #------------------------------------------------------Get Marked as Read Only
                   10902: 
                   10903: sub get_marked_as_readonly {
                   10904:     my ($domain,$user,$what,$group) = @_;
                   10905:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10906:     my @readonly_files;
1.629     banghart 10907:     my $cmp1=$what;
                   10908:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10909:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10910:         if (defined($group)) {
                   10911:             if ($file_name !~ m-^\Q$group\E/-) {
                   10912:                 next;
                   10913:             }
                   10914:         }
1.561     banghart 10915:         if (ref($value) eq "ARRAY"){
                   10916:             foreach my $stored_what (@{$value}) {
1.629     banghart 10917:                 my $cmp2=$stored_what;
1.759     albertel 10918:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10919:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10920:                 }
1.629     banghart 10921:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10922:                     push(@readonly_files, $file_name);
1.745     raeburn  10923:                     last;
1.563     banghart 10924:                 } elsif (!defined($what)) {
                   10925:                     push(@readonly_files, $file_name);
1.745     raeburn  10926:                     last;
1.561     banghart 10927:                 }
                   10928:             }
1.745     raeburn  10929:         }
1.561     banghart 10930:     }
                   10931:     return @readonly_files;
                   10932: }
1.577     banghart 10933: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10934: 
1.577     banghart 10935: sub get_marked_as_readonly_hash {
1.745     raeburn  10936:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10937:     my %readonly_files;
1.745     raeburn  10938:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10939:         if (defined($group)) {
                   10940:             if ($file_name !~ m-^\Q$group\E/-) {
                   10941:                 next;
                   10942:             }
                   10943:         }
1.577     banghart 10944:         if (ref($value) eq "ARRAY"){
                   10945:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10946:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10947:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10948:                         if ($lock_descriptor eq 'graded') {
                   10949:                             $readonly_files{$file_name} = 'graded';
                   10950:                         } elsif ($lock_descriptor eq 'handback') {
                   10951:                             $readonly_files{$file_name} = 'handback';
                   10952:                         } else {
                   10953:                             if (!exists($readonly_files{$file_name})) {
                   10954:                                 $readonly_files{$file_name} = 'locked';
                   10955:                             }
                   10956:                         }
1.745     raeburn  10957:                     }
1.750     banghart 10958:                 } 
1.577     banghart 10959:             }
                   10960:         } 
                   10961:     }
                   10962:     return %readonly_files;
                   10963: }
1.559     banghart 10964: # ------------------------------------------------------------ Unmark as Read Only
                   10965: 
                   10966: sub unmark_as_readonly {
1.629     banghart 10967:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10968:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10969:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10970:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10971:     my $symb_crs = $what;
                   10972:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10973:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10974:     my ($tmp)=keys(%current_permissions);
                   10975:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10976:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10977:     foreach my $file (@readonly_files) {
1.759     albertel 10978: 	my $clean_file = &declutter_portfile($file);
                   10979: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10980: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10981:         my @new_locks;
                   10982:         my @del_keys;
                   10983:         if (ref($current_locks) eq "ARRAY"){
                   10984:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10985:                 my $compare=$locker;
1.749     raeburn  10986:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10987:                     $compare=join('',@{$locker});
1.746     raeburn  10988:                     if ($compare ne $symb_crs) {
                   10989:                         push(@new_locks, $locker);
                   10990:                     }
1.563     banghart 10991:                 }
                   10992:             }
1.650     albertel 10993:             if (scalar(@new_locks) > 0) {
1.563     banghart 10994:                 $current_permissions{$file} = \@new_locks;
                   10995:             } else {
                   10996:                 push(@del_keys, $file);
1.613     albertel 10997:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10998:                 delete($current_permissions{$file});
1.563     banghart 10999:             }
                   11000:         }
1.561     banghart 11001:     }
1.613     albertel 11002:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11003:     return;
                   11004: }
1.512     banghart 11005: 
1.17      www      11006: # ------------------------------------------------------------ Directory lister
                   11007: 
                   11008: sub dirlist {
1.955     raeburn  11009:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11010:     $uri=~s/^\///;
                   11011:     $uri=~s/\/$//;
1.253     stredwic 11012:     my ($udom, $uname);
1.955     raeburn  11013:     if ($getuserdir) {
1.253     stredwic 11014:         $udom = $userdomain;
                   11015:         $uname = $username;
1.955     raeburn  11016:     } else {
                   11017:         (undef,$udom,$uname)=split(/\//,$uri);
                   11018:         if(defined($userdomain)) {
                   11019:             $udom = $userdomain;
                   11020:         }
                   11021:         if(defined($username)) {
                   11022:             $uname = $username;
                   11023:         }
1.253     stredwic 11024:     }
1.955     raeburn  11025:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11026: 
1.955     raeburn  11027:     $dirRoot = $perlvar{'lonDocRoot'};
                   11028:     if (defined($getpropath)) {
                   11029:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11030:         $dirRoot =~ s/\/$//;
1.955     raeburn  11031:     } elsif (defined($getuserdir)) {
                   11032:         my $subdir=$uname.'__';
                   11033:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11034:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11035:                    ."/$udom/$subdir/$uname";
                   11036:     } elsif (defined($alternateRoot)) {
                   11037:         $dirRoot = $alternateRoot;
1.751     banghart 11038:     }
1.253     stredwic 11039: 
                   11040:     if($udom) {
                   11041:         if($uname) {
1.1135    raeburn  11042:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11043:             if ($uhome eq 'no_host') {
                   11044:                 return ([],'no_host');
                   11045:             }
1.955     raeburn  11046:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11047:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11048:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11049:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11050:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11051:             } else {
                   11052:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11053:             }
1.605     matthew  11054:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11055:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11056:                 @listing_results = split(/:/,$listing);
                   11057:             } else {
                   11058:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11059:             }
1.1135    raeburn  11060:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11061:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11062:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11063:                 return ([],$listing);
                   11064:             } else {
                   11065:                 return (\@listing_results);
1.1135    raeburn  11066:             }
1.955     raeburn  11067:         } elsif(!$alternateRoot) {
1.1136    raeburn  11068:             my (%allusers,%listerror);
1.841     albertel 11069: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11070:  	    foreach my $tryserver (keys(%servers)) {
                   11071:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11072:                                   &escape($udom),$tryserver);
                   11073:                 if ($listing eq 'unknown_cmd') {
                   11074: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11075: 				      $udom, $tryserver);
                   11076:                 } else {
                   11077:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11078:                 }
1.841     albertel 11079: 		if ($listing eq 'unknown_cmd') {
                   11080: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11081: 				      $udom, $tryserver);
                   11082: 		    @listing_results = split(/:/,$listing);
                   11083: 		} else {
                   11084: 		    @listing_results =
                   11085: 			map { &unescape($_); } split(/:/,$listing);
                   11086: 		}
1.1136    raeburn  11087:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11088:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11089:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11090:                     $listerror{$tryserver} = $listing;
                   11091:                 } else {
1.841     albertel 11092: 		    foreach my $line (@listing_results) {
                   11093: 			my ($entry) = split(/&/,$line,2);
                   11094: 			$allusers{$entry} = 1;
                   11095: 		    }
                   11096: 		}
1.253     stredwic 11097:             }
1.1136    raeburn  11098:             my @alluserslist=();
1.800     albertel 11099:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11100:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11101:             }
1.1172.2.80  raeburn  11102:             if (!%listerror) {
                   11103:                 # no errors
                   11104:                 return (\@alluserslist);
                   11105:             } elsif (scalar(keys(%servers)) == 1) {
                   11106:                 # one library server, one error
                   11107:                 my ($key) = keys(%listerror);
                   11108:                 return (\@alluserslist, $listerror{$key});
                   11109:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11110:                 # con_lost indicates that we might miss data from at least one
                   11111:                 # library server
                   11112:                 return (\@alluserslist, 'con_lost');
                   11113:             } else {
                   11114:                 # multiple library servers and no con_lost -> data should be
                   11115:                 # complete.
                   11116:                 return (\@alluserslist);
                   11117:             }
                   11118: 
1.253     stredwic 11119:         } else {
1.1136    raeburn  11120:             return ([],'missing username');
1.253     stredwic 11121:         }
1.955     raeburn  11122:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11123:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11124:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11125:         return (\@all_domains);
1.955     raeburn  11126:     } else {
1.1136    raeburn  11127:         return ([],'missing domain');
1.275     stredwic 11128:     }
                   11129: }
                   11130: 
                   11131: # --------------------------------------------- GetFileTimestamp
                   11132: # This function utilizes dirlist and returns the date stamp for
                   11133: # when it was last modified.  It will also return an error of -1
                   11134: # if an error occurs
                   11135: 
                   11136: sub GetFileTimestamp {
1.955     raeburn  11137:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11138:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11139:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11140:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11141:                                     undef,$getuserdir);
                   11142:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11143:         return -1;
                   11144:     }
                   11145:     if (ref($fileref) eq 'ARRAY') {
                   11146:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11147:         # @stats contains first the filename, then the stat output
                   11148:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11149:     } else {
                   11150:         return -1;
1.253     stredwic 11151:     }
1.26      www      11152: }
                   11153: 
1.712     albertel 11154: sub stat_file {
                   11155:     my ($uri) = @_;
1.787     albertel 11156:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11157: 
1.955     raeburn  11158:     my ($udom,$uname,$file);
1.712     albertel 11159:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11160: 	($udom,$uname,$file) =
1.811     albertel 11161: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11162: 	$file = 'userfiles/'.$file;
                   11163:     }
                   11164:     if ($uri =~ m-^/res/-) {
                   11165: 	($udom,$uname) = 
1.807     albertel 11166: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11167: 	$file = $uri;
                   11168:     }
                   11169: 
                   11170:     if (!$udom || !$uname || !$file) {
                   11171: 	# unable to handle the uri
                   11172: 	return ();
                   11173:     }
1.956     raeburn  11174:     my $getpropath;
                   11175:     if ($file =~ /^userfiles\//) {
                   11176:         $getpropath = 1;
                   11177:     }
1.1136    raeburn  11178:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11179:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11180:         return ();
                   11181:     } else {
                   11182:         if (ref($listref) eq 'ARRAY') {
                   11183:             my @stats = split('&',$listref->[0]);
                   11184: 	    shift(@stats); #filename is first
                   11185: 	    return @stats;
                   11186:         }
1.712     albertel 11187:     }
                   11188:     return ();
                   11189: }
                   11190: 
1.26      www      11191: # -------------------------------------------------------- Value of a Condition
                   11192: 
1.713     albertel 11193: # gets the value of a specific preevaluated condition
                   11194: #    stored in the string  $env{user.state.<cid>}
                   11195: # or looks up a condition reference in the bighash and if if hasn't
                   11196: # already been evaluated recurses into docondval to get the value of
                   11197: # the condition, then memoizing it to 
                   11198: #   $env{user.state.<cid>.<condition>}
1.40      www      11199: sub directcondval {
                   11200:     my $number=shift;
1.620     albertel 11201:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11202: 	&Apache::lonuserstate::evalstate();
                   11203:     }
1.713     albertel 11204:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11205: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11206:     } elsif ($number =~ /^_/) {
                   11207: 	my $sub_condition;
                   11208: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11209: 		&GDBM_READER(),0640)) {
                   11210: 	    $sub_condition=$bighash{'conditions'.$number};
                   11211: 	    untie(%bighash);
                   11212: 	}
                   11213: 	my $value = &docondval($sub_condition);
1.949     raeburn  11214: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11215: 	return $value;
                   11216:     }
1.620     albertel 11217:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11218:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11219:     } else {
                   11220:        return 2;
                   11221:     }
                   11222: }
                   11223: 
1.713     albertel 11224: # get the collection of conditions for this resource
1.26      www      11225: sub condval {
                   11226:     my $condidx=shift;
1.54      www      11227:     my $allpathcond='';
1.713     albertel 11228:     foreach my $cond (split(/\|/,$condidx)) {
                   11229: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11230: 	    $allpathcond.=
                   11231: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11232: 	}
1.191     harris41 11233:     }
1.54      www      11234:     $allpathcond=~s/\|$//;
1.713     albertel 11235:     return &docondval($allpathcond);
                   11236: }
                   11237: 
                   11238: #evaluates an expression of conditions
                   11239: sub docondval {
                   11240:     my ($allpathcond) = @_;
                   11241:     my $result=0;
                   11242:     if ($env{'request.course.id'}
                   11243: 	&& defined($allpathcond)) {
                   11244: 	my $operand='|';
                   11245: 	my @stack;
                   11246: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11247: 	    if ($chunk eq '(') {
                   11248: 		push @stack,($operand,$result);
                   11249: 	    } elsif ($chunk eq ')') {
                   11250: 		my $before=pop @stack;
                   11251: 		if (pop @stack eq '&') {
                   11252: 		    $result=$result>$before?$before:$result;
                   11253: 		} else {
                   11254: 		    $result=$result>$before?$result:$before;
                   11255: 		}
                   11256: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11257: 		$operand=$chunk;
                   11258: 	    } else {
                   11259: 		my $new=directcondval($chunk);
                   11260: 		if ($operand eq '&') {
                   11261: 		    $result=$result>$new?$new:$result;
                   11262: 		} else {
                   11263: 		    $result=$result>$new?$result:$new;
                   11264: 		}
                   11265: 	    }
                   11266: 	}
1.26      www      11267:     }
                   11268:     return $result;
1.421     albertel 11269: }
                   11270: 
                   11271: # ---------------------------------------------------- Devalidate courseresdata
                   11272: 
                   11273: sub devalidatecourseresdata {
                   11274:     my ($coursenum,$coursedomain)=@_;
                   11275:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11276:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11277: }
                   11278: 
1.763     www      11279: 
1.200     www      11280: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11281: #
                   11282: #  Parameters:
                   11283: #      $coursenum    - Number of the course.
                   11284: #      $coursedomain - Domain at which the course was created.
                   11285: #  Returns:
                   11286: #     A hash of the course parameters along (I think) with timestamps
                   11287: #     and version info.
1.877     foxr     11288: 
1.624     albertel 11289: sub get_courseresdata {
                   11290:     my ($coursenum,$coursedomain)=@_;
1.200     www      11291:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11292:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11293:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11294:     my %dumpreply;
1.417     albertel 11295:     unless (defined($cached)) {
1.624     albertel 11296: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11297: 	$result=\%dumpreply;
1.251     albertel 11298: 	my ($tmp) = keys(%dumpreply);
                   11299: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11300: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11301: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11302: 	    return $tmp;
1.416     albertel 11303: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11304: 	    $result=undef;
1.599     albertel 11305: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11306: 	}
                   11307:     }
1.624     albertel 11308:     return $result;
                   11309: }
                   11310: 
1.633     albertel 11311: sub devalidateuserresdata {
                   11312:     my ($uname,$udom)=@_;
                   11313:     my $hashid="$udom:$uname";
                   11314:     &devalidate_cache_new('userres',$hashid);
                   11315: }
                   11316: 
1.624     albertel 11317: sub get_userresdata {
                   11318:     my ($uname,$udom)=@_;
                   11319:     #most student don\'t have any data set, check if there is some data
                   11320:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11321: 
                   11322:     my $hashid="$udom:$uname";
                   11323:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11324:     if (!defined($cached)) {
                   11325: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11326: 	$result=\%resourcedata;
                   11327: 	&do_cache_new('userres',$hashid,$result,600);
                   11328:     }
                   11329:     my ($tmp)=keys(%$result);
                   11330:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11331: 	return $result;
                   11332:     }
                   11333:     #error 2 occurs when the .db doesn't exist
                   11334:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11335:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11336: 	    &logthis("<font color=\"blue\">WARNING:".
                   11337: 		     " Trying to get resource data for ".
                   11338: 		     $uname." at ".$udom.": ".
                   11339: 		     $tmp."</font>");
                   11340:         }
1.624     albertel 11341:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11342: 	#&EXT_cache_set($udom,$uname);
                   11343: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11344: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11345:     }
                   11346:     return $tmp;
                   11347: }
1.879     foxr     11348: #----------------------------------------------- resdata - return resource data
                   11349: #  Purpose:
                   11350: #    Return resource data for either users or for a course.
                   11351: #  Parameters:
                   11352: #     $name      - Course/user name.
                   11353: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11354:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11355: #     @which     - Array of names of resources desired.
                   11356: #  Returns:
                   11357: #     The value of the first reasource in @which that is found in the
                   11358: #     resource hash.
                   11359: #  Exceptional Conditions:
                   11360: #     If the $type passed in is not valid (not the string 'course' or 
                   11361: #     'user', an undefined  reference is returned.
                   11362: #     If none of the resources are found, an undef is returned
1.624     albertel 11363: sub resdata {
                   11364:     my ($name,$domain,$type,@which)=@_;
                   11365:     my $result;
                   11366:     if ($type eq 'course') {
                   11367: 	$result=&get_courseresdata($name,$domain);
                   11368:     } elsif ($type eq 'user') {
                   11369: 	$result=&get_userresdata($name,$domain);
                   11370:     }
                   11371:     if (!ref($result)) { return $result; }    
1.251     albertel 11372:     foreach my $item (@which) {
1.1172.2.118.  .8(raebu 11373:20): 	if (defined($result->{$item->[0]})) {
                   11374:20): 	    return [$result->{$item->[0]},$item->[1]];
          .1(raebu 11375:20):         }
1.250     albertel 11376:     }
1.291     albertel 11377:     return undef;
1.200     www      11378: }
                   11379: 
1.1172.2.118.  .10(raeb 11380:-20): sub get_domain_lti {
                   11381:-20):     my ($cdom,$context) = @_;
                   11382:-20):     my ($name,%lti);
                   11383:-20):     if ($context eq 'consumer') {
                   11384:-20):         $name = 'ltitools';
                   11385:-20):     } elsif ($context eq 'provider') {
                   11386:-20):         $name = 'lti';
                   11387:-20):     } else {
                   11388:-20):         return %lti;
                   11389:-20):     }
                   11390:-20):     my ($result,$cached)=&is_cached_new($name,$cdom);
          .1(raebu 11391:20):     if (defined($cached)) {
                   11392:20):         if (ref($result) eq 'HASH') {
          .10(raeb 11393:-20):             %lti = %{$result};
          .1(raebu 11394:20):         }
                   11395:20):     } else {
          .10(raeb 11396:-20):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11397:-20):         if (ref($domconfig{$name}) eq 'HASH') {
                   11398:-20):             %lti = %{$domconfig{$name}};
                   11399:-20):             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11400:-20):             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11401:-20):                 foreach my $id (keys(%lti)) {
                   11402:-20):                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
          .1(raebu 11403:20):                         foreach my $item ('key','secret') {
          .10(raeb 11404:-20):                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
          .1(raebu 11405:20):                         }
                   11406:20):                     }
                   11407:20):                 }
                   11408:20):             }
                   11409:20):         }
                   11410:20):         my $cachetime = 24*60*60;
          .10(raeb 11411:-20):         &do_cache_new($name,$cdom,\%lti,$cachetime);
          .1(raebu 11412:20):     }
          .10(raeb 11413:-20):     return %lti;
          .1(raebu 11414:20): }
                   11415:20): 
1.1172.2.31  raeburn  11416: sub get_numsuppfiles {
                   11417:     my ($cnum,$cdom,$ignorecache)=@_;
                   11418:     my $hashid=$cnum.':'.$cdom;
                   11419:     my ($suppcount,$cached);
                   11420:     unless ($ignorecache) {
                   11421:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11422:     }
                   11423:     unless (defined($cached)) {
                   11424:         my $chome=&homeserver($cnum,$cdom);
                   11425:         unless ($chome eq 'no_host') {
                   11426:             ($suppcount,my $errors) = (0,0);
                   11427:             my $suppmap = 'supplemental.sequence';
                   11428:             ($suppcount,$errors) =
                   11429:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11430:         }
                   11431:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11432:     }
                   11433:     return $suppcount;
                   11434: }
                   11435: 
1.379     matthew  11436: #
                   11437: # EXT resource caching routines
                   11438: #
                   11439: 
                   11440: sub clear_EXT_cache_status {
1.383     albertel 11441:     &delenv('cache.EXT.');
1.379     matthew  11442: }
                   11443: 
                   11444: sub EXT_cache_status {
                   11445:     my ($target_domain,$target_user) = @_;
1.383     albertel 11446:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11447:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11448:         # We know already the user has no data
                   11449:         return 1;
                   11450:     } else {
                   11451:         return 0;
                   11452:     }
                   11453: }
                   11454: 
                   11455: sub EXT_cache_set {
                   11456:     my ($target_domain,$target_user) = @_;
1.383     albertel 11457:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11458:     #&appenv({$cachename => time});
1.379     matthew  11459: }
                   11460: 
1.28      www      11461: # --------------------------------------------------------- Value of a Variable
1.58      www      11462: sub EXT {
1.715     albertel 11463: 
1.1172.2.28  raeburn  11464:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11465:     unless ($varname) { return ''; }
1.218     albertel 11466:     #get real user name/domain, courseid and symb
                   11467:     my $courseid;
1.359     albertel 11468:     my $publicuser;
1.427     www      11469:     if ($symbparm) {
                   11470: 	$symbparm=&get_symb_from_alias($symbparm);
                   11471:     }
1.218     albertel 11472:     if (!($uname && $udom)) {
1.790     albertel 11473:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11474:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11475:     } else {
1.620     albertel 11476: 	$courseid=$env{'request.course.id'};
1.218     albertel 11477:     }
1.48      www      11478:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11479:     my $rest;
1.320     albertel 11480:     if (defined($therest[0])) {
1.48      www      11481:        $rest=join('.',@therest);
                   11482:     } else {
                   11483:        $rest='';
                   11484:     }
1.320     albertel 11485: 
1.57      www      11486:     my $qualifierrest=$qualifier;
                   11487:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11488:     my $spacequalifierrest=$space;
                   11489:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11490:     if ($realm eq 'user') {
1.48      www      11491: # --------------------------------------------------------------- user.resource
                   11492: 	if ($space eq 'resource') {
1.651     albertel 11493: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11494: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11495: 		 &&
1.744     albertel 11496: 		 ($symbparm eq &symbread()) ) {	
                   11497: 		# if we are in the middle of processing the resource the
                   11498: 		# get the value we are planning on committing
                   11499:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11500:                     return $Apache::lonhomework::results{$qualifierrest};
                   11501:                 } else {
                   11502:                     return $Apache::lonhomework::history{$qualifierrest};
                   11503:                 }
1.335     albertel 11504: 	    } else {
1.359     albertel 11505: 		my %restored;
1.620     albertel 11506: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11507: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11508: 		} else {
                   11509: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11510: 		}
1.335     albertel 11511: 		return $restored{$qualifierrest};
                   11512: 	    }
1.48      www      11513: # ----------------------------------------------------------------- user.access
                   11514:         } elsif ($space eq 'access') {
1.218     albertel 11515: 	    # FIXME - not supporting calls for a specific user
1.48      www      11516:             return &allowed($qualifier,$rest);
                   11517: # ------------------------------------------ user.preferences, user.environment
                   11518:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11519: 	    if (($uname eq $env{'user.name'}) &&
                   11520: 		($udom eq $env{'user.domain'})) {
                   11521: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11522: 	    } else {
1.359     albertel 11523: 		my %returnhash;
                   11524: 		if (!$publicuser) {
                   11525: 		    %returnhash=&userenvironment($udom,$uname,
                   11526: 						 $qualifierrest);
                   11527: 		}
1.218     albertel 11528: 		return $returnhash{$qualifierrest};
                   11529: 	    }
1.48      www      11530: # ----------------------------------------------------------------- user.course
                   11531:         } elsif ($space eq 'course') {
1.218     albertel 11532: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11533:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11534: # ------------------------------------------------------------------- user.role
                   11535:         } elsif ($space eq 'role') {
1.218     albertel 11536: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11537:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11538:             if ($qualifier eq 'value') {
                   11539: 		return $role;
                   11540:             } elsif ($qualifier eq 'extent') {
                   11541:                 return $where;
                   11542:             }
                   11543: # ----------------------------------------------------------------- user.domain
                   11544:         } elsif ($space eq 'domain') {
1.218     albertel 11545:             return $udom;
1.48      www      11546: # ------------------------------------------------------------------- user.name
                   11547:         } elsif ($space eq 'name') {
1.218     albertel 11548:             return $uname;
1.48      www      11549: # ---------------------------------------------------- Any other user namespace
1.29      www      11550:         } else {
1.359     albertel 11551: 	    my %reply;
                   11552: 	    if (!$publicuser) {
                   11553: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11554: 	    }
                   11555: 	    return $reply{$qualifierrest};
1.48      www      11556:         }
1.236     www      11557:     } elsif ($realm eq 'query') {
                   11558: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11559:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11560: 						[$spacequalifierrest]);
1.620     albertel 11561: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11562:    } elsif ($realm eq 'request') {
1.48      www      11563: # ------------------------------------------------------------- request.browser
                   11564:         if ($space eq 'browser') {
1.1145    bisitz   11565:             return $env{'browser.'.$qualifier};
1.57      www      11566: # ------------------------------------------------------------ request.filename
                   11567:         } else {
1.620     albertel 11568:             return $env{'request.'.$spacequalifierrest};
1.29      www      11569:         }
1.28      www      11570:     } elsif ($realm eq 'course') {
1.48      www      11571: # ---------------------------------------------------------- course.description
1.620     albertel 11572:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11573:     } elsif ($realm eq 'resource') {
1.165     www      11574: 
1.620     albertel 11575: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11576: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11577: 	}
1.693     albertel 11578: 
1.1172.2.30  raeburn  11579:         if ($qualifier eq '') {
                   11580: 	    if ($space eq 'title') {
                   11581: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11582: 	        return &gettitle($symbparm);
                   11583: 	    }
1.693     albertel 11584: 	
1.1172.2.30  raeburn  11585: 	    if ($space eq 'map') {
                   11586: 	        my ($map) = &decode_symb($symbparm);
                   11587: 	        return &symbread($map);
                   11588: 	    }
                   11589:             if ($space eq 'maptitle') {
                   11590:                 my ($map) = &decode_symb($symbparm);
                   11591:                 return &gettitle($map);
                   11592:             }
                   11593: 	    if ($space eq 'filename') {
                   11594: 	        if ($symbparm) {
                   11595: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11596: 	        }
                   11597: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11598: 	    }
1.1172.2.30  raeburn  11599: 
                   11600:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11601:                 if ($space eq 'visibleparts') {
                   11602:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11603:                     my $item;
                   11604:                     if (ref($navmap)) {
                   11605:                         my $res = $navmap->getBySymb($symbparm);
                   11606:                         my $parts = $res->parts();
                   11607:                         if (ref($parts) eq 'ARRAY') {
                   11608:                             $item = join(',',@{$parts});
                   11609:                         }
                   11610:                         undef($navmap);
                   11611:                     }
                   11612:                     return $item;
                   11613:                 }
                   11614:             }
                   11615:         }
1.693     albertel 11616: 
                   11617: 	my ($section, $group, @groups);
1.593     albertel 11618: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11619:         if (($courseid eq '') && ($cid)) {
                   11620:             $courseid = $cid;
                   11621:         }
                   11622: 	if (($symbparm && $courseid) && 
                   11623: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11624: 
1.218     albertel 11625: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11626: 
1.60      www      11627: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11628: 	    my $symbp=$symbparm;
1.735     albertel 11629: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11630: 
                   11631: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11632: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11633: 
1.620     albertel 11634: 	    if (($env{'user.name'} eq $uname) &&
                   11635: 		($env{'user.domain'} eq $udom)) {
                   11636: 		$section=$env{'request.course.sec'};
1.733     raeburn  11637:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11638:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11639: 	    } else {
1.539     albertel 11640: 		if (! defined($usection)) {
1.551     albertel 11641: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11642: 		} else {
                   11643: 		    $section = $usection;
                   11644: 		}
1.733     raeburn  11645:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11646: 	    }
                   11647: 
                   11648: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11649: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11650: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11651: 
1.593     albertel 11652: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11653: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11654: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11655: 
1.60      www      11656: # ----------------------------------------------------------- first, check user
1.624     albertel 11657: 
                   11658: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11659: 				       ([$courselevelr,'resource'],
                   11660: 					[$courselevelm,'map'     ],
                   11661: 					[$courselevel, 'course'  ]));
1.931     albertel 11662: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11663: 
1.594     albertel 11664: # ------------------------------------------------ second, check some of course
1.684     raeburn  11665:             my $coursereply;
1.691     raeburn  11666:             if (@groups > 0) {
                   11667:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11668:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11669:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11670:             }
1.96      www      11671: 
1.684     raeburn  11672: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11673: 				  $env{'course.'.$courseid.'.domain'},
                   11674: 				  'course',
                   11675: 				  ([$seclevelr,   'resource'],
                   11676: 				   [$seclevelm,   'map'     ],
                   11677: 				   [$seclevel,    'course'  ],
                   11678: 				   [$courselevelr,'resource']));
                   11679: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11680: 
1.60      www      11681: # ------------------------------------------------------ third, check map parms
1.218     albertel 11682: 	    my %parmhash=();
                   11683: 	    my $thisparm='';
                   11684: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11685: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11686: 		    &GDBM_READER(),0640)) {
1.218     albertel 11687: 		$thisparm=$parmhash{$symbparm};
                   11688: 		untie(%parmhash);
                   11689: 	    }
1.927     albertel 11690: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11691: 	}
1.594     albertel 11692: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11693: 
1.218     albertel 11694: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11695: 	my $filename;
                   11696: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11697: 	if ($symbparm) {
1.409     www      11698: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11699: 	} else {
1.620     albertel 11700: 	    $filename=$env{'request.filename'};
1.282     albertel 11701: 	}
                   11702: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11703: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11704: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11705: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11706: 
1.927     albertel 11707: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11708: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11709: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11710: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11711: 				     $env{'course.'.$courseid.'.domain'},
                   11712: 				     'course',
1.927     albertel 11713: 				     ([$courselevelm,'map'   ],
                   11714: 				      [$courselevel, 'course']));
                   11715: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11716: 	}
1.145     www      11717: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11718: 	unless ($space eq '0') {
1.336     albertel 11719: 	    my @parts=split(/_/,$space);
                   11720: 	    my $id=pop(@parts);
                   11721: 	    my $part=join('_',@parts);
                   11722: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11723: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11724: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11725: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11726: 	}
1.395     albertel 11727: 	if ($recurse) { return undef; }
                   11728: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11729: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11730: # ---------------------------------------------------- Any other user namespace
                   11731:     } elsif ($realm eq 'environment') {
                   11732: # ----------------------------------------------------------------- environment
1.620     albertel 11733: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11734: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11735: 	} else {
1.770     albertel 11736: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11737: 		return '';
                   11738: 	    }
1.219     albertel 11739: 	    my %returnhash=&userenvironment($udom,$uname,
                   11740: 					    $spacequalifierrest);
                   11741: 	    return $returnhash{$spacequalifierrest};
                   11742: 	}
1.28      www      11743:     } elsif ($realm eq 'system') {
1.48      www      11744: # ----------------------------------------------------------------- system.time
                   11745: 	if ($space eq 'time') {
                   11746: 	    return time;
                   11747:         }
1.696     albertel 11748:     } elsif ($realm eq 'server') {
                   11749: # ----------------------------------------------------------------- system.time
                   11750: 	if ($space eq 'name') {
                   11751: 	    return $ENV{'SERVER_NAME'};
                   11752:         }
1.28      www      11753:     }
1.48      www      11754:     return '';
1.61      www      11755: }
                   11756: 
1.927     albertel 11757: sub get_reply {
                   11758:     my ($reply_value) = @_;
1.940     raeburn  11759:     if (ref($reply_value) eq 'ARRAY') {
                   11760:         if (wantarray) {
                   11761: 	    return @$reply_value;
                   11762:         }
                   11763:         return $reply_value->[0];
                   11764:     } else {
                   11765:         return $reply_value;
1.927     albertel 11766:     }
                   11767: }
                   11768: 
1.691     raeburn  11769: sub check_group_parms {
                   11770:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11771:     my @groupitems = ();
                   11772:     my $resultitem;
1.927     albertel 11773:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11774:     foreach my $group (@{$groups}) {
                   11775:         foreach my $level (@levels) {
1.927     albertel 11776:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11777:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11778:         }
                   11779:     }
                   11780:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11781:                             $env{'course.'.$courseid.'.domain'},
                   11782:                                      'course',@groupitems);
                   11783:     return $coursereply;
                   11784: }
                   11785: 
                   11786: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11787:     my ($courseid,@groups) = @_;
                   11788:     @groups = sort(@groups);
1.691     raeburn  11789:     return @groups;
                   11790: }
                   11791: 
1.395     albertel 11792: sub packages_tab_default {
                   11793:     my ($uri,$varname)=@_;
                   11794:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11795: 
                   11796:     my (@extension,@specifics,$do_default);
                   11797:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11798: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11799: 	if ($pack_type eq 'default') {
                   11800: 	    $do_default=1;
                   11801: 	} elsif ($pack_type eq 'extension') {
                   11802: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11803: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11804: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11805: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11806: 	}
                   11807:     }
                   11808:     # first look for a package that matches the requested part id
                   11809:     foreach my $package (@specifics) {
                   11810: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11811: 	next if ($pack_part ne $part);
                   11812: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11813: 	    return $packagetab{"$pack_type&$name&default"};
                   11814: 	}
                   11815:     }
                   11816:     # look for any possible matching non extension_ package
                   11817:     foreach my $package (@specifics) {
                   11818: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11819: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11820: 	    return $packagetab{"$pack_type&$name&default"};
                   11821: 	}
1.585     albertel 11822: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11823: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11824: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11825: 	}
                   11826:     }
1.738     albertel 11827:     # look for any posible extension_ match
                   11828:     foreach my $package (@extension) {
                   11829: 	my ($package,$pack_type)=@{$package};
                   11830: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11831: 	    return $packagetab{"$pack_type&$name&default"};
                   11832: 	}
                   11833: 	if (defined($packagetab{$package."&$name&default"})) {
                   11834: 	    return $packagetab{$package."&$name&default"};
                   11835: 	}
                   11836:     }
                   11837:     # look for a global default setting
                   11838:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11839: 	return $packagetab{"default&$name&default"};
                   11840:     }
1.395     albertel 11841:     return undef;
                   11842: }
                   11843: 
1.334     albertel 11844: sub add_prefix_and_part {
                   11845:     my ($prefix,$part)=@_;
                   11846:     my $keyroot;
                   11847:     if (defined($prefix) && $prefix !~ /^__/) {
                   11848: 	# prefix that has a part already
                   11849: 	$keyroot=$prefix;
                   11850:     } elsif (defined($prefix)) {
                   11851: 	# prefix that is missing a part
                   11852: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11853:     } else {
                   11854: 	# no prefix at all
                   11855: 	if (defined($part)) { $keyroot='_'.$part; }
                   11856:     }
                   11857:     return $keyroot;
                   11858: }
                   11859: 
1.71      www      11860: # ---------------------------------------------------------------- Get metadata
                   11861: 
1.599     albertel 11862: my %metaentry;
1.1070    www      11863: my %importedpartids;
1.1172.2.99  raeburn  11864: my %importedrespids;
1.71      www      11865: sub metadata {
1.176     www      11866:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11867:     $uri=&declutter($uri);
1.288     albertel 11868:     # if it is a non metadata possible uri return quickly
1.529     albertel 11869:     if (($uri eq '') || 
                   11870: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11871:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11872:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11873: 	return undef;
                   11874:     }
1.1172.2.49  raeburn  11875:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11876: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11877: 	return undef;
1.288     albertel 11878:     }
1.73      www      11879:     my $filename=$uri;
                   11880:     $uri=~s/\.meta$//;
1.172     www      11881: #
                   11882: # Is the metadata already cached?
1.177     www      11883: # Look at timestamp of caching
1.172     www      11884: # Everything is cached by the main uri, libraries are never directly cached
                   11885: #
1.428     albertel 11886:     if (!defined($liburi)) {
1.599     albertel 11887: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11888: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11889:     }
                   11890:     {
1.1069    www      11891: # Imported parts would go here
1.1172.2.99  raeburn  11892:         my @origfiletagids=();
1.1069    www      11893:         my $importedparts=0;
1.1172.2.99  raeburn  11894: 
                   11895: # Imported responseids would go here
                   11896:         my $importedresponses=0;
1.172     www      11897: #
                   11898: # Is this a recursive call for a library?
                   11899: #
1.599     albertel 11900: #	if (! exists($metacache{$uri})) {
                   11901: #	    $metacache{$uri}={};
                   11902: #	}
1.924     albertel 11903: 	my $cachetime = 60*60;
1.171     www      11904:         if ($liburi) {
                   11905: 	    $liburi=&declutter($liburi);
                   11906:             $filename=$liburi;
1.401     bowersj2 11907:         } else {
1.599     albertel 11908: 	    &devalidate_cache_new('meta',$uri);
                   11909: 	    undef(%metaentry);
1.401     bowersj2 11910: 	}
1.140     www      11911:         my %metathesekeys=();
1.73      www      11912:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11913: 	my $metastring;
1.1140    www      11914: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11915: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11916: 	    $metastring = 
1.929     albertel 11917: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11918: 					  ('grade_target' => 'meta'));
                   11919: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11920: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11921:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11922: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11923: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11924: 	    $metastring=&getfile($file);
1.489     albertel 11925: 	}
1.208     albertel 11926:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11927:         my $token;
1.140     www      11928:         undef %metathesekeys;
1.71      www      11929:         while ($token=$parser->get_token) {
1.339     albertel 11930: 	    if ($token->[0] eq 'S') {
                   11931: 		if (defined($token->[2]->{'package'})) {
1.172     www      11932: #
                   11933: # This is a package - get package info
                   11934: #
1.339     albertel 11935: 		    my $package=$token->[2]->{'package'};
                   11936: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11937: 		    if (defined($token->[2]->{'id'})) { 
                   11938: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11939: 		    }
1.599     albertel 11940: 		    if ($metaentry{':packages'}) {
                   11941: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11942: 		    } else {
1.599     albertel 11943: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11944: 		    }
1.736     albertel 11945: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11946: 			my $part=$keyroot;
                   11947: 			$part=~s/^\_//;
1.736     albertel 11948: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11949: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11950: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11951: 			    # ignore package.tab specified default values
                   11952:                             # here &package_tab_default() will fetch those
                   11953: 			    if ($subp eq 'default') { next; }
1.736     albertel 11954: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11955: 			    my $unikey;
                   11956: 			    if ($pack =~ /_0$/) {
                   11957: 				$unikey='parameter_0_'.$name;
                   11958: 				$part=0;
                   11959: 			    } else {
                   11960: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11961: 			    }
1.339     albertel 11962: 			    if ($subp eq 'display') {
                   11963: 				$value.=' [Part: '.$part.']';
                   11964: 			    }
1.599     albertel 11965: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11966: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11967: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11968: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11969: 			    }
1.599     albertel 11970: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11971: 				$metaentry{':'.$unikey}=
                   11972: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11973: 			    }
1.339     albertel 11974: 			}
                   11975: 		    }
                   11976: 		} else {
1.172     www      11977: #
                   11978: # This is not a package - some other kind of start tag
1.339     albertel 11979: #
                   11980: 		    my $entry=$token->[1];
1.1068    www      11981: 		    my $unikey='';
1.175     www      11982: 
1.339     albertel 11983: 		    if ($entry eq 'import') {
1.175     www      11984: #
                   11985: # Importing a library here
1.339     albertel 11986: #
1.1067    www      11987:                         my $location=$parser->get_text('/import');
                   11988:                         my $dir=$filename;
                   11989:                         $dir=~s|[^/]*$||;
                   11990:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11991: 
                   11992:                         my $importid=$token->[2]->{'id'};
1.1068    www      11993:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11994: #
                   11995: # Check metadata for imported file to
                   11996: # see if it contained response items
                   11997: #
                   11998:                         my %currmetaentry = %metaentry;
                   11999:                         my $libresponseorder = &metadata($location,'responseorder');
                   12000:                         my $origfile;
                   12001:                         if ($libresponseorder ne '') {
                   12002:                             if ($#origfiletagids<0) {
                   12003:                                 undef(%importedrespids);
                   12004:                                 undef(%importedpartids);
                   12005:                             }
                   12006:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12007:                             if (@{$importedrespids{$importid}} > 0) {
                   12008:                                 $importedresponses = 1;
                   12009: # We need to get the original file and the imported file to get the response order correct
                   12010: # Load and inspect original file
                   12011:                                 if ($#origfiletagids<0) {
                   12012:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12013:                                     $origfile=&getfile($origfilelocation);
                   12014:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12015:                                 }
                   12016:                             }
                   12017:                         }
                   12018: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12019: # hash populated for imported library file
                   12020:                         %metaentry = %currmetaentry;
                   12021:                         undef(%currmetaentry);
1.1068    www      12022:                         if ($importmode eq 'problem') {
1.1069    www      12023: # Import as problem/response
1.1068    www      12024:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12025:                         } elsif ($importmode eq 'part') {
                   12026: # Import as part(s)
1.1069    www      12027:                            $importedparts=1;
                   12028: # We need to get the original file and the imported file to get the part order correct
                   12029: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12030: # Load and inspect original file if we didn't do that already
                   12031:                            if ($#origfiletagids<0) {
                   12032:                                undef(%importedrespids);
                   12033:                                undef(%importedpartids);
                   12034:                                if ($origfile eq '') {
                   12035:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12036:                                    $origfile=&getfile($origfilelocation);
                   12037:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12038:                                }
1.1070    www      12039:                            }
                   12040: 
1.1069    www      12041: # Load and inspect imported file
                   12042:                            my $impfile=&getfile($location);
                   12043:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12044:                            if ($#impfilepartids>=0) {
                   12045: # This problem had parts
1.1070    www      12046:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12047:                            } else {
                   12048: # Importing by turning a single problem into a problem part
                   12049: # It gets the import-tags ID as part-ID
                   12050:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12051:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12052:                            }
1.1068    www      12053:                         } else {
                   12054: # Normal import
                   12055:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12056:                            if (defined($token->[2]->{'id'})) {
                   12057:                               $unikey.='_'.$token->[2]->{'id'};
                   12058:                            }
1.1067    www      12059:                         }
                   12060: 
1.339     albertel 12061: 			if ($depthcount<20) {
1.736     albertel 12062: 			    my $metadata = 
                   12063: 				&metadata($uri,'keys', $location,$unikey,
                   12064: 					  $depthcount+1);
                   12065: 			    foreach my $meta (split(',',$metadata)) {
                   12066: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12067: 				$metathesekeys{$meta}=1;
1.339     albertel 12068: 			    }
1.1068    www      12069: 			
                   12070:                         }
1.1067    www      12071: 		    } else {
                   12072: #
                   12073: # Not importing, some other kind of non-package, non-library start tag
                   12074: # 
                   12075:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12076:                         if (defined($token->[2]->{'id'})) {
                   12077:                             $unikey.='_'.$token->[2]->{'id'};
                   12078:                         }
1.339     albertel 12079: 			if (defined($token->[2]->{'name'})) { 
                   12080: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12081: 			}
                   12082: 			$metathesekeys{$unikey}=1;
1.736     albertel 12083: 			foreach my $param (@{$token->[3]}) {
                   12084: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12085: 				$token->[2]->{$param};
1.339     albertel 12086: 			}
                   12087: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12088: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12089: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12090: 		 # only ws inside the tag, and not in default, so use default
                   12091: 		 # as value
1.599     albertel 12092: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12093: 			} elsif ( $internaltext =~ /\S/ ) {
                   12094: 		  # something interesting inside the tag
                   12095: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12096: 			} else {
1.908     albertel 12097: 		  # no interesting values, don't set a default
1.339     albertel 12098: 			}
1.172     www      12099: # end of not-a-package not-a-library import
1.339     albertel 12100: 		    }
1.172     www      12101: # end of not-a-package start tag
1.339     albertel 12102: 		}
1.172     www      12103: # the next is the end of "start tag"
1.339     albertel 12104: 	    }
                   12105: 	}
1.483     albertel 12106: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12107: 	$extension = lc($extension);
                   12108: 	if ($extension eq 'htm') { $extension='html'; }
                   12109: 
1.737     albertel 12110: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12111: 	    #no specific packages #how's our extension
                   12112: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12113: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12114: 					 \%metathesekeys);
                   12115: 	}
1.883     albertel 12116: 
                   12117: 	if (!exists($metaentry{':packages'})
                   12118: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12119: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12120: 		#no specific packages well let's get default then
                   12121: 		if ($key!~/^default&/) { next; }
1.488     albertel 12122: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12123: 					     \%metathesekeys);
                   12124: 	    }
                   12125: 	}
1.338     www      12126: # are there custom rights to evaluate
1.599     albertel 12127: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12128: 
1.338     www      12129:     #
                   12130:     # Importing a rights file here
1.339     albertel 12131:     #
                   12132: 	    unless ($depthcount) {
1.599     albertel 12133: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12134: 		my $dir=$filename;
                   12135: 		$dir=~s|[^/]*$||;
                   12136: 		$location=&filelocation($dir,$location);
1.736     albertel 12137: 		my $rights_metadata =
                   12138: 		    &metadata($uri,'keys',$location,'_rights',
                   12139: 			      $depthcount+1);
                   12140: 		foreach my $rights (split(',',$rights_metadata)) {
                   12141: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12142: 		    $metathesekeys{$rights}=1;
1.339     albertel 12143: 		}
                   12144: 	    }
                   12145: 	}
1.737     albertel 12146: 	# uniqifiy package listing
                   12147: 	my %seen;
                   12148: 	my @uniq_packages =
                   12149: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12150: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12151: 
1.1172.2.99  raeburn  12152:         if (($importedresponses) || ($importedparts)) {
                   12153:             if ($importedparts) {
1.1070    www      12154: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12155:                 $metaentry{':partorder'}='';
                   12156:                 $metathesekeys{'partorder'}=1;
                   12157:             }
                   12158:             if ($importedresponses) {
                   12159: # We had imported responses and need to rebuild responseorder
                   12160:                 $metaentry{':responseorder'}='';
                   12161:                 $metathesekeys{'responseorder'}=1;
                   12162:             }
                   12163:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12164:                 my $origid = $origfiletagids[$index+1];
                   12165:                 if ($origfiletagids[$index] eq 'part') {
                   12166: # Original part, part of the problem
                   12167:                     if ($importedparts) {
                   12168:                         $metaentry{':partorder'}.=','.$origid;
                   12169:                     }
                   12170:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12171:                     if ($importedparts) {
                   12172: # We have imported parts at this position
                   12173:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12174:                     }
                   12175:                     if ($importedresponses) {
                   12176: # We have imported responses at this position
                   12177:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12178:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12179:                         }
                   12180:                     }
                   12181:                 } else {
                   12182: # Original response item, part of the problem
                   12183:                     if ($importedresponses) {
                   12184:                         $metaentry{':responseorder'}.=','.$origid;
                   12185:                     }
                   12186:                 }
                   12187:             }
                   12188:             if ($importedparts) {
                   12189:                 $metaentry{':partorder'}=~s/^\,//;
                   12190:             }
                   12191:             if ($importedresponses) {
                   12192:                 $metaentry{':responseorder'}=~s/^\,//;
                   12193:             }
1.1070    www      12194:         }
                   12195: 
1.737     albertel 12196: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12197: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12198: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12199: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12200: # this is the end of "was not already recently cached
1.71      www      12201:     }
1.599     albertel 12202:     return $metaentry{':'.$what};
1.261     albertel 12203: }
                   12204: 
1.488     albertel 12205: sub metadata_create_package_def {
1.483     albertel 12206:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12207:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12208:     if ($subp eq 'default') { next; }
                   12209:     
1.599     albertel 12210:     if (defined($metaentry{':packages'})) {
                   12211: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12212:     } else {
1.599     albertel 12213: 	$metaentry{':packages'}=$package;
1.483     albertel 12214:     }
                   12215:     my $value=$packagetab{$key};
                   12216:     my $unikey;
                   12217:     $unikey='parameter_0_'.$name;
1.599     albertel 12218:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12219:     $$metathesekeys{$unikey}=1;
1.599     albertel 12220:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12221: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12222:     }
1.599     albertel 12223:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12224: 	$metaentry{':'.$unikey}=
                   12225: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12226:     }
                   12227: }
                   12228: 
1.261     albertel 12229: sub metadata_generate_part0 {
                   12230:     my ($metadata,$metacache,$uri) = @_;
                   12231:     my %allnames;
1.737     albertel 12232:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12233: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12234: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12235: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12236: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12237: 	    $allnames{$name}=$part;
                   12238: 	  }
                   12239: 	}
                   12240:     }
                   12241:     foreach my $name (keys(%allnames)) {
                   12242:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12243:       my $key=":parameter_0_$name";
1.261     albertel 12244:       $$metacache{"$key.part"}='0';
                   12245:       $$metacache{"$key.name"}=$name;
1.428     albertel 12246:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12247: 					   $allnames{$name}.'_'.$name.
                   12248: 					   '.type'};
1.428     albertel 12249:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12250: 			     '.display'};
1.644     www      12251:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12252:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12253:       $$metacache{"$key.display"}=$olddis;
                   12254:     }
1.71      www      12255: }
                   12256: 
1.764     albertel 12257: # ------------------------------------------------------ Devalidate title cache
                   12258: 
                   12259: sub devalidate_title_cache {
                   12260:     my ($url)=@_;
                   12261:     if (!$env{'request.course.id'}) { return; }
                   12262:     my $symb=&symbread($url);
                   12263:     if (!$symb) { return; }
                   12264:     my $key=$env{'request.course.id'}."\0".$symb;
                   12265:     &devalidate_cache_new('title',$key);
                   12266: }
                   12267: 
1.1014    droeschl 12268: # ------------------------------------------------- Get the title of a course
                   12269: 
                   12270: sub current_course_title {
                   12271:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12272: }
1.301     www      12273: # ------------------------------------------------- Get the title of a resource
                   12274: 
                   12275: sub gettitle {
                   12276:     my $urlsymb=shift;
                   12277:     my $symb=&symbread($urlsymb);
1.534     albertel 12278:     if ($symb) {
1.620     albertel 12279: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12280: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12281: 	if (defined($cached)) { 
                   12282: 	    return $result;
                   12283: 	}
1.534     albertel 12284: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12285: 	my $title='';
1.907     albertel 12286: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12287: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12288: 	} else {
                   12289: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12290: 		    &GDBM_READER(),0640)) {
                   12291: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12292: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12293: 		untie(%bighash);
                   12294: 	    }
1.534     albertel 12295: 	}
                   12296: 	$title=~s/\&colon\;/\:/gs;
                   12297: 	if ($title) {
1.1159    www      12298: # Remember both $symb and $title for dynamic metadata
                   12299:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12300:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12301: # Cache this title and then return it
1.599     albertel 12302: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12303: 	}
                   12304: 	$urlsymb=$url;
                   12305:     }
                   12306:     my $title=&metadata($urlsymb,'title');
                   12307:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12308:     return $title;
1.301     www      12309: }
1.613     albertel 12310: 
1.614     albertel 12311: sub get_slot {
                   12312:     my ($which,$cnum,$cdom)=@_;
                   12313:     if (!$cnum || !$cdom) {
1.790     albertel 12314: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12315: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12316: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12317:     }
1.703     albertel 12318:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12319:     my %slotinfo;
                   12320:     if (exists($remembered{$key})) {
                   12321: 	$slotinfo{$which} = $remembered{$key};
                   12322:     } else {
                   12323: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12324: 	&Apache::lonhomework::showhash(%slotinfo);
                   12325: 	my ($tmp)=keys(%slotinfo);
                   12326: 	if ($tmp=~/^error:/) { return (); }
                   12327: 	$remembered{$key} = $slotinfo{$which};
                   12328:     }
1.616     albertel 12329:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12330: 	return %{$slotinfo{$which}};
                   12331:     }
                   12332:     return $slotinfo{$which};
1.614     albertel 12333: }
1.1150    raeburn  12334: 
                   12335: sub get_reservable_slots {
                   12336:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12337:     my $now = time;
                   12338:     my $reservable_info;
                   12339:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12340:     if (exists($remembered{$key})) {
                   12341:         $reservable_info = $remembered{$key};
                   12342:     } else {
                   12343:         my %resv;
                   12344:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12345:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12346:         $reservable_info = \%resv;
                   12347:         $remembered{$key} = $reservable_info;
                   12348:     }
                   12349:     return $reservable_info;
                   12350: }
                   12351: 
                   12352: sub get_course_slots {
                   12353:     my ($cnum,$cdom) = @_;
                   12354:     my $hashid=$cnum.':'.$cdom;
                   12355:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12356:     if (defined($cached)) {
                   12357:         if (ref($result) eq 'HASH') {
                   12358:             return %{$result};
                   12359:         }
                   12360:     } else {
                   12361:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12362:         my ($tmp) = keys(%slots);
                   12363:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12364:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12365:             return %slots;
                   12366:         }
                   12367:     }
                   12368:     return;
                   12369: }
                   12370: 
                   12371: sub devalidate_slots_cache {
                   12372:     my ($cnum,$cdom)=@_;
                   12373:     my $hashid=$cnum.':'.$cdom;
                   12374:     &devalidate_cache_new('allslots',$hashid);
                   12375: }
                   12376: 
1.1172.2.8  raeburn  12377: sub get_coursechange {
                   12378:     my ($cdom,$cnum) = @_;
                   12379:     if ($cdom eq '' || $cnum eq '') {
                   12380:         return unless ($env{'request.course.id'});
                   12381:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12382:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12383:     }
                   12384:     my $hashid=$cdom.'_'.$cnum;
                   12385:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12386:     if ((defined($cached)) && ($change ne '')) {
                   12387:         return $change;
                   12388:     } else {
                   12389:         my %crshash;
                   12390:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12391:         if ($crshash{'internal.contentchange'} eq '') {
                   12392:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12393:             if ($change eq '') {
                   12394:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12395:                 $change = $crshash{'internal.created'};
                   12396:             }
                   12397:         } else {
                   12398:             $change = $crshash{'internal.contentchange'};
                   12399:         }
                   12400:         my $cachetime = 600;
                   12401:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12402:     }
                   12403:     return $change;
                   12404: }
                   12405: 
                   12406: sub devalidate_coursechange_cache {
                   12407:     my ($cnum,$cdom)=@_;
                   12408:     my $hashid=$cnum.':'.$cdom;
                   12409:     &devalidate_cache_new('crschange',$hashid);
                   12410: }
                   12411: 
1.31      www      12412: # ------------------------------------------------- Update symbolic store links
                   12413: 
                   12414: sub symblist {
                   12415:     my ($mapname,%newhash)=@_;
1.438     www      12416:     $mapname=&deversion(&declutter($mapname));
1.31      www      12417:     my %hash;
1.620     albertel 12418:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12419:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12420:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12421: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12422: 		next if ($url eq 'last_known'
                   12423: 			 && $env{'form.no_update_last_known'});
                   12424: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12425: 						    $newhash{$url}->[1],
                   12426: 						    $newhash{$url}->[0]);
1.191     harris41 12427:             }
1.31      www      12428:             if (untie(%hash)) {
                   12429: 		return 'ok';
                   12430:             }
                   12431:         }
                   12432:     }
                   12433:     return 'error';
1.212     www      12434: }
                   12435: 
                   12436: # --------------------------------------------------------------- Verify a symb
                   12437: 
                   12438: sub symbverify {
1.1172.2.11  raeburn  12439:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12440:     my $thisfn=$thisurl;
1.439     www      12441:     $thisfn=&declutter($thisfn);
1.215     www      12442: # direct jump to resource in page or to a sequence - will construct own symbs
                   12443:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12444: # check URL part
1.409     www      12445:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12446: 
1.431     www      12447:     unless ($url eq $thisfn) { return 0; }
1.213     www      12448: 
1.216     www      12449:     $symb=&symbclean($symb);
1.510     www      12450:     $thisurl=&deversion($thisurl);
1.439     www      12451:     $thisfn=&deversion($thisfn);
1.213     www      12452: 
                   12453:     my %bighash;
                   12454:     my $okay=0;
1.431     www      12455: 
1.620     albertel 12456:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12457:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12458:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12459:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12460:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12461:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12462:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12463:             }
                   12464:         }
                   12465:         my $ids;
1.1172.2.118.  .5(raebu 12466:20):         if ($map =~ m{^uploaded/.+\.page$}) {
                   12467:20):             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12468:         } else {
                   12469:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12470:         }
1.1102    raeburn  12471:         unless ($ids) {
1.1172.2.13  raeburn  12472:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12473:             $ids=$bighash{$idkey};
1.216     www      12474:         }
                   12475:         if ($ids) {
                   12476: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12477:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12478:                 $symb =~ s/\?.+$//;
                   12479:             }
1.800     albertel 12480: 	    foreach my $id (split(/\,/,$ids)) {
                   12481: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12482:                if (
                   12483:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12484:    eq $symb) {
1.1172.2.11  raeburn  12485:                    if (ref($encstate)) {
                   12486:                        $$encstate = $bighash{'encrypted_'.$id};
                   12487:                    }
1.1172.2.13  raeburn  12488:                    if (($env{'request.role.adv'}) ||
                   12489:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12490:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12491:                        $okay=1;
                   12492:                        last;
                   12493:                    }
                   12494:                }
                   12495:            }
1.216     www      12496:         }
1.213     www      12497: 	untie(%bighash);
                   12498:     }
                   12499:     return $okay;
1.31      www      12500: }
                   12501: 
1.210     www      12502: # --------------------------------------------------------------- Clean-up symb
                   12503: 
                   12504: sub symbclean {
                   12505:     my $symb=shift;
1.568     albertel 12506:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12507: # remove version from map
                   12508:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12509: 
1.210     www      12510: # remove version from URL
                   12511:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12512: 
1.507     www      12513: # remove wrapper
                   12514: 
1.510     www      12515:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12516:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12517:     return $symb;
1.409     www      12518: }
                   12519: 
                   12520: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12521: 
                   12522: sub encode_symb {
                   12523:     my ($map,$resid,$url)=@_;
                   12524:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12525: }
1.409     www      12526: 
                   12527: sub decode_symb {
1.568     albertel 12528:     my $symb=shift;
                   12529:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12530:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12531:     return (&fixversion($map),$resid,&fixversion($url));
                   12532: }
                   12533: 
                   12534: sub fixversion {
                   12535:     my $fn=shift;
1.609     banghart 12536:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12537:     my %bighash;
                   12538:     my $uri=&clutter($fn);
1.620     albertel 12539:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12540: # is this cached?
1.599     albertel 12541:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12542:     if (defined($cached)) { return $result; }
                   12543: # unfortunately not cached, or expired
1.620     albertel 12544:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12545: 	    &GDBM_READER(),0640)) {
                   12546:  	if ($bighash{'version_'.$uri}) {
                   12547:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12548:  	    unless (($version eq 'mostrecent') || 
                   12549: 		    ($version==&getversion($uri))) {
1.440     www      12550:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12551:  	    }
                   12552:  	}
                   12553:  	untie %bighash;
1.413     www      12554:     }
1.599     albertel 12555:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12556: }
                   12557: 
                   12558: sub deversion {
                   12559:     my $url=shift;
                   12560:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12561:     return $url;
1.210     www      12562: }
                   12563: 
1.31      www      12564: # ------------------------------------------------------ Return symb list entry
                   12565: 
                   12566: sub symbread {
1.1172.2.118.  .8(raebu 12567:20):     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
          .9(raebu 12568:20):         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12569:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.118.  .9(raebu 12570:20):     if (defined($env{$cache_str})) {
          .8(raebu 12571:20):         unless (ref($possibles) eq 'HASH') {
                   12572:20):             if ($ignorecachednull) {
                   12573:20):                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12574:20):             } else {
                   12575:20):                 return $env{$cache_str};
                   12576:20):             }
1.1172.2.66  raeburn  12577:         }
                   12578:     }
1.242     www      12579: # no filename provided? try from environment
1.1172.2.54  raeburn  12580:     unless ($thisfn) {
1.620     albertel 12581:         if ($env{'request.symb'}) {
1.1172.2.118.  .9(raebu 12582:20):             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12583:         }
                   12584:         $thisfn=$env{'request.filename'};
1.44      www      12585:     }
1.569     albertel 12586:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12587: # is that filename actually a symb? Verify, clean, and return
                   12588:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12589: 	if (&symbverify($thisfn,$1)) {
1.1172.2.118.  .9(raebu 12590:20): 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12591: 	}
1.242     www      12592:     }
1.44      www      12593:     $thisfn=declutter($thisfn);
1.31      www      12594:     my %hash;
1.37      www      12595:     my %bighash;
                   12596:     my $syval='';
1.620     albertel 12597:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12598:         my $targetfn = $thisfn;
1.609     banghart 12599:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12600:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12601:         }
1.687     albertel 12602: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12603: 	    $targetfn=$1;
                   12604: 	}
1.1172.2.118.  .9(raebu 12605:20):         unless ($ignoresymbdb) {
          .8(raebu 12606:20):             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12607:20):                           &GDBM_READER(),0640)) {
                   12608:20): 	        $syval=$hash{$targetfn};
                   12609:20):                 untie(%hash);
                   12610:20):             }
          .9(raebu 12611:20):             if ($syval && $checkforblock) {
                   12612:20):                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
          .8(raebu 12613:20):                 if (@blockers) {
                   12614:20):                     $syval='';
                   12615:20):                 }
                   12616:20):             }
1.37      www      12617:         }
                   12618: # ---------------------------------------------------------- There was an entry
                   12619:         if ($syval) {
1.601     albertel 12620: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12621: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12622: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12623: 		    #return $env{$cache_str}='';
1.601     albertel 12624: 		#}    
                   12625: 		#$syval.=$1;
                   12626: 	    #}
1.37      www      12627:         } else {
                   12628: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12629:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12630:                             &GDBM_READER(),0640)) {
1.37      www      12631: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12632:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12633:               unless ($ids) { 
                   12634:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12635:               }
                   12636:               unless ($ids) {
                   12637: # alias?
                   12638: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12639:               }
1.37      www      12640:               if ($ids) {
                   12641: # ------------------------------------------------------------------- Has ID(s)
                   12642:                  my @possibilities=split(/\,/,$ids);
1.39      www      12643:                  if ($#possibilities==0) {
                   12644: # ----------------------------------------------- There is only one possibility
1.37      www      12645: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12646: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12647: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12648:                      if (ref($possibles) eq 'HASH') {
1.1172.2.118.  .8(raebu 12649:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12650:20):                              $possibles->{$syval} = 1;
                   12651:20):                          }
1.1172.2.66  raeburn  12652:                      }
                   12653:                      if ($checkforblock) {
1.1172.2.118.  .8(raebu 12654:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12655:20):                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
                   12656:20):                              if (@blockers) {
                   12657:20):                                  $syval = '';
                   12658:20):                                  untie(%bighash);
                   12659:20):                                  return $env{$cache_str}='';
                   12660:20):                              }
1.1172.2.66  raeburn  12661:                          }
                   12662:                      }
                   12663:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12664: # ------------------------------------------ There is more than one possibility
                   12665:                      my $realpossible=0;
1.800     albertel 12666:                      foreach my $id (@possibilities) {
                   12667: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12668:                          my $canaccess;
                   12669:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12670:                              $canaccess = 1;
                   12671:                          } else {
                   12672:                              $canaccess = &allowed('bre',$file);
                   12673:                          }
                   12674:                          if ($canaccess) {
                   12675:          		     my ($mapid,$resid)=split(/\./,$id);
                   12676:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12677:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12678:                                                              $resid,$thisfn);
1.1172.2.118.  .8(raebu 12679:20):                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
                   12680:20):                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12681:                                  if ($checkforblock) {
1.1172.2.118.  .8(raebu 12682:20):                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
                   12683:20):                                      if (@blockers > 0) {
                   12684:20):                                          $syval = '';
                   12685:20):                                      } else {
1.1172.2.66  raeburn  12686:                                          $syval = $poss_syval;
                   12687:                                          $realpossible++;
                   12688:                                      }
                   12689:                                  } else {
                   12690:                                      $syval = $poss_syval;
                   12691:                                      $realpossible++;
                   12692:                                  }
1.1172.2.118.  .8(raebu 12693:20):                                  if ($syval) {
                   12694:20):                                      if (ref($possibles) eq 'HASH') {
                   12695:20):                                          $possibles->{$syval} = 1;
                   12696:20):                                      }
                   12697:20):                                  }
1.1172.2.66  raeburn  12698:                              }
1.39      www      12699: 			 }
1.191     harris41 12700:                      }
1.39      www      12701: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12702:                  } else {
                   12703:                      $syval='';
1.37      www      12704:                  }
                   12705: 	      }
1.1172.2.66  raeburn  12706:               untie(%bighash);
1.481     raeburn  12707:            }
1.31      www      12708:         }
1.62      www      12709:         if ($syval) {
1.1172.2.118.  .9(raebu 12710:20): 	    return $env{$cache_str}=$syval;
1.62      www      12711:         }
1.31      www      12712:     }
1.949     raeburn  12713:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12714:     return $env{$cache_str}='';
1.31      www      12715: }
                   12716: 
                   12717: # ---------------------------------------------------------- Return random seed
                   12718: 
1.32      www      12719: sub numval {
                   12720:     my $txt=shift;
                   12721:     $txt=~tr/A-J/0-9/;
                   12722:     $txt=~tr/a-j/0-9/;
                   12723:     $txt=~tr/K-T/0-9/;
                   12724:     $txt=~tr/k-t/0-9/;
                   12725:     $txt=~tr/U-Z/0-5/;
                   12726:     $txt=~tr/u-z/0-5/;
                   12727:     $txt=~s/\D//g;
1.564     albertel 12728:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12729:     return int($txt);
1.368     albertel 12730: }
                   12731: 
1.484     albertel 12732: sub numval2 {
                   12733:     my $txt=shift;
                   12734:     $txt=~tr/A-J/0-9/;
                   12735:     $txt=~tr/a-j/0-9/;
                   12736:     $txt=~tr/K-T/0-9/;
                   12737:     $txt=~tr/k-t/0-9/;
                   12738:     $txt=~tr/U-Z/0-5/;
                   12739:     $txt=~tr/u-z/0-5/;
                   12740:     $txt=~s/\D//g;
                   12741:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12742:     my $total;
                   12743:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12744:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12745:     return int($total);
                   12746: }
                   12747: 
1.575     albertel 12748: sub numval3 {
                   12749:     use integer;
                   12750:     my $txt=shift;
                   12751:     $txt=~tr/A-J/0-9/;
                   12752:     $txt=~tr/a-j/0-9/;
                   12753:     $txt=~tr/K-T/0-9/;
                   12754:     $txt=~tr/k-t/0-9/;
                   12755:     $txt=~tr/U-Z/0-5/;
                   12756:     $txt=~tr/u-z/0-5/;
                   12757:     $txt=~s/\D//g;
                   12758:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12759:     my $total;
                   12760:     foreach my $val (@txts) { $total+=$val; }
                   12761:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12762:     return $total;
                   12763: }
                   12764: 
1.675     albertel 12765: sub digest {
                   12766:     my ($data)=@_;
                   12767:     my $digest=&Digest::MD5::md5($data);
                   12768:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12769:     my ($e,$f);
                   12770:     {
                   12771:         use integer;
                   12772:         $e=($a+$b);
                   12773:         $f=($c+$d);
                   12774:         if ($_64bit) {
                   12775:             $e=(($e<<32)>>32);
                   12776:             $f=(($f<<32)>>32);
                   12777:         }
                   12778:     }
                   12779:     if (wantarray) {
                   12780: 	return ($e,$f);
                   12781:     } else {
                   12782: 	my $g;
                   12783: 	{
                   12784: 	    use integer;
                   12785: 	    $g=($e+$f);
                   12786: 	    if ($_64bit) {
                   12787: 		$g=(($g<<32)>>32);
                   12788: 	    }
                   12789: 	}
                   12790: 	return $g;
                   12791:     }
                   12792: }
                   12793: 
1.368     albertel 12794: sub latest_rnd_algorithm_id {
1.675     albertel 12795:     return '64bit5';
1.366     albertel 12796: }
1.32      www      12797: 
1.503     albertel 12798: sub get_rand_alg {
                   12799:     my ($courseid)=@_;
1.790     albertel 12800:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12801:     if ($courseid) {
1.620     albertel 12802: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12803:     }
                   12804:     return &latest_rnd_algorithm_id();
                   12805: }
                   12806: 
1.562     albertel 12807: sub validCODE {
                   12808:     my ($CODE)=@_;
                   12809:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12810:     return 0;
                   12811: }
                   12812: 
1.491     albertel 12813: sub getCODE {
1.620     albertel 12814:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12815:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12816: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12817: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12818: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12819:     }
                   12820:     return undef;
                   12821: }
1.1133    foxr     12822: #
                   12823: #  Determines the random seed for a specific context:
                   12824: #
                   12825: # parameters:
                   12826: #   symb      - in course context the symb for the seed.
                   12827: #   course_id - The course id of the form domain_coursenum.
                   12828: #   domain    - Domain for the user.
                   12829: #   course    - Course for the user.
                   12830: #   cenv      - environment of the course.
                   12831: #
                   12832: # NOTE:
                   12833: #   All parameters are picked out of the environment if missing
                   12834: #   or not defined.
                   12835: #   If a symb cannot be determined the current time is used instead.
                   12836: #
                   12837: #  For a given well defined symb, courside, domain, username,
                   12838: #  and course environment, the seed is reproducible.
                   12839: #
1.31      www      12840: sub rndseed {
1.1133    foxr     12841:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12842:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12843:     if (!defined($symb)) {
1.366     albertel 12844: 	unless ($symb=$wsymb) { return time; }
                   12845:     }
1.1146    foxr     12846:     if (!defined $courseid) { 
                   12847: 	$courseid=$wcourseid; 
                   12848:     }
                   12849:     if (!defined $domain) { $domain=$wdomain; }
                   12850:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12851: 
                   12852:     my $which;
                   12853:     if (defined($cenv->{'rndseed'})) {
                   12854: 	$which = $cenv->{'rndseed'};
                   12855:     } else {
                   12856: 	$which =&get_rand_alg($courseid);
                   12857:     }
1.491     albertel 12858:     if (defined(&getCODE())) {
1.675     albertel 12859: 	if ($which eq '64bit5') {
                   12860: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12861: 	} elsif ($which eq '64bit4') {
1.575     albertel 12862: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12863: 	} else {
                   12864: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12865: 	}
1.675     albertel 12866:     } elsif ($which eq '64bit5') {
                   12867: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12868:     } elsif ($which eq '64bit4') {
                   12869: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12870:     } elsif ($which eq '64bit3') {
                   12871: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12872:     } elsif ($which eq '64bit2') {
                   12873: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12874:     } elsif ($which eq '64bit') {
                   12875: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12876:     }
                   12877:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12878: }
                   12879: 
                   12880: sub rndseed_32bit {
                   12881:     my ($symb,$courseid,$domain,$username)=@_;
                   12882:     {
                   12883: 	use integer;
                   12884: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12885: 	my $symbseed=numval($symb) << 22;
                   12886: 	my $namechck=unpack("%32C*",$username) << 17;
                   12887: 	my $nameseed=numval($username) << 12;
                   12888: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12889: 	my $courseseed=unpack("%32C*",$courseid);
                   12890: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12891: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12892: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12893: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12894: 	return $num;
                   12895:     }
                   12896: }
                   12897: 
                   12898: sub rndseed_64bit {
                   12899:     my ($symb,$courseid,$domain,$username)=@_;
                   12900:     {
                   12901: 	use integer;
                   12902: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12903: 	my $symbseed=numval($symb) << 10;
                   12904: 	my $namechck=unpack("%32S*",$username);
                   12905: 	
                   12906: 	my $nameseed=numval($username) << 21;
                   12907: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12908: 	my $courseseed=unpack("%32S*",$courseid);
                   12909: 	
                   12910: 	my $num1=$symbchck+$symbseed+$namechck;
                   12911: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12912: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12913: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12914: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12915: 	return "$num1,$num2";
1.155     albertel 12916:     }
1.366     albertel 12917: }
                   12918: 
1.443     albertel 12919: sub rndseed_64bit2 {
                   12920:     my ($symb,$courseid,$domain,$username)=@_;
                   12921:     {
                   12922: 	use integer;
                   12923: 	# strings need to be an even # of cahracters long, it it is odd the
                   12924:         # last characters gets thrown away
                   12925: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12926: 	my $symbseed=numval($symb) << 10;
                   12927: 	my $namechck=unpack("%32S*",$username.' ');
                   12928: 	
                   12929: 	my $nameseed=numval($username) << 21;
1.501     albertel 12930: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12931: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12932: 	
                   12933: 	my $num1=$symbchck+$symbseed+$namechck;
                   12934: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12935: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12936: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12937: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12938: 	return "$num1,$num2";
                   12939:     }
                   12940: }
                   12941: 
                   12942: sub rndseed_64bit3 {
                   12943:     my ($symb,$courseid,$domain,$username)=@_;
                   12944:     {
                   12945: 	use integer;
                   12946: 	# strings need to be an even # of cahracters long, it it is odd the
                   12947:         # last characters gets thrown away
                   12948: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12949: 	my $symbseed=numval2($symb) << 10;
                   12950: 	my $namechck=unpack("%32S*",$username.' ');
                   12951: 	
                   12952: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12953: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12954: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12955: 	
                   12956: 	my $num1=$symbchck+$symbseed+$namechck;
                   12957: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12958: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12959: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12960: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12961: 	
1.503     albertel 12962: 	return "$num1:$num2";
1.443     albertel 12963:     }
                   12964: }
                   12965: 
1.575     albertel 12966: sub rndseed_64bit4 {
                   12967:     my ($symb,$courseid,$domain,$username)=@_;
                   12968:     {
                   12969: 	use integer;
                   12970: 	# strings need to be an even # of cahracters long, it it is odd the
                   12971:         # last characters gets thrown away
                   12972: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12973: 	my $symbseed=numval3($symb) << 10;
                   12974: 	my $namechck=unpack("%32S*",$username.' ');
                   12975: 	
                   12976: 	my $nameseed=numval3($username) << 21;
                   12977: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12978: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12979: 	
                   12980: 	my $num1=$symbchck+$symbseed+$namechck;
                   12981: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12982: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12983: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12984: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12985: 	
1.575     albertel 12986: 	return "$num1:$num2";
                   12987:     }
                   12988: }
                   12989: 
1.675     albertel 12990: sub rndseed_64bit5 {
                   12991:     my ($symb,$courseid,$domain,$username)=@_;
                   12992:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12993:     return "$num1:$num2";
                   12994: }
                   12995: 
1.366     albertel 12996: sub rndseed_CODE_64bit {
                   12997:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12998:     {
1.366     albertel 12999: 	use integer;
1.443     albertel 13000: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13001: 	my $symbseed=numval2($symb);
1.491     albertel 13002: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13003: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13004: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13005: 	my $num1=$symbseed+$CODEchck;
                   13006: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13007: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13008: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13009: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13010: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13011: 	return "$num1:$num2";
1.366     albertel 13012:     }
                   13013: }
                   13014: 
1.575     albertel 13015: sub rndseed_CODE_64bit4 {
                   13016:     my ($symb,$courseid,$domain,$username)=@_;
                   13017:     {
                   13018: 	use integer;
                   13019: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13020: 	my $symbseed=numval3($symb);
                   13021: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13022: 	my $CODEseed=numval3(&getCODE());
                   13023: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13024: 	my $num1=$symbseed+$CODEchck;
                   13025: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13026: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13027: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13028: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13029: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13030: 	return "$num1:$num2";
                   13031:     }
                   13032: }
                   13033: 
1.675     albertel 13034: sub rndseed_CODE_64bit5 {
                   13035:     my ($symb,$courseid,$domain,$username)=@_;
                   13036:     my $code = &getCODE();
                   13037:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13038:     return "$num1:$num2";
                   13039: }
                   13040: 
1.366     albertel 13041: sub setup_random_from_rndseed {
                   13042:     my ($rndseed)=@_;
1.503     albertel 13043:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13044: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13045:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13046:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13047:         } else {
                   13048:             &Math::Random::random_set_seed($num1,$num2);
                   13049:         }
1.366     albertel 13050:     } else {
                   13051: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13052:     }
1.36      albertel 13053: }
                   13054: 
1.474     albertel 13055: sub latest_receipt_algorithm_id {
1.835     albertel 13056:     return 'receipt3';
1.474     albertel 13057: }
                   13058: 
1.480     www      13059: sub recunique {
                   13060:     my $fucourseid=shift;
                   13061:     my $unique;
1.835     albertel 13062:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13063: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13064: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13065:     } else {
                   13066: 	$unique=$perlvar{'lonReceipt'};
                   13067:     }
                   13068:     return unpack("%32C*",$unique);
                   13069: }
                   13070: 
                   13071: sub recprefix {
                   13072:     my $fucourseid=shift;
                   13073:     my $prefix;
1.835     albertel 13074:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13075: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13076: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13077:     } else {
                   13078: 	$prefix=$perlvar{'lonHostID'};
                   13079:     }
                   13080:     return unpack("%32C*",$prefix);
                   13081: }
                   13082: 
1.76      www      13083: sub ireceipt {
1.474     albertel 13084:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13085: 
                   13086:     my $return =&recprefix($fucourseid).'-';
                   13087: 
                   13088:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13089: 	$env{'request.state'} eq 'construct') {
                   13090: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13091: 	return $return;
                   13092:     }
                   13093: 
1.76      www      13094:     my $cuname=unpack("%32C*",$funame);
                   13095:     my $cudom=unpack("%32C*",$fudom);
                   13096:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13097:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13098:     my $cunique=&recunique($fucourseid);
1.474     albertel 13099:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13100:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13101: 
1.790     albertel 13102: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13103: 			       
                   13104: 	$return.= ($cunique%$cuname+
                   13105: 		   $cunique%$cudom+
                   13106: 		   $cusymb%$cuname+
                   13107: 		   $cusymb%$cudom+
                   13108: 		   $cucourseid%$cuname+
                   13109: 		   $cucourseid%$cudom+
                   13110: 		   $cpart%$cuname+
                   13111: 		   $cpart%$cudom);
                   13112:     } else {
                   13113: 	$return.= ($cunique%$cuname+
                   13114: 		   $cunique%$cudom+
                   13115: 		   $cusymb%$cuname+
                   13116: 		   $cusymb%$cudom+
                   13117: 		   $cucourseid%$cuname+
                   13118: 		   $cucourseid%$cudom);
                   13119:     }
                   13120:     return $return;
1.76      www      13121: }
                   13122: 
                   13123: sub receipt {
1.474     albertel 13124:     my ($part)=@_;
1.790     albertel 13125:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13126:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13127: }
1.260     ng       13128: 
1.790     albertel 13129: sub whichuser {
                   13130:     my ($passedsymb)=@_;
                   13131:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13132:     if (defined($env{'form.grade_symb'})) {
                   13133: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13134: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13135: 	if (!$allowed &&
                   13136: 	    exists($env{'request.course.sec'}) &&
                   13137: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13138: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13139: 			      '/'.$env{'request.course.sec'});
                   13140: 	}
                   13141: 	if ($allowed) {
                   13142: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13143: 	    $courseid=$tmp_courseid;
                   13144: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13145: 	    ($name)=&get_env_multiple('form.grade_username');
                   13146: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13147: 	}
                   13148:     }
                   13149:     if (!$passedsymb) {
                   13150: 	$symb=&symbread();
                   13151:     } else {
                   13152: 	$symb=$passedsymb;
                   13153:     }
                   13154:     $courseid=$env{'request.course.id'};
                   13155:     $domain=$env{'user.domain'};
                   13156:     $name=$env{'user.name'};
                   13157:     if ($name eq 'public' && $domain eq 'public') {
                   13158: 	if (!defined($env{'form.username'})) {
                   13159: 	    $env{'form.username'}.=time.rand(10000000);
                   13160: 	}
                   13161: 	$name.=$env{'form.username'};
                   13162:     }
                   13163:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13164: 
                   13165: }
                   13166: 
1.36      albertel 13167: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13168: # returns either the contents of the file or 
                   13169: # -1 if the file doesn't exist
1.481     raeburn  13170: #
                   13171: # if the target is a file that was uploaded via DOCS, 
                   13172: # a check will be made to see if a current copy exists on the local server,
                   13173: # if it does this will be served, otherwise a copy will be retrieved from
                   13174: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13175: # the local server.   
1.472     albertel 13176: 
1.36      albertel 13177: sub getfile {
1.538     albertel 13178:     my ($file) = @_;
1.609     banghart 13179:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13180:     &repcopy($file);
                   13181:     return &readfile($file);
                   13182: }
                   13183: 
                   13184: sub repcopy_userfile {
                   13185:     my ($file)=@_;
1.1142    raeburn  13186:     my $londocroot = $perlvar{'lonDocRoot'};
                   13187:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13188:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13189:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13190: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13191:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13192:     if (-e "$file") {
1.828     www      13193: # we already have a local copy, check it out
1.538     albertel 13194: 	my @fileinfo = stat($file);
1.828     www      13195: 	my $rtncode;
                   13196: 	my $info;
1.538     albertel 13197: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13198: 	if ($lwpresp ne 'ok') {
1.828     www      13199: # there is no such file anymore, even though we had a local copy
1.482     albertel 13200: 	    if ($rtncode eq '404') {
1.538     albertel 13201: 		unlink($file);
1.482     albertel 13202: 	    }
                   13203: 	    return -1;
                   13204: 	}
                   13205: 	if ($info < $fileinfo[9]) {
1.828     www      13206: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13207: 	    return 'ok';
1.828     www      13208: 	} else {
                   13209: # the file is outdated, get rid of it
                   13210: 	    unlink($file);
1.482     albertel 13211: 	}
1.828     www      13212:     }
                   13213: # one way or the other, at this point, we don't have the file
                   13214: # construct the correct path for the file
                   13215:     my @parts = ($cdom,$cnum); 
                   13216:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13217: 	push @parts, split(/\//,$1);
                   13218:     }
                   13219:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13220:     foreach my $part (@parts) {
                   13221: 	$path .= '/'.$part;
                   13222: 	if (!-e $path) {
                   13223: 	    mkdir($path,0770);
1.482     albertel 13224: 	}
                   13225:     }
1.828     www      13226: # now the path exists for sure
                   13227: # get a user agent
                   13228:     my $ua=new LWP::UserAgent;
                   13229:     my $transferfile=$file.'.in.transfer';
                   13230: # FIXME: this should flock
                   13231:     if (-e $transferfile) { return 'ok'; }
                   13232:     my $request;
                   13233:     $uri=~s/^\///;
1.980     raeburn  13234:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13235:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13236:     my $protocol = $protocol{$homeserver};
                   13237:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13238:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13239:     my $response=$ua->request($request,$transferfile);
                   13240: # did it work?
                   13241:     if ($response->is_error()) {
                   13242: 	unlink($transferfile);
                   13243: 	&logthis("Userfile repcopy failed for $uri");
                   13244: 	return -1;
                   13245:     }
                   13246: # worked, rename the transfer file
                   13247:     rename($transferfile,$file);
1.607     raeburn  13248:     return 'ok';
1.481     raeburn  13249: }
                   13250: 
1.517     albertel 13251: sub tokenwrapper {
                   13252:     my $uri=shift;
1.980     raeburn  13253:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13254:     $uri=~s|^/||;
1.620     albertel 13255:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13256:     my $token=$1;
1.552     albertel 13257:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13258:     if ($udom && $uname && $file) {
                   13259: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13260:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13261:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13262:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13263:         my $protocol = $protocol{$homeserver};
                   13264:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13265:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13266:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13267:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13268:     } else {
                   13269:         return '/adm/notfound.html';
                   13270:     }
                   13271: }
                   13272: 
1.828     www      13273: # call with reqtype HEAD: get last modification time
                   13274: # call with reqtype GET: get the file contents
                   13275: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13276: #
1.481     raeburn  13277: sub getuploaded {
                   13278:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13279:     $uri=~s/^\///;
1.980     raeburn  13280:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13281:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13282:     my $protocol = $protocol{$homeserver};
                   13283:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13284:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13285:     my $ua=new LWP::UserAgent;
                   13286:     my $request=new HTTP::Request($reqtype,$uri);
                   13287:     my $response=$ua->request($request);
                   13288:     $$rtncode = $response->code;
1.482     albertel 13289:     if (! $response->is_success()) {
                   13290: 	return 'failed';
                   13291:     }      
                   13292:     if ($reqtype eq 'HEAD') {
1.486     www      13293: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13294:     } elsif ($reqtype eq 'GET') {
                   13295: 	$$info = $response->content;
1.472     albertel 13296:     }
1.482     albertel 13297:     return 'ok';
1.36      albertel 13298: }
                   13299: 
1.481     raeburn  13300: sub readfile {
                   13301:     my $file = shift;
                   13302:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13303:     my $fh;
1.1172.2.96  raeburn  13304:     open($fh,"<",$file);
1.481     raeburn  13305:     my $a='';
1.800     albertel 13306:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13307:     return $a;
                   13308: }
                   13309: 
1.36      albertel 13310: sub filelocation {
1.590     banghart 13311:     my ($dir,$file) = @_;
                   13312:     my $location;
                   13313:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13314: 
                   13315:     if ($file =~ m-^/adm/-) {
                   13316: 	$file=~s-^/adm/wrapper/-/-;
                   13317: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13318:     }
1.882     albertel 13319: 
1.1139    www      13320:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13321:         $location = $file;
1.609     banghart 13322:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13323:         my ($udom,$uname,$filename)=
1.811     albertel 13324:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13325:         my $home=&homeserver($uname,$udom);
                   13326:         my $is_me=0;
                   13327:         my @ids=&current_machine_ids();
                   13328:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13329:         if ($is_me) {
1.1117    foxr     13330:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13331:         } else {
                   13332:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13333:   	      $udom.'/'.$uname.'/'.$filename;
                   13334:         }
1.882     albertel 13335:     } elsif ($file =~ m-^/adm/-) {
                   13336: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13337:     } else {
                   13338:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13339:         $file=~s:^/(res|priv)/:/:;
                   13340:         my $space=$1;
1.590     banghart 13341:         if ( !( $file =~ m:^/:) ) {
                   13342:             $location = $dir. '/'.$file;
                   13343:         } else {
1.1142    raeburn  13344:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13345:         }
1.59      albertel 13346:     }
1.590     banghart 13347:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13348:     while ($location=~m{/\.\./}) {
                   13349: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13350: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13351: 	} else {
                   13352: 	    $location=~ s{/\.\./}{/}g;
                   13353: 	}
                   13354:     } #remove dir/..
1.590     banghart 13355:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13356:     return $location;
1.46      www      13357: }
1.36      albertel 13358: 
1.46      www      13359: sub hreflocation {
                   13360:     my ($dir,$file)=@_;
1.980     raeburn  13361:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13362: 	$file=filelocation($dir,$file);
1.700     albertel 13363:     } elsif ($file=~m-^/adm/-) {
                   13364: 	$file=~s-^/adm/wrapper/-/-;
                   13365: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13366:     }
                   13367:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13368: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13369:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13370: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13371: 	        {/uploaded/$1/$2/}x;
1.46      www      13372:     }
1.913     albertel 13373:     if ($file=~ m{^/userfiles/}) {
                   13374: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13375:     }
1.462     albertel 13376:     return $file;
1.465     albertel 13377: }
                   13378: 
1.1139    www      13379: 
                   13380: 
                   13381: 
                   13382: 
1.465     albertel 13383: sub current_machine_domains {
1.853     albertel 13384:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13385: }
                   13386: 
                   13387: sub machine_domains {
                   13388:     my ($hostname) = @_;
1.465     albertel 13389:     my @domains;
1.838     albertel 13390:     my %hostname = &all_hostnames();
1.465     albertel 13391:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13392: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13393: 	if ($hostname eq $name) {
1.844     albertel 13394: 	    push(@domains,&host_domain($id));
1.465     albertel 13395: 	}
                   13396:     }
                   13397:     return @domains;
                   13398: }
                   13399: 
                   13400: sub current_machine_ids {
1.853     albertel 13401:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13402: }
                   13403: 
                   13404: sub machine_ids {
                   13405:     my ($hostname) = @_;
                   13406:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13407:     my @ids;
1.888     albertel 13408:     my %name_to_host = &all_names();
1.889     albertel 13409:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13410: 	return @{ $name_to_host{$hostname} };
                   13411:     }
                   13412:     return;
1.31      www      13413: }
                   13414: 
1.824     raeburn  13415: sub additional_machine_domains {
                   13416:     my @domains;
1.1172.2.96  raeburn  13417:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13418:     while( my $line = <$fh>) {
                   13419:         $line =~ s/\s//g;
                   13420:         push(@domains,$line);
                   13421:     }
                   13422:     return @domains;
                   13423: }
                   13424: 
                   13425: sub default_login_domain {
                   13426:     my $domain = $perlvar{'lonDefDomain'};
                   13427:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13428:     foreach my $posdom (&current_machine_domains(),
                   13429:                         &additional_machine_domains()) {
                   13430:         if (lc($posdom) eq lc($testdomain)) {
                   13431:             $domain=$posdom;
                   13432:             last;
                   13433:         }
                   13434:     }
                   13435:     return $domain;
                   13436: }
                   13437: 
1.1172.2.106  raeburn  13438: sub shared_institution {
                   13439:     my ($dom) = @_;
                   13440:     my $same_intdom;
                   13441:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13442:     if ($hostintdom ne '') {
                   13443:         my %iphost = &get_iphost();
                   13444:         my $primary_id = &domain($dom,'primary');
                   13445:         my $primary_ip = &get_host_ip($primary_id);
                   13446:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13447:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13448:                 my $intdom = &internet_dom($id);
                   13449:                 if ($intdom eq $hostintdom) {
                   13450:                     $same_intdom = 1;
                   13451:                     last;
                   13452:                 }
                   13453:             }
                   13454:         }
                   13455:     }
                   13456:     return $same_intdom;
                   13457: }
                   13458: 
1.1172.2.118.  .3(raebu 13459:20): sub uses_sts {
                   13460:20):     my ($ignore_cache) = @_;
                   13461:20):     my $lonhost = $perlvar{'lonHostID'};
                   13462:20):     my $hostname = &hostname($lonhost);
                   13463:20):     my $sts_on;
                   13464:20):     if ($protocol{$lonhost} eq 'https') {
                   13465:20):         my $cachetime = 12*3600;
                   13466:20):         if (!$ignore_cache) {
                   13467:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13468:20):             if (defined($cached)) {
                   13469:20):                 return $sts_on;
                   13470:20):             }
                   13471:20):         }
          .4(raebu 13472:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13473:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13474:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13475:20):         my $response=$ua->request($request);
          .3(raebu 13476:20):         if ($response->is_success) {
                   13477:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13478:20):             if ($has_sts eq '') {
                   13479:20):                 $sts_on = 0;
                   13480:20):             } else {
                   13481:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13482:20):                     my $maxage = $1;
                   13483:20):                     if ($maxage) {
                   13484:20):                         $sts_on = 1;
                   13485:20):                     } else {
                   13486:20):                         $sts_on = 0;
                   13487:20):                     }
                   13488:20):                 } else {
                   13489:20):                     $sts_on = 0;
                   13490:20):                 }
                   13491:20):             }
                   13492:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13493:20):         }
                   13494:20):     }
                   13495:20):     return;
                   13496:20): }
                   13497:20): 
          .14(raeb 13498:-21): sub get_requestor_ip {
                   13499:-21):     my ($r,$nolookup,$noproxy) = @_;
                   13500:-21):     my $from_ip;
                   13501:-21):     if (ref($r)) {
                   13502:-21):         $from_ip = $r->get_remote_host($nolookup);
                   13503:-21):     } else {
                   13504:-21):         $from_ip = $ENV{'REMOTE_ADDR'};
                   13505:-21):     }
                   13506:-21):     return $from_ip;
                   13507:-21): }
                   13508:-21): 
1.31      www      13509: # ------------------------------------------------------------- Declutters URLs
                   13510: 
                   13511: sub declutter {
                   13512:     my $thisfn=shift;
1.569     albertel 13513:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13514:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13515:         $thisfn=~s{^/home/httpd/html}{};
                   13516:     }
1.31      www      13517:     $thisfn=~s/^\///;
1.697     albertel 13518:     $thisfn=~s|^adm/wrapper/||;
                   13519:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13520:     $thisfn=~s/^res\///;
1.1172    bisitz   13521:     $thisfn=~s/^priv\///;
1.1032    raeburn  13522:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13523:         $thisfn=~s/\?.+$//;
                   13524:     }
1.268     www      13525:     return $thisfn;
                   13526: }
                   13527: 
                   13528: # ------------------------------------------------------------- Clutter up URLs
                   13529: 
                   13530: sub clutter {
                   13531:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13532:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13533: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13534:        $thisfn='/res'.$thisfn; 
                   13535:     }
1.1031    raeburn  13536:     if ($thisfn !~m|^/adm|) {
                   13537: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13538: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13539: 	} else {
                   13540: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13541: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13542: 	    if ($embstyle eq 'ssi'
                   13543: 		|| ($embstyle eq 'hdn')
                   13544: 		|| ($embstyle eq 'rat')
                   13545: 		|| ($embstyle eq 'prv')
                   13546: 		|| ($embstyle eq 'ign')) {
                   13547: 		#do nothing with these
                   13548: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13549: 		|| ($embstyle eq 'emb')
                   13550: 		|| ($embstyle eq 'wrp')) {
                   13551: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13552: 	    } elsif ($embstyle eq 'unk'
                   13553: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13554: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13555: 	    } else {
1.718     www      13556: #		&logthis("Got a blank emb style");
1.695     albertel 13557: 	    }
1.694     albertel 13558: 	}
1.1172.2.118.  .1(raebu 13559:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13560:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13561:     }
1.31      www      13562:     return $thisfn;
1.12      www      13563: }
                   13564: 
1.787     albertel 13565: sub clutter_with_no_wrapper {
                   13566:     my $uri = &clutter(shift);
                   13567:     if ($uri =~ m-^/adm/-) {
                   13568: 	$uri =~ s-^/adm/wrapper/-/-;
                   13569: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13570:     }
                   13571:     return $uri;
                   13572: }
                   13573: 
1.557     albertel 13574: sub freeze_escape {
                   13575:     my ($value)=@_;
                   13576:     if (ref($value)) {
                   13577: 	$value=&nfreeze($value);
                   13578: 	return '__FROZEN__'.&escape($value);
                   13579:     }
                   13580:     return &escape($value);
                   13581: }
                   13582: 
1.11      www      13583: 
1.557     albertel 13584: sub thaw_unescape {
                   13585:     my ($value)=@_;
                   13586:     if ($value =~ /^__FROZEN__/) {
                   13587: 	substr($value,0,10,undef);
                   13588: 	$value=&unescape($value);
                   13589: 	return &thaw($value);
                   13590:     }
                   13591:     return &unescape($value);
                   13592: }
                   13593: 
1.436     albertel 13594: sub correct_line_ends {
                   13595:     my ($result)=@_;
                   13596:     $$result =~s/\r\n/\n/mg;
                   13597:     $$result =~s/\r/\n/mg;
1.415     albertel 13598: }
1.1       albertel 13599: # ================================================================ Main Program
                   13600: 
1.184     www      13601: sub goodbye {
1.204     albertel 13602:    &logthis("Starting Shut down");
1.443     albertel 13603: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13604:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13605: #converted
1.599     albertel 13606: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13607:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13608: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13609: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13610: #1.1 only
1.870     albertel 13611: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13612: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13613: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13614: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13615:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13616:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13617:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13618:    &flushcourselogs();
                   13619:    &logthis("Shutting down");
                   13620: }
                   13621: 
1.852     albertel 13622: sub get_dns {
1.1172.2.17  raeburn  13623:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13624:     if (!$ignore_cache) {
                   13625: 	my ($content,$cached)=
                   13626: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13627: 	if ($cached) {
1.1172.2.17  raeburn  13628: 	    &$func($content,$hashref);
1.869     albertel 13629: 	    return;
                   13630: 	}
                   13631:     }
                   13632: 
                   13633:     my %alldns;
1.1172.2.96  raeburn  13634:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13635:         foreach my $dns (<$config>) {
                   13636: 	    next if ($dns !~ /^\^(\S*)/x);
                   13637:             my $line = $1;
                   13638:             my ($host,$protocol) = split(/:/,$line);
                   13639:             if ($protocol ne 'https') {
                   13640:                 $protocol = 'http';
                   13641:             }
                   13642: 	    $alldns{$host} = $protocol;
1.979     raeburn  13643:         }
1.1172.2.96  raeburn  13644:         close($config);
1.869     albertel 13645:     }
                   13646:     while (%alldns) {
1.1172.2.52  raeburn  13647: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13648: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13649:         $ua->timeout(30);
1.979     raeburn  13650: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13651: 	my $response=$ua->request($request);
1.979     raeburn  13652:         delete($alldns{$dns});
1.852     albertel 13653: 	next if ($response->is_error());
                   13654: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13655:         unless ($nocache) {
1.1172.2.23  raeburn  13656: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13657:         }
                   13658: 	&$func(\@content,$hashref);
1.869     albertel 13659: 	return;
1.852     albertel 13660:     }
1.871     albertel 13661:     my $which = (split('/',$url))[3];
                   13662:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13663:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13664:         my @content = <$config>;
                   13665:         &$func(\@content,$hashref);
                   13666:     }
1.1172.2.17  raeburn  13667:     return;
                   13668: }
                   13669: 
                   13670: # ------------------------------------------------------Get DNS checksums file
                   13671: sub parse_dns_checksums_tab {
                   13672:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13673:     my $lonhost = $perlvar{'lonHostID'};
                   13674:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13675:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13676:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13677:     my $webconfdir = '/etc/httpd/conf';
                   13678:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13679:         $webconfdir = '/etc/apache2';
                   13680:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13681:         if ($1 >= 10) {
                   13682:             $webconfdir = '/etc/apache2';
                   13683:         }
                   13684:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13685:         if ($1 >= 10.0) {
                   13686:             $webconfdir = '/etc/apache2';
                   13687:         }
                   13688:     }
1.1172.2.17  raeburn  13689:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13690:     my (%chksum,%revnum);
                   13691:     if (ref($lines) eq 'ARRAY') {
                   13692:         chomp(@{$lines});
1.1172.2.34  raeburn  13693:         my $version = shift(@{$lines});
                   13694:         if ($version eq $release) {
1.1172.2.17  raeburn  13695:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13696:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13697:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13698:                     if ($webconfdir eq '/etc/apache2') {
                   13699:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13700:                     }
                   13701:                 }
1.1172.2.34  raeburn  13702:                 $chksum{$file} = $shasum;
                   13703:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13704:             }
                   13705:             if (ref($hashref) eq 'HASH') {
                   13706:                 %{$hashref} = (
                   13707:                                 sums     => \%chksum,
                   13708:                                 versions => \%revnum,
                   13709:                               );
                   13710:             }
                   13711:         }
                   13712:     }
1.869     albertel 13713:     return;
1.852     albertel 13714: }
1.1172.2.17  raeburn  13715: 
                   13716: sub fetch_dns_checksums {
                   13717:     my %checksums;
1.1172.2.34  raeburn  13718:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13719:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13720:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13721:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13722:              \%checksums);
                   13723:     return \%checksums;
                   13724: }
                   13725: 
1.327     albertel 13726: # ------------------------------------------------------------ Read domain file
                   13727: {
1.852     albertel 13728:     my $loaded;
1.846     albertel 13729:     my %domain;
                   13730: 
1.852     albertel 13731:     sub parse_domain_tab {
                   13732: 	my ($lines) = @_;
                   13733: 	foreach my $line (@$lines) {
                   13734: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13735: 
1.846     albertel 13736: 	    chomp($line);
1.852     albertel 13737: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13738: 	    my %this_domain;
                   13739: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13740: 			       'lang_def', 'city', 'longi', 'lati',
                   13741: 			       'primary') {
                   13742: 		$this_domain{$field} = shift(@elements);
                   13743: 	    }
                   13744: 	    $domain{$name} = \%this_domain;
1.852     albertel 13745: 	}
                   13746:     }
1.864     albertel 13747: 
                   13748:     sub reset_domain_info {
                   13749: 	undef($loaded);
                   13750: 	undef(%domain);
                   13751:     }
                   13752: 
1.852     albertel 13753:     sub load_domain_tab {
1.1172.2.70  raeburn  13754: 	my ($ignore_cache,$nocache) = @_;
                   13755: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13756: 	my $fh;
1.1172.2.96  raeburn  13757: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13758: 	    my @lines = <$fh>;
                   13759: 	    &parse_domain_tab(\@lines);
1.448     albertel 13760: 	}
1.852     albertel 13761: 	close($fh);
                   13762: 	$loaded = 1;
1.327     albertel 13763:     }
1.846     albertel 13764: 
                   13765:     sub domain {
1.852     albertel 13766: 	&load_domain_tab() if (!$loaded);
                   13767: 
1.846     albertel 13768: 	my ($name,$what) = @_;
                   13769: 	return if ( !exists($domain{$name}) );
                   13770: 
                   13771: 	if (!$what) {
                   13772: 	    return $domain{$name}{'description'};
                   13773: 	}
                   13774: 	return $domain{$name}{$what};
                   13775:     }
1.974     raeburn  13776: 
                   13777:     sub domain_info {
                   13778:         &load_domain_tab() if (!$loaded);
                   13779:         return %domain;
                   13780:     }
                   13781: 
1.327     albertel 13782: }
                   13783: 
                   13784: 
1.1       albertel 13785: # ------------------------------------------------------------- Read hosts file
                   13786: {
1.838     albertel 13787:     my %hostname;
1.844     albertel 13788:     my %hostdom;
1.845     albertel 13789:     my %libserv;
1.852     albertel 13790:     my $loaded;
1.888     albertel 13791:     my %name_to_host;
1.1074    raeburn  13792:     my %internetdom;
1.1107    raeburn  13793:     my %LC_dns_serv;
1.852     albertel 13794: 
                   13795:     sub parse_hosts_tab {
                   13796: 	my ($file) = @_;
                   13797: 	foreach my $configline (@$file) {
                   13798: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13799:             chomp($configline);
                   13800: 	    if ($configline =~ /^\^/) {
                   13801:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13802:                     $LC_dns_serv{$1} = 1;
                   13803:                 }
                   13804:                 next;
                   13805:             }
1.1074    raeburn  13806: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13807: 	    $name=~s/\s//g;
                   13808: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13809:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13810:                     my $curr = $hostname{$id};
                   13811:                     my $skip;
                   13812:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13813:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13814:                             $skip = 1;
                   13815:                         } else {
                   13816:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13817:                         }
                   13818:                     }
                   13819:                     unless ($skip) {
                   13820:                         push(@{$name_to_host{$name}},$id);
                   13821:                     }
                   13822:                 } else {
                   13823:                     push(@{$name_to_host{$name}},$id);
                   13824:                 }
1.852     albertel 13825: 		$hostname{$id}=$name;
                   13826: 		$hostdom{$id}=$domain;
                   13827: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13828:                 if (defined($protocol)) {
                   13829:                     if ($protocol eq 'https') {
                   13830:                         $protocol{$id} = $protocol;
                   13831:                     } else {
                   13832:                         $protocol{$id} = 'http'; 
                   13833:                     }
1.968     raeburn  13834:                 } else {
1.969     raeburn  13835:                     $protocol{$id} = 'http';
1.968     raeburn  13836:                 }
1.1074    raeburn  13837:                 if (defined($intdom)) {
                   13838:                     $internetdom{$id} = $intdom;
                   13839:                 }
1.852     albertel 13840: 	    }
                   13841: 	}
                   13842:     }
1.864     albertel 13843:     
                   13844:     sub reset_hosts_info {
1.897     albertel 13845: 	&purge_remembered();
1.864     albertel 13846: 	&reset_domain_info();
                   13847: 	&reset_hosts_ip_info();
1.892     albertel 13848: 	undef(%name_to_host);
1.864     albertel 13849: 	undef(%hostname);
                   13850: 	undef(%hostdom);
                   13851: 	undef(%libserv);
                   13852: 	undef($loaded);
                   13853:     }
1.1       albertel 13854: 
1.852     albertel 13855:     sub load_hosts_tab {
1.1172.2.70  raeburn  13856: 	my ($ignore_cache,$nocache) = @_;
                   13857: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13858: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13859: 	my @config = <$config>;
                   13860: 	&parse_hosts_tab(\@config);
                   13861: 	close($config);
                   13862: 	$loaded=1;
1.1       albertel 13863:     }
1.852     albertel 13864: 
1.838     albertel 13865:     sub hostname {
1.852     albertel 13866: 	&load_hosts_tab() if (!$loaded);
                   13867: 
1.838     albertel 13868: 	my ($lonid) = @_;
                   13869: 	return $hostname{$lonid};
                   13870:     }
1.845     albertel 13871: 
1.838     albertel 13872:     sub all_hostnames {
1.852     albertel 13873: 	&load_hosts_tab() if (!$loaded);
                   13874: 
1.838     albertel 13875: 	return %hostname;
                   13876:     }
1.845     albertel 13877: 
1.888     albertel 13878:     sub all_names {
1.1172.2.70  raeburn  13879:         my ($ignore_cache,$nocache) = @_;
                   13880: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13881: 
                   13882: 	return %name_to_host;
                   13883:     }
                   13884: 
1.974     raeburn  13885:     sub all_host_domain {
                   13886:         &load_hosts_tab() if (!$loaded);
                   13887:         return %hostdom;
                   13888:     }
                   13889: 
1.845     albertel 13890:     sub is_library {
1.852     albertel 13891: 	&load_hosts_tab() if (!$loaded);
                   13892: 
1.845     albertel 13893: 	return exists($libserv{$_[0]});
                   13894:     }
                   13895: 
                   13896:     sub all_library {
1.852     albertel 13897: 	&load_hosts_tab() if (!$loaded);
                   13898: 
1.845     albertel 13899: 	return %libserv;
                   13900:     }
                   13901: 
1.1062    droeschl 13902:     sub unique_library {
                   13903: 	#2x reverse removes all hostnames that appear more than once
                   13904:         my %unique = reverse &all_library();
                   13905:         return reverse %unique;
                   13906:     }
                   13907: 
1.841     albertel 13908:     sub get_servers {
1.852     albertel 13909: 	&load_hosts_tab() if (!$loaded);
                   13910: 
1.841     albertel 13911: 	my ($domain,$type) = @_;
                   13912: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13913: 	                                          : %hostname;
                   13914: 	my %result;
1.842     albertel 13915: 	if (ref($domain) eq 'ARRAY') {
                   13916: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13917: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13918: 		    $result{$host} = $hostname;
                   13919: 		}
                   13920: 	    }
                   13921: 	} else {
                   13922: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13923: 		if ($hostdom{$host} eq $domain) {
                   13924: 		    $result{$host} = $hostname;
                   13925: 		}
1.841     albertel 13926: 	    }
                   13927: 	}
                   13928: 	return %result;
                   13929:     }
1.845     albertel 13930: 
1.1062    droeschl 13931:     sub get_unique_servers {
                   13932:         my %unique = reverse &get_servers(@_);
                   13933: 	return reverse %unique;
                   13934:     }
                   13935: 
1.844     albertel 13936:     sub host_domain {
1.852     albertel 13937: 	&load_hosts_tab() if (!$loaded);
                   13938: 
1.844     albertel 13939: 	my ($lonid) = @_;
                   13940: 	return $hostdom{$lonid};
                   13941:     }
                   13942: 
1.841     albertel 13943:     sub all_domains {
1.852     albertel 13944: 	&load_hosts_tab() if (!$loaded);
                   13945: 
1.841     albertel 13946: 	my %seen;
                   13947: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13948: 	return @uniq;
                   13949:     }
1.1074    raeburn  13950: 
                   13951:     sub internet_dom {
                   13952:         &load_hosts_tab() if (!$loaded);
                   13953: 
                   13954:         my ($lonid) = @_;
                   13955:         return $internetdom{$lonid};
                   13956:     }
1.1107    raeburn  13957: 
                   13958:     sub is_LC_dns {
                   13959:         &load_hosts_tab() if (!$loaded);
                   13960: 
                   13961:         my ($hostname) = @_;
                   13962:         return exists($LC_dns_serv{$hostname});
                   13963:     }
                   13964: 
1.1       albertel 13965: }
                   13966: 
1.847     albertel 13967: { 
                   13968:     my %iphost;
1.856     albertel 13969:     my %name_to_ip;
                   13970:     my %lonid_to_ip;
1.869     albertel 13971: 
1.847     albertel 13972:     sub get_hosts_from_ip {
                   13973: 	my ($ip) = @_;
                   13974: 	my %iphosts = &get_iphost();
                   13975: 	if (ref($iphosts{$ip})) {
                   13976: 	    return @{$iphosts{$ip}};
                   13977: 	}
                   13978: 	return;
1.839     albertel 13979:     }
1.864     albertel 13980:     
                   13981:     sub reset_hosts_ip_info {
                   13982: 	undef(%iphost);
                   13983: 	undef(%name_to_ip);
                   13984: 	undef(%lonid_to_ip);
                   13985:     }
1.856     albertel 13986: 
                   13987:     sub get_host_ip {
                   13988: 	my ($lonid) = @_;
                   13989: 	if (exists($lonid_to_ip{$lonid})) {
                   13990: 	    return $lonid_to_ip{$lonid};
                   13991: 	}
                   13992: 	my $name=&hostname($lonid);
                   13993:    	my $ip = gethostbyname($name);
                   13994: 	return if (!$ip || length($ip) ne 4);
                   13995: 	$ip=inet_ntoa($ip);
                   13996: 	$name_to_ip{$name}   = $ip;
                   13997: 	$lonid_to_ip{$lonid} = $ip;
                   13998: 	return $ip;
                   13999:     }
1.847     albertel 14000:     
                   14001:     sub get_iphost {
1.1172.2.70  raeburn  14002: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14003: 
1.869     albertel 14004: 	if (!$ignore_cache) {
                   14005: 	    if (%iphost) {
                   14006: 		return %iphost;
                   14007: 	    }
                   14008: 	    my ($ip_info,$cached)=
                   14009: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14010: 	    if ($cached) {
                   14011: 		%iphost      = %{$ip_info->[0]};
                   14012: 		%name_to_ip  = %{$ip_info->[1]};
                   14013: 		%lonid_to_ip = %{$ip_info->[2]};
                   14014: 		return %iphost;
                   14015: 	    }
                   14016: 	}
1.894     albertel 14017: 
                   14018: 	# get yesterday's info for fallback
                   14019: 	my %old_name_to_ip;
                   14020: 	my ($ip_info,$cached)=
                   14021: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14022: 	if ($cached) {
                   14023: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14024: 	}
                   14025: 
1.1172.2.70  raeburn  14026: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14027: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14028: 	    my $ip;
                   14029: 	    if (!exists($name_to_ip{$name})) {
                   14030: 		$ip = gethostbyname($name);
                   14031: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14032: 		    if (defined($old_name_to_ip{$name})) {
                   14033: 			$ip = $old_name_to_ip{$name};
                   14034: 			&logthis("Can't find $name defaulting to old $ip");
                   14035: 		    } else {
                   14036: 			&logthis("Name $name no IP found");
                   14037: 			next;
                   14038: 		    }
                   14039: 		} else {
                   14040: 		    $ip=inet_ntoa($ip);
1.847     albertel 14041: 		}
                   14042: 		$name_to_ip{$name} = $ip;
                   14043: 	    } else {
                   14044: 		$ip = $name_to_ip{$name};
1.653     albertel 14045: 	    }
1.888     albertel 14046: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14047: 		$lonid_to_ip{$id} = $ip;
                   14048: 	    }
                   14049: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14050: 	}
1.1172.2.70  raeburn  14051:         unless ($nocache) {
                   14052: 	    &do_cache_new('iphost','iphost',
                   14053: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14054: 		          48*60*60);
                   14055:         }
1.869     albertel 14056: 
1.847     albertel 14057: 	return %iphost;
1.598     albertel 14058:     }
                   14059: 
1.992     raeburn  14060:     #
                   14061:     #  Given a DNS returns the loncapa host name for that DNS 
                   14062:     # 
                   14063:     sub host_from_dns {
                   14064:         my ($dns) = @_;
                   14065:         my @hosts;
                   14066:         my $ip;
                   14067: 
1.993     raeburn  14068:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14069:             $ip = $name_to_ip{$dns};
                   14070:         }
                   14071:         if (!$ip) {
                   14072:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14073:             if (length($ip) == 4) { 
                   14074: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14075:             }
                   14076:         }
                   14077:         if ($ip) {
                   14078: 	    @hosts = get_hosts_from_ip($ip);
                   14079: 	    return $hosts[0];
                   14080:         }
                   14081:         return undef;
1.986     foxr     14082:     }
1.992     raeburn  14083: 
1.1074    raeburn  14084:     sub get_internet_names {
                   14085:         my ($lonid) = @_;
                   14086:         return if ($lonid eq '');
                   14087:         my ($idnref,$cached)=
                   14088:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14089:         if ($cached) {
                   14090:             return $idnref;
                   14091:         }
                   14092:         my $ip = &get_host_ip($lonid);
                   14093:         my @hosts = &get_hosts_from_ip($ip);
                   14094:         my %iphost = &get_iphost();
                   14095:         my (@idns,%seen);
                   14096:         foreach my $id (@hosts) {
                   14097:             my $dom = &host_domain($id);
                   14098:             my $prim_id = &domain($dom,'primary');
                   14099:             my $prim_ip = &get_host_ip($prim_id);
                   14100:             next if ($seen{$prim_ip});
                   14101:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14102:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14103:                     my $intdom = &internet_dom($id);
                   14104:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14105:                         push(@idns,$intdom);
                   14106:                     }
                   14107:                 }
                   14108:             }
                   14109:             $seen{$prim_ip} = 1;
                   14110:         }
1.1172.2.23  raeburn  14111:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14112:     }
                   14113: 
1.986     foxr     14114: }
                   14115: 
1.1079    raeburn  14116: sub all_loncaparevs {
1.1172.2.39  raeburn  14117:     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  14118: }
                   14119: 
1.1172.2.27  raeburn  14120: # ------------------------------------------------------- Read loncaparev table
                   14121: {
                   14122:     sub load_loncaparevs {
                   14123:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14124:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14125:                 while (my $configline=<$config>) {
                   14126:                     chomp($configline);
                   14127:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14128:                     $loncaparevs{$hostid}=$loncaparev;
                   14129:                 }
                   14130:                 close($config);
                   14131:             }
                   14132:         }
                   14133:     }
                   14134: }
                   14135: 
                   14136: # ----------------------------------------------------- Read serverhostID table
                   14137: {
                   14138:     sub load_serverhomeIDs {
                   14139:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14140:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14141:                 while (my $configline=<$config>) {
                   14142:                     chomp($configline);
                   14143:                     my ($name,$id)=split(/:/,$configline);
                   14144:                     $serverhomeIDs{$name}=$id;
                   14145:                 }
                   14146:                 close($config);
                   14147:             }
                   14148:         }
                   14149:     }
                   14150: }
                   14151: 
                   14152: 
1.862     albertel 14153: BEGIN {
                   14154: 
                   14155: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14156:     unless ($readit) {
                   14157: {
                   14158:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14159:     %perlvar = (%perlvar,%{$configvars});
                   14160: }
                   14161: 
                   14162: 
1.1       albertel 14163: # ------------------------------------------------------ Read spare server file
                   14164: {
1.1172.2.96  raeburn  14165:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14166: 
                   14167:     while (my $configline=<$config>) {
                   14168:        chomp($configline);
1.284     matthew  14169:        if ($configline) {
1.784     albertel 14170: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14171: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14172: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14173:        }
                   14174:     }
1.448     albertel 14175:     close($config);
1.1       albertel 14176: }
1.11      www      14177: # ------------------------------------------------------------ Read permissions
                   14178: {
1.1172.2.96  raeburn  14179:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14180: 
                   14181:     while (my $configline=<$config>) {
1.448     albertel 14182: 	chomp($configline);
                   14183: 	if ($configline) {
                   14184: 	    my ($role,$perm)=split(/ /,$configline);
                   14185: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14186: 	}
1.11      www      14187:     }
1.448     albertel 14188:     close($config);
1.11      www      14189: }
                   14190: 
                   14191: # -------------------------------------------- Read plain texts for permissions
                   14192: {
1.1172.2.96  raeburn  14193:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14194: 
                   14195:     while (my $configline=<$config>) {
1.448     albertel 14196: 	chomp($configline);
                   14197: 	if ($configline) {
1.742     raeburn  14198: 	    my ($short,@plain)=split(/:/,$configline);
                   14199:             %{$prp{$short}} = ();
                   14200: 	    if (@plain > 0) {
                   14201:                 $prp{$short}{'std'} = $plain[0];
                   14202:                 for (my $i=1; $i<@plain; $i++) {
                   14203:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14204:                 }
                   14205:             }
1.448     albertel 14206: 	}
1.135     www      14207:     }
1.448     albertel 14208:     close($config);
1.135     www      14209: }
                   14210: 
                   14211: # ---------------------------------------------------------- Read package table
                   14212: {
1.1172.2.96  raeburn  14213:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14214: 
                   14215:     while (my $configline=<$config>) {
1.483     albertel 14216: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14217: 	chomp($configline);
                   14218: 	my ($short,$plain)=split(/:/,$configline);
                   14219: 	my ($pack,$name)=split(/\&/,$short);
                   14220: 	if ($plain ne '') {
                   14221: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14222: 	    $packagetab{$short}=$plain; 
                   14223: 	}
1.11      www      14224:     }
1.448     albertel 14225:     close($config);
1.329     matthew  14226: }
                   14227: 
1.1172.2.27  raeburn  14228: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14229: 
1.1172.2.27  raeburn  14230: &load_loncaparevs();
                   14231: 
                   14232: # ------------------------------------------------------- Read serverhostID table
                   14233: 
                   14234: &load_serverhomeIDs();
1.1074    raeburn  14235: 
1.1172.2.27  raeburn  14236: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14237: {
                   14238:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14239:     if (-e $file) {
                   14240:         my $parser = HTML::LCParser->new($file);
                   14241:         while (my $token = $parser->get_token()) {
                   14242:             if ($token->[0] eq 'S') {
                   14243:                 my $item = $token->[1];
                   14244:                 my $name = $token->[2]{'name'};
                   14245:                 my $value = $token->[2]{'value'};
                   14246:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14247:                     my $release = $parser->get_text();
                   14248:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14249:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14250:                 }
                   14251:             }
                   14252:         }
                   14253:     }
1.1073    raeburn  14254: }
                   14255: 
1.1138    raeburn  14256: # ---------------------------------------------------------- Read managers table
                   14257: {
                   14258:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14259:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14260:             while (my $configline=<$config>) {
                   14261:                 chomp($configline);
                   14262:                 next if ($configline =~ /^\#/);
                   14263:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14264:                     $managerstab{$configline} = 1;
                   14265:                 }
                   14266:             }
                   14267:             close($config);
                   14268:         }
                   14269:     }
                   14270: }
                   14271: 
1.329     matthew  14272: # ------------- set up temporary directory
                   14273: {
1.1117    foxr     14274:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14275: 
1.11      www      14276: }
                   14277: 
1.1172.2.104  raeburn  14278: # ------------- set default texengine (domain default overrides this)
                   14279: {
                   14280:     $deftex = LONCAPA::texengine();
                   14281: }
                   14282: 
1.1172.2.114  raeburn  14283: # ------------- set default minimum length for passwords for internal auth users
                   14284: {
                   14285:     $passwdmin = LONCAPA::passwd_min();
                   14286: }
                   14287: 
1.794     albertel 14288: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14289: 				'compress_threshold'=> 20_000,
                   14290:  			        });
1.185     www      14291: 
1.281     www      14292: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14293: $dumpcount=0;
1.958     www      14294: $locknum=0;
1.22      www      14295: 
1.163     harris41 14296: &logtouch();
1.672     albertel 14297: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14298: $readit=1;
1.564     albertel 14299:     {
                   14300: 	use integer;
                   14301: 	my $test=(2**32)+1;
1.568     albertel 14302: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14303: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14304:     }
1.195     www      14305: }
1.1       albertel 14306: }
1.179     www      14307: 
1.1       albertel 14308: 1;
1.191     harris41 14309: __END__
                   14310: 
1.243     albertel 14311: =pod
                   14312: 
1.191     harris41 14313: =head1 NAME
                   14314: 
1.243     albertel 14315: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14316: 
                   14317: =head1 SYNOPSIS
                   14318: 
1.243     albertel 14319: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14320: 
                   14321:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14322: 
1.243     albertel 14323: Common parameters:
                   14324: 
                   14325: =over 4
                   14326: 
                   14327: =item *
                   14328: 
                   14329: $uname : an internal username (if $cname expecting a course Id specifically)
                   14330: 
                   14331: =item *
                   14332: 
                   14333: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14334: 
                   14335: =item *
                   14336: 
                   14337: $symb : a resource instance identifier
                   14338: 
                   14339: =item *
                   14340: 
                   14341: $namespace : the name of a .db file that contains the data needed or
                   14342: being set.
                   14343: 
                   14344: =back
                   14345: 
1.394     bowersj2 14346: =head1 OVERVIEW
1.191     harris41 14347: 
1.394     bowersj2 14348: lonnet provides subroutines which interact with the
                   14349: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14350: about classes, users, and resources.
1.243     albertel 14351: 
                   14352: For many of these objects you can also use this to store data about
                   14353: them or modify them in various ways.
1.191     harris41 14354: 
1.394     bowersj2 14355: =head2 Symbs
1.191     harris41 14356: 
1.394     bowersj2 14357: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14358: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14359: map, the resource number of the resource in the map, and the URL of
                   14360: the resource itself. The latter is somewhat redundant, but might help
                   14361: if maps change.
                   14362: 
                   14363: An example is
                   14364: 
                   14365:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14366: 
                   14367: The respective map entry is
                   14368: 
                   14369:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14370:   title="Problem 2">
                   14371:  </resource>
                   14372: 
                   14373: Symbs are used by the random number generator, as well as to store and
                   14374: restore data specific to a certain instance of for example a problem.
                   14375: 
                   14376: =head2 Storing And Retrieving Data
                   14377: 
                   14378: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14379: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14380: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14381: is is the non-critical message twin of cstore. These functions are for
                   14382: handlers to store a perl hash to a user's permanent data space in an
                   14383: easy manner, and to retrieve it again on another call. It is expected
                   14384: that a handler would use this once at the beginning to retrieve data,
                   14385: and then again once at the end to send only the new data back.
                   14386: 
                   14387: The data is stored in the user's data directory on the user's
                   14388: homeserver under the ID of the course.
                   14389: 
                   14390: The hash that is returned by restore will have all of the previous
                   14391: value for all of the elements of the hash.
                   14392: 
                   14393: Example:
                   14394: 
                   14395:  #creating a hash
                   14396:  my %hash;
                   14397:  $hash{'foo'}='bar';
                   14398: 
                   14399:  #storing it
                   14400:  &Apache::lonnet::cstore(\%hash);
                   14401: 
                   14402:  #changing a value
                   14403:  $hash{'foo'}='notbar';
                   14404: 
                   14405:  #adding a new value
                   14406:  $hash{'bar'}='foo';
                   14407:  &Apache::lonnet::cstore(\%hash);
                   14408: 
                   14409:  #retrieving the hash
                   14410:  my %history=&Apache::lonnet::restore();
                   14411: 
                   14412:  #print the hash
                   14413:  foreach my $key (sort(keys(%history))) {
                   14414:    print("\%history{$key} = $history{$key}");
                   14415:  }
                   14416: 
                   14417: Will print out:
1.191     harris41 14418: 
1.394     bowersj2 14419:  %history{1:foo} = bar
                   14420:  %history{1:keys} = foo:timestamp
                   14421:  %history{1:timestamp} = 990455579
                   14422:  %history{2:bar} = foo
                   14423:  %history{2:foo} = notbar
                   14424:  %history{2:keys} = foo:bar:timestamp
                   14425:  %history{2:timestamp} = 990455580
                   14426:  %history{bar} = foo
                   14427:  %history{foo} = notbar
                   14428:  %history{timestamp} = 990455580
                   14429:  %history{version} = 2
                   14430: 
                   14431: Note that the special hash entries C<keys>, C<version> and
                   14432: C<timestamp> were added to the hash. C<version> will be equal to the
                   14433: total number of versions of the data that have been stored. The
                   14434: C<timestamp> attribute will be the UNIX time the hash was
                   14435: stored. C<keys> is available in every historical section to list which
                   14436: keys were added or changed at a specific historical revision of a
                   14437: hash.
                   14438: 
                   14439: B<Warning>: do not store the hash that restore returns directly. This
                   14440: will cause a mess since it will restore the historical keys as if the
                   14441: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14442: 
1.394     bowersj2 14443: Calling convention:
1.191     harris41 14444: 
1.1172.2.27  raeburn  14445:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14446:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14447: 
1.394     bowersj2 14448: For more detailed information, see lonnet specific documentation.
1.191     harris41 14449: 
1.394     bowersj2 14450: =head1 RETURN MESSAGES
1.191     harris41 14451: 
1.394     bowersj2 14452: =over 4
1.191     harris41 14453: 
1.394     bowersj2 14454: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14455: 
1.394     bowersj2 14456: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14457: when the connection is brought back up
1.191     harris41 14458: 
1.394     bowersj2 14459: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14460: for later delivery
1.191     harris41 14461: 
1.967     bisitz   14462: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14463: 
1.394     bowersj2 14464: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14465: that was requested
1.191     harris41 14466: 
1.243     albertel 14467: =back
1.191     harris41 14468: 
1.243     albertel 14469: =head1 PUBLIC SUBROUTINES
1.191     harris41 14470: 
1.243     albertel 14471: =head2 Session Environment Functions
1.191     harris41 14472: 
1.243     albertel 14473: =over 4
1.191     harris41 14474: 
1.394     bowersj2 14475: =item * 
                   14476: X<appenv()>
1.949     raeburn  14477: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14478: the user envirnoment file, and will be restored for each access this
1.620     albertel 14479: user makes during this session, also modifies the %env for the current
1.949     raeburn  14480: process. Optional rolesarrayref - if defined contains a reference to an array
                   14481: of roles which are exempt from the restriction on modifying user.role entries 
                   14482: in the user's environment.db and in %env.    
1.191     harris41 14483: 
                   14484: =item *
1.394     bowersj2 14485: X<delenv()>
1.987     raeburn  14486: B<delenv($delthis,$regexp)>: removes all items from the session
                   14487: environment file that begin with $delthis. If the 
                   14488: optional second arg - $regexp - is true, $delthis is treated as a 
                   14489: regular expression, otherwise \Q$delthis\E is used. 
                   14490: The values are also deleted from the current processes %env.
1.191     harris41 14491: 
1.795     albertel 14492: =item * get_env_multiple($name) 
                   14493: 
                   14494: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14495: values may be defined and end up as an array ref.
                   14496: 
                   14497: returns an array of values
                   14498: 
1.243     albertel 14499: =back
                   14500: 
                   14501: =head2 User Information
1.191     harris41 14502: 
1.243     albertel 14503: =over 4
1.191     harris41 14504: 
                   14505: =item *
1.394     bowersj2 14506: X<queryauthenticate()>
                   14507: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14508: authentication scheme
                   14509: 
                   14510: =item *
1.394     bowersj2 14511: X<authenticate()>
1.1073    raeburn  14512: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14513: authenticate user from domain's lib servers (first use the current
                   14514: one). C<$upass> should be the users password.
1.1073    raeburn  14515: $checkdefauth is optional (value is 1 if a check should be made to
                   14516:    authenticate user using default authentication method, and allow
                   14517:    account creation if username does not have account in the domain).
                   14518: $clientcancheckhost is optional (value is 1 if checking whether the
                   14519:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14520: 
                   14521: =item *
1.394     bowersj2 14522: X<homeserver()>
                   14523: B<homeserver($uname,$udom)>: find the server which has
                   14524: the user's directory and files (there must be only one), this caches
                   14525: the answer, and also caches if there is a borken connection.
1.191     harris41 14526: 
                   14527: =item *
1.394     bowersj2 14528: X<idget()>
                   14529: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14530: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14531: username, and only 1 username per ID in a specific domain) (returns
                   14532: hash: id=>name,id=>name)
1.191     harris41 14533: 
                   14534: =item *
1.394     bowersj2 14535: X<idrget()>
                   14536: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14537: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14538: 
                   14539: =item *
1.394     bowersj2 14540: X<idput()>
                   14541: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14542: 
                   14543: =item *
1.394     bowersj2 14544: X<rolesinit()>
1.1169    droeschl 14545: B<rolesinit($udom,$username)>: get user privileges.
                   14546: returns user role, first access and timer interval hashes
1.243     albertel 14547: 
                   14548: =item *
1.1171    droeschl 14549: X<privileged()>
                   14550: B<privileged($username,$domain)>: returns a true if user has a
                   14551: privileged and active role (i.e. su or dc), false otherwise.
                   14552: 
                   14553: =item *
1.551     albertel 14554: X<getsection()>
                   14555: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14556: course $cname, return section name/number or '' for "not in course"
                   14557: and '-1' for "no section"
                   14558: 
                   14559: =item *
1.394     bowersj2 14560: X<userenvironment()>
                   14561: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14562: passed in @what from the requested user's environment, returns a hash
                   14563: 
1.858     raeburn  14564: =item * 
                   14565: X<userlog_query()>
1.859     albertel 14566: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14567: activity.log file. %filters defines filters applied when parsing the
                   14568: log file. These can be start or end timestamps, or the type of action
                   14569: - log to look for Login or Logout events, check for Checkin or
                   14570: Checkout, role for role selection. The response is in the form
                   14571: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14572: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14573: 
1.243     albertel 14574: =back
                   14575: 
                   14576: =head2 User Roles
                   14577: 
                   14578: =over 4
                   14579: 
                   14580: =item *
                   14581: 
1.1172.2.65  raeburn  14582: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14583: returns codes for allowed actions.
                   14584: 
                   14585: The first argument is required, all others are optional.
                   14586: 
                   14587: $priv is the privilege being checked.
                   14588: $uri contains additional information about what is being checked for access (e.g.,
                   14589: URL, course ID etc.).
                   14590: $symb is the unique resource instance identifier in a course; if needed,
                   14591: but not provided, it will be retrieved via a call to &symbread().
                   14592: $role is the role for which a priv is being checked (only used if priv is evb).
                   14593: $clientip is the user's IP address (only used when checking for access to portfolio
                   14594: files).
                   14595: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14596: prevents recursive calls to &allowed.
                   14597: 
1.243     albertel 14598:  F: full access
                   14599:  U,I,K: authentication modes (cxx only)
                   14600:  '': forbidden
                   14601:  1: user needs to choose course
                   14602:  2: browse allowed
1.766     albertel 14603:  A: passphrase authentication needed
1.1172.2.65  raeburn  14604:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14605: 
                   14606: =item *
                   14607: 
1.1172.2.13  raeburn  14608: constructaccess($url,$setpriv) : check for access to construction space URL
                   14609: 
                   14610: See if the owner domain and name in the URL match those in the
                   14611: expected environment.  If so, return three element list
                   14612: ($ownername,$ownerdomain,$ownerhome).
                   14613: 
                   14614: Otherwise return the null string.
                   14615: 
                   14616: If second argument 'setpriv' is true, it assigns the privileges,
                   14617: and returns the same three element list, unless the owner has
                   14618: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14619: in which case the null string is returned.
                   14620: 
                   14621: =item *
                   14622: 
1.1172.2.84  raeburn  14623: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14624: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14625: for system, domain, and course level. $uname and $udom are optional (current
                   14626: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14627: 
                   14628: =item *
                   14629: 
1.988     raeburn  14630: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14631: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14632: $type is Course (default) or Community.
1.988     raeburn  14633: If $forcedefault evaluates to true, text returned will be default 
                   14634: text for $type. Otherwise, if this is a course, the text returned 
                   14635: will be a custom name for the role (if defined in the course's 
                   14636: environment).  If no custom name is defined the default is returned.
                   14637:    
1.832     raeburn  14638: =item *
                   14639: 
1.1172.2.23  raeburn  14640: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14641: All arguments are optional. Returns a hash of a roles, either for
                   14642: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14643: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14644: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14645: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14646: For each key, value is set to colon-separated start and end times for
                   14647: the role.  If no username and domain are specified, will default to
1.934     raeburn  14648: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14649: of role statuses (active, future or previous), roles 
                   14650: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14651: to restrict the list of roles reported. If no array ref is 
                   14652: provided for types, will default to return only active roles.
1.834     albertel 14653: 
1.1172.2.13  raeburn  14654: =item *
                   14655: 
                   14656: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14657: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14658: 
                   14659: Additional optional arguments are: $type (if role checking is to be restricted
                   14660: to certain user status types -- previous (expired roles), active (currently
                   14661: available roles) or future (roles available in the future), and
                   14662: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14663: have active Domain Coordinator role in course's domain or in additional
                   14664: domains (specified in 'Domains to check for privileged users' in course
                   14665: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14666: 
                   14667: =item *
                   14668: 
                   14669: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14670: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14671: $possdomains and $possroles are optional array refs -- to domains to check and
                   14672: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14673: users' roles.db to check for a dc or su role in any domain. This can be
                   14674: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14675: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14676: this then allows &privileged_by_domain() to be used, which caches the identity
                   14677: of privileged users, eliminating the need for repeated calls to &dump().
                   14678: 
                   14679: =item *
                   14680: 
                   14681: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14682: where the outer hash keys are domains specified in the $possdomains array ref,
                   14683: next inner hash keys are privileged roles specified in the $roles array ref,
                   14684: and the innermost hash contains key = value pairs for username:domain = end:start
                   14685: for active or future "privileged" users with that role in that domain. To avoid
                   14686: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14687: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14688: 
1.243     albertel 14689: =back
                   14690: 
                   14691: =head2 User Modification
                   14692: 
                   14693: =over 4
                   14694: 
                   14695: =item *
                   14696: 
1.957     raeburn  14697: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14698: user for the level given by URL.  Optional start and end dates (leave empty
                   14699: string or zero for "no date")
1.191     harris41 14700: 
                   14701: =item *
                   14702: 
1.243     albertel 14703: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14704: change a users, password, possible return values are: ok,
                   14705: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14706: refused
1.191     harris41 14707: 
                   14708: =item *
                   14709: 
1.243     albertel 14710: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14711: 
                   14712: =item *
                   14713: 
1.1058    raeburn  14714: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14715:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14716: 
                   14717: will update user information (firstname,middlename,lastname,generation,
                   14718: permanentemail), and if forceid is true, student/employee ID also.
                   14719: A user's institutional affiliation(s) can also be updated.
                   14720: User information fields will not be overwritten with empty entries 
                   14721: unless the field is included in the $candelete array reference.
                   14722: This array is included when a single user is modified via "Manage Users",
                   14723: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14724: 
                   14725: =item *
                   14726: 
1.286     matthew  14727: modifystudent
                   14728: 
1.957     raeburn  14729: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14730: The course id is resolved based on the current user's environment.  
                   14731: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14732: associated with a course.
                   14733: 
1.297     matthew  14734: This call is essentially a wrapper for lonnet::modifyuser and
                   14735: lonnet::modify_student_enrollment
1.286     matthew  14736: 
                   14737: Inputs: 
                   14738: 
                   14739: =over 4
                   14740: 
1.957     raeburn  14741: =item B<$udom> Student's loncapa domain
1.286     matthew  14742: 
1.957     raeburn  14743: =item B<$uname> Student's loncapa login name
1.286     matthew  14744: 
1.964     bisitz   14745: =item B<$uid> Student/Employee ID
1.286     matthew  14746: 
1.957     raeburn  14747: =item B<$umode> Student's authentication mode
1.286     matthew  14748: 
1.957     raeburn  14749: =item B<$upass> Student's password
1.286     matthew  14750: 
1.957     raeburn  14751: =item B<$first> Student's first name
1.286     matthew  14752: 
1.957     raeburn  14753: =item B<$middle> Student's middle name
1.286     matthew  14754: 
1.957     raeburn  14755: =item B<$last> Student's last name
1.286     matthew  14756: 
1.957     raeburn  14757: =item B<$gene> Student's generation
1.286     matthew  14758: 
1.957     raeburn  14759: =item B<$usec> Student's section in course
1.286     matthew  14760: 
                   14761: =item B<$end> Unix time of the roles expiration
                   14762: 
                   14763: =item B<$start> Unix time of the roles start date
                   14764: 
                   14765: =item B<$forceid> If defined, allow $uid to be changed
                   14766: 
                   14767: =item B<$desiredhome> server to use as home server for student
                   14768: 
1.957     raeburn  14769: =item B<$email> Student's permanent e-mail address
                   14770: 
                   14771: =item B<$type> Type of enrollment (auto or manual)
                   14772: 
1.963     raeburn  14773: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14774: 
                   14775: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14776: 
1.963     raeburn  14777: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14778: 
1.963     raeburn  14779: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14780: 
1.1172.2.19  raeburn  14781: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14782: 
                   14783: =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  14784: 
1.286     matthew  14785: =back
1.297     matthew  14786: 
                   14787: =item *
                   14788: 
                   14789: modify_student_enrollment
                   14790: 
1.1172.2.31  raeburn  14791: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14792: 'role.request.course' must be defined for this function to proceed.
                   14793: 
                   14794: Inputs:
                   14795: 
                   14796: =over 4
                   14797: 
1.1172.2.31  raeburn  14798: =item $udom, student's domain
1.297     matthew  14799: 
1.1172.2.31  raeburn  14800: =item $uname, student's name
1.297     matthew  14801: 
1.1172.2.31  raeburn  14802: =item $uid, student's user id
1.297     matthew  14803: 
1.1172.2.31  raeburn  14804: =item $first, student's first name
1.297     matthew  14805: 
                   14806: =item $middle
                   14807: 
                   14808: =item $last
                   14809: 
                   14810: =item $gene
                   14811: 
                   14812: =item $usec
                   14813: 
                   14814: =item $end
                   14815: 
                   14816: =item $start
                   14817: 
1.957     raeburn  14818: =item $type
                   14819: 
                   14820: =item $locktype
                   14821: 
                   14822: =item $cid
                   14823: 
                   14824: =item $selfenroll
                   14825: 
                   14826: =item $context
                   14827: 
1.1172.2.19  raeburn  14828: =item $credits, number of credits student will earn from this class
                   14829: 
1.1172.2.76  raeburn  14830: =item $instsec, institutional course section code for student
                   14831: 
1.297     matthew  14832: =back
                   14833: 
1.191     harris41 14834: 
                   14835: =item *
                   14836: 
1.243     albertel 14837: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14838: custom role; give a custom role to a user for the level given by URL.  Specify
                   14839: name and domain of role author, and role name
1.191     harris41 14840: 
                   14841: =item *
                   14842: 
1.243     albertel 14843: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14844: 
                   14845: =item *
                   14846: 
1.243     albertel 14847: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14848: 
                   14849: =back
                   14850: 
                   14851: =head2 Course Infomation
                   14852: 
                   14853: =over 4
1.191     harris41 14854: 
                   14855: =item *
                   14856: 
1.1118    foxr     14857: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14858: specified course id, including all environment settings for the
                   14859: course, the description of the course will be in the hash under the
                   14860: key 'description'
1.191     harris41 14861: 
1.1118    foxr     14862: $options is an optional parameter that if supplied is a hash reference that controls
                   14863: what how this function works.  It has the following key/values:
                   14864: 
                   14865: =over 4
                   14866: 
                   14867: =item freshen_cache
                   14868: 
                   14869: If defined, and the environment cache for the course is valid, it is 
                   14870: returned in the returned hash.
                   14871: 
                   14872: =item one_time
                   14873: 
                   14874: If defined, the last cache time is set to _now_
                   14875: 
                   14876: =item user
                   14877: 
                   14878: If defined, the supplied username is used instead of the current user.
                   14879: 
                   14880: 
                   14881: =back
                   14882: 
1.191     harris41 14883: =item *
                   14884: 
1.624     albertel 14885: resdata($name,$domain,$type,@which) : request for current parameter
                   14886: setting for a specific $type, where $type is either 'course' or 'user',
                   14887: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14888: answers for 10 minutes.
1.243     albertel 14889: 
1.877     foxr     14890: =item *
                   14891: 
                   14892: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14893: data base, returning a hash that is keyed by the resource name and has
                   14894: values that are the resource value.  I believe that the timestamps and
                   14895: versions are also returned.
                   14896: 
1.1172.2.31  raeburn  14897: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14898: supplemental content area. This routine caches the number of files for
                   14899: 10 minutes.
                   14900: 
1.243     albertel 14901: =back
                   14902: 
                   14903: =head2 Course Modification
                   14904: 
                   14905: =over 4
1.191     harris41 14906: 
                   14907: =item *
                   14908: 
1.243     albertel 14909: writecoursepref($courseid,%prefs) : write preferences (environment
                   14910: database) for a course
1.191     harris41 14911: 
                   14912: =item *
                   14913: 
1.1011    raeburn  14914: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14915: 
                   14916: =item *
                   14917: 
1.1038    raeburn  14918: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14919: 
1.1167    droeschl 14920: =item *
                   14921: 
                   14922: is_course($courseid), is_course($cdom, $cnum)
                   14923: 
                   14924: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14925: two component version $cdom, $cnum. It checks if the specified course exists.
                   14926: 
                   14927: Returns:
                   14928:     undef if the course doesn't exist, otherwise
                   14929:     in scalar context the combined courseid.
                   14930:     in list context the two components of the course identifier, domain and 
                   14931:     courseid.    
                   14932: 
1.243     albertel 14933: =back
                   14934: 
1.1172.2.109  raeburn  14935: =head2 Bubblesheet Configuration
                   14936: 
                   14937: =over 4
                   14938: 
                   14939: =item *
                   14940: 
                   14941: get_scantron_config($which)
                   14942: 
                   14943: $which - the name of the configuration to parse from the file.
                   14944: 
                   14945: Parses and returns the bubblesheet configuration line selected as a
                   14946: hash of configuration file fields.
                   14947: 
                   14948: 
                   14949: Returns:
                   14950:     If the named configuration is not in the file, an empty
                   14951:     hash is returned.
                   14952: 
                   14953:     a hash with the fields
                   14954:       name         - internal name for the this configuration setup
                   14955:       description  - text to display to operator that describes this config
                   14956:       CODElocation - if 0 or the string 'none'
                   14957:                           - no CODE exists for this config
                   14958:                      if -1 || the string 'letter'
                   14959:                           - a CODE exists for this config and is
                   14960:                             a string of letters
                   14961:                      Unsupported value (but planned for future support)
                   14962:                           if a positive integer
                   14963:                                - The CODE exists as the first n items from
                   14964:                                  the question section of the form
                   14965:                           if the string 'number'
                   14966:                                - The CODE exists for this config and is
                   14967:                                  a string of numbers
                   14968:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14969:                      the CODE starts
                   14970:       CODElength  - length of the CODE
                   14971:       IDstart     - column where the student/employee ID starts
                   14972:       IDlength    - length of the student/employee ID info
                   14973:       Qstart      - column where the information from the bubbled
                   14974:                     'questions' start
                   14975:       Qlength     - number of columns comprising a single bubble line from
                   14976:                     the sheet. (usually either 1 or 10)
                   14977:       Qon         - either a single character representing the character used
                   14978:                     to signal a bubble was chosen in the positional setup, or
                   14979:                     the string 'letter' if the letter of the chosen bubble is
                   14980:                     in the final, or 'number' if a number representing the
                   14981:                     chosen bubble is in the file (1->A 0->J)
                   14982:       Qoff        - the character used to represent that a bubble was
                   14983:                     left blank
                   14984:       PaperID     - if the scanning process generates a unique number for each
                   14985:                     sheet scanned the column that this ID number starts in
                   14986:       PaperIDlength - number of columns that comprise the unique ID number
                   14987:                       for the sheet of paper
                   14988:       FirstName   - column that the first name starts in
                   14989:       FirstNameLength - number of columns that the first name spans
                   14990:       LastName    - column that the last name starts in
                   14991:       LastNameLength - number of columns that the last name spans
                   14992:       BubblesPerRow - number of bubbles available in each row used to
                   14993:                       bubble an answer. (If not specified, 10 assumed).
                   14994: 
                   14995: 
                   14996: =item *
                   14997: 
                   14998: get_scantronformat_file($cdom)
                   14999: 
                   15000: $cdom - the course's domain (optional); if not supplied, uses
                   15001: domain for current $env{'request.course.id'}.
                   15002: 
                   15003: Returns an array containing lines from the scantron format file for
                   15004: the domain of the course.
                   15005: 
                   15006: If a url for a custom.tab file is listed in domain's configuration.db,
                   15007: lines are from this file.
                   15008: 
                   15009: Otherwise, if a default.tab has been published in RES space by the
                   15010: domainconfig user, lines are from this file.
                   15011: 
                   15012: Otherwise, fall back to getting lines from the legacy file on the
                   15013: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15014: 
                   15015: =back
                   15016: 
1.243     albertel 15017: =head2 Resource Subroutines
                   15018: 
                   15019: =over 4
1.191     harris41 15020: 
                   15021: =item *
                   15022: 
1.243     albertel 15023: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15024: 
                   15025: =item *
                   15026: 
1.243     albertel 15027: repcopy($filename) : subscribes to the requested file, and attempts to
                   15028: replicate from the owning library server, Might return
1.607     raeburn  15029: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15030: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15031: resource. Expects the local filesystem pathname
                   15032: (/home/httpd/html/res/....)
                   15033: 
                   15034: =back
                   15035: 
                   15036: =head2 Resource Information
                   15037: 
                   15038: =over 4
1.191     harris41 15039: 
                   15040: =item *
                   15041: 
1.1172.2.28  raeburn  15042: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15043: and returns the value of a variety of different possible values,
                   15044: $varname should be a request string, and the other parameters can be
                   15045: used to specify who and what one is asking about. Ordinarily, $cid 
                   15046: does not need to be specified, as it is retrived from 
                   15047: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15048: within lonuserstate::loadmap() when initializing a course, before
                   15049: $env{'request.course.id'} has been set, so it needs to be provided
                   15050: in that one case.
1.243     albertel 15051: 
                   15052: Possible values for $varname are environment.lastname (or other item
                   15053: from the envirnment hash), user.name (or someother aspect about the
                   15054: user), resource.0.maxtries (or some other part and parameter of a
                   15055: resource)
1.204     albertel 15056: 
                   15057: =item *
                   15058: 
1.243     albertel 15059: directcondval($number) : get current value of a condition; reads from a state
                   15060: string
1.204     albertel 15061: 
                   15062: =item *
                   15063: 
1.243     albertel 15064: condval($condidx) : value of condition index based on state
1.204     albertel 15065: 
                   15066: =item *
                   15067: 
1.243     albertel 15068: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15069: resource's metadata, $what should be either a specific key, or either
                   15070: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15071: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15072: 
                   15073: this function automatically caches all requests
1.191     harris41 15074: 
                   15075: =item *
                   15076: 
1.243     albertel 15077: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15078: network of library servers; returns file handle of where SQL and regex results
                   15079: will be stored for query
1.191     harris41 15080: 
                   15081: =item *
                   15082: 
1.1172.2.66  raeburn  15083: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15084: return symbolic list entry (all arguments optional).
                   15085: 
                   15086: Args: filename is the filename (including path) for the file for which a symb
                   15087: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15088: to check access status if more than one resource was found in the bighash
                   15089: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15090: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15091: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15092: cause possible symbs to be checked to determine if they are subject to content
                   15093: blocking, if so they will not be included as possible symbs; possibles is a
                   15094: ref to a hash, which, as a side effect, will be populated with all possible
                   15095: symbs (content blocking not tested).
                   15096: 
1.243     albertel 15097: returns the data handle
1.191     harris41 15098: 
                   15099: =item *
                   15100: 
1.1172.2.17  raeburn  15101: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15102: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15103: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15104: on failure, user must be in a course, as it assumes the existence of
                   15105: the course initial hash, and uses $env('request.course.id'}.  The third
                   15106: arg is an optional reference to a scalar.  If this arg is passed in the
                   15107: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15108: encrypted; otherwise it will be null.
1.243     albertel 15109: 
1.191     harris41 15110: =item *
                   15111: 
1.243     albertel 15112: symbclean($symb) : removes versions numbers from a symb, returns the
                   15113: cleaned symb
1.191     harris41 15114: 
                   15115: =item *
                   15116: 
1.243     albertel 15117: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15118: course map, user must be in a course for it to work.
1.191     harris41 15119: 
                   15120: =item *
                   15121: 
1.243     albertel 15122: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15123: 
                   15124: =item *
                   15125: 
1.243     albertel 15126: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15127: a random seed, all arguments are optional, if they aren't sent it uses the
                   15128: environment to derive them. Note: if symb isn't sent and it can't get one
                   15129: from &symbread it will use the current time as its return value
1.191     harris41 15130: 
                   15131: =item *
                   15132: 
1.243     albertel 15133: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15134: unfakeable, receipt
1.191     harris41 15135: 
                   15136: =item *
                   15137: 
1.620     albertel 15138: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15139: 
                   15140: =item *
                   15141: 
1.243     albertel 15142: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15143: 
                   15144: =item *
                   15145: 
1.243     albertel 15146: 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 15147: 
                   15148: =item *
                   15149: 
1.243     albertel 15150: 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 15151: 
                   15152: =item *
                   15153: 
1.243     albertel 15154: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15155: 
                   15156: =item *
                   15157: 
1.243     albertel 15158: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15159: forcing spreadsheet to reevaluate the resource scores next time.
                   15160: 
1.1172.2.13  raeburn  15161: =item *
                   15162: 
                   15163: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15164: when viewing in course context.
                   15165: 
                   15166:  input: six args -- filename (decluttered), course number, course domain,
                   15167:                     url, symb (if registered) and group (if this is a
                   15168:                     group item -- e.g., bulletin board, group page etc.).
                   15169: 
                   15170:  output: array of five scalars --
                   15171:          $cfile -- url for file editing if editable on current server
                   15172:          $home -- homeserver of resource (i.e., for author if published,
                   15173:                                           or course if uploaded.).
                   15174:          $switchserver --  1 if server switch will be needed.
                   15175:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15176:          $forceview -- 1 if icon/link should be to go to view mode
                   15177: 
                   15178: =item *
                   15179: 
                   15180: is_course_upload($file,$cnum,$cdom)
                   15181: 
                   15182: Used in course context to determine if current file was uploaded to
                   15183: the course (i.e., would be found in /userfiles/docs on the course's
                   15184: homeserver.
                   15185: 
                   15186:   input: 3 args -- filename (decluttered), course number and course domain.
                   15187:   output: boolean -- 1 if file was uploaded.
                   15188: 
1.243     albertel 15189: =back
                   15190: 
                   15191: =head2 Storing/Retreiving Data
                   15192: 
                   15193: =over 4
1.191     harris41 15194: 
                   15195: =item *
                   15196: 
1.1172.2.64  raeburn  15197: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15198: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15199: the remaining args aren't required and if they aren't passed or are '' they will
                   15200: be derived from the env (with the exception of $laststore, which is an
                   15201: optional arg used when a user's submission is stored in grading).
                   15202: $laststore is $version=$timestamp, where $version is the most recent version
                   15203: number retrieved for the corresponding $symb in the $namespace db file, and
                   15204: $timestamp is the timestamp for that transaction (UNIX time).
                   15205: $laststore is currently only passed when cstore() is called by
                   15206: structuretags::finalize_storage().
1.191     harris41 15207: 
                   15208: =item *
                   15209: 
1.1172.2.64  raeburn  15210: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15211: but uses critical subroutine
1.191     harris41 15212: 
                   15213: =item *
                   15214: 
1.243     albertel 15215: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15216: all args are optional
1.191     harris41 15217: 
                   15218: =item *
                   15219: 
1.717     albertel 15220: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15221: dumps the complete (or key matching regexp) namespace into a hash
                   15222: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15223: normally &store()ed into
                   15224: 
                   15225: $range should be either an integer '100' (give me the first 100
                   15226:                                            matching records)
                   15227:               or be  two integers sperated by a - with no spaces
                   15228:                  '30-50' (give me the 30th through the 50th matching
                   15229:                           records)
                   15230: 
                   15231: 
                   15232: =item *
                   15233: 
1.1172.2.59  raeburn  15234: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15235: replaces a &store() version of data with a replacement set of data
                   15236: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15237: reference. If $tolog is true, the transaction is logged in the courselog
                   15238: with an action=PUTSTORE.
1.717     albertel 15239: 
                   15240: =item *
                   15241: 
1.243     albertel 15242: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15243: works very similar to store/cstore, but all data is stored in a
                   15244: temporary location and can be reset using tmpreset, $storehash should
                   15245: be a hash reference, returns nothing on success
1.191     harris41 15246: 
                   15247: =item *
                   15248: 
1.243     albertel 15249: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15250: similar to restore, but all data is stored in a temporary location and
                   15251: can be reset using tmpreset. Returns a hash of values on success,
                   15252: error string otherwise.
1.191     harris41 15253: 
                   15254: =item *
                   15255: 
1.243     albertel 15256: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15257: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15258: 
                   15259: =item *
                   15260: 
1.243     albertel 15261: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15262: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15263: 
                   15264: =item *
                   15265: 
1.243     albertel 15266: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15267: namesp ($udom and $uname are optional)
1.191     harris41 15268: 
                   15269: =item *
                   15270: 
1.702     albertel 15271: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15272: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15273: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15274: 
1.702     albertel 15275: $range should be either an integer '100' (give me the first 100
                   15276:                                            matching records)
                   15277:               or be  two integers sperated by a - with no spaces
                   15278:                  '30-50' (give me the 30th through the 50th matching
                   15279:                           records)
1.449     matthew  15280: =item *
                   15281: 
                   15282: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15283: $store can be a scalar, an array reference, or if the amount to be 
                   15284: incremented is > 1, a hash reference.
                   15285: 
                   15286: ($udom and $uname are optional)
1.191     harris41 15287: 
                   15288: =item *
                   15289: 
1.243     albertel 15290: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15291: ($udom and $uname are optional)
1.191     harris41 15292: 
                   15293: =item *
                   15294: 
1.243     albertel 15295: cput($namespace,$storehash,$udom,$uname) : critical put
                   15296: ($udom and $uname are optional)
1.191     harris41 15297: 
                   15298: =item *
                   15299: 
1.748     albertel 15300: newput($namespace,$storehash,$udom,$uname) :
                   15301: 
                   15302: Attempts to store the items in the $storehash, but only if they don't
                   15303: currently exist, if this succeeds you can be certain that you have 
                   15304: successfully created a new key value pair in the $namespace db.
                   15305: 
                   15306: 
                   15307: Args:
                   15308:  $namespace: name of database to store values to
                   15309:  $storehash: hashref to store to the db
                   15310:  $udom: (optional) domain of user containing the db
                   15311:  $uname: (optional) name of user caontaining the db
                   15312: 
                   15313: Returns:
                   15314:  'ok' -> succeeded in storing all keys of $storehash
                   15315:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15316:                         least <key> already existed in the db (other
                   15317:                         requested keys may also already exist)
1.967     bisitz   15318:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15319:  'con_lost' -> unable to contact request server
                   15320:  'refused' -> action was not allowed by remote machine
                   15321: 
                   15322: 
                   15323: =item *
                   15324: 
1.243     albertel 15325: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15326: reference filled in from namesp (encrypts the return communication)
                   15327: ($udom and $uname are optional)
1.191     harris41 15328: 
                   15329: =item *
                   15330: 
1.243     albertel 15331: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15332: critical subroutine
                   15333: 
1.806     raeburn  15334: =item *
                   15335: 
1.860     raeburn  15336: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15337: array reference filled in from namespace found in domain level on either
                   15338: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15339: 
                   15340: =item *
                   15341: 
1.860     raeburn  15342: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15343: domain level either on specified domain server ($uhome) or primary domain 
                   15344: server ($udom and $uhome are optional)
1.806     raeburn  15345: 
1.943     raeburn  15346: =item * 
                   15347: 
1.1172.2.35  raeburn  15348: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15349: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15350: the target domain.
                   15351: 
                   15352: May also include additional key => value pairs for the following groups:
                   15353: 
                   15354: =over
                   15355: 
                   15356: =item
                   15357: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15358: 
                   15359: =over
                   15360: 
                   15361: =item defaultquota, authorquota
                   15362: 
                   15363: =back
                   15364: 
                   15365: =item
                   15366: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15367: portfolio for users).
                   15368: 
                   15369: =over
                   15370: 
                   15371: =item
                   15372: aboutme, blog, webdav, portfolio
                   15373: 
                   15374: =back
                   15375: 
                   15376: =item
                   15377: requestcourses: ability to request courses, and how requests are processed.
                   15378: 
                   15379: =over
                   15380: 
                   15381: =item
1.1172.2.37  raeburn  15382: official, unofficial, community, textbook
1.1172.2.35  raeburn  15383: 
                   15384: =back
                   15385: 
                   15386: =item
                   15387: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15388: 
                   15389: =over
                   15390: 
                   15391: =item
1.1172.2.44  raeburn  15392: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15393: 
                   15394: =back
                   15395: 
                   15396: =item
                   15397: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15398: for course's uploaded content.
                   15399: 
                   15400: =over
                   15401: 
                   15402: =item
1.1172.2.68  raeburn  15403: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15404: communityquota, textbookquota
1.1172.2.35  raeburn  15405: 
                   15406: =back
                   15407: 
                   15408: =item
                   15409: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15410: on your servers.
                   15411: 
                   15412: =over
                   15413: 
                   15414: =item
                   15415: remotesessions, hostedsessions
                   15416: 
                   15417: =back
                   15418: 
                   15419: =back
                   15420: 
                   15421: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15422: utility to create a configuration.db file on a domain's primary library server
                   15423: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15424: -- corresponding values are authentication type (internal, krb4, krb5,
                   15425: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15426: will be available. Values are retrieved from cache (if current), unless the
                   15427: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15428: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15429: 
                   15430: Typical usage:
1.943     raeburn  15431: 
1.1172.2.35  raeburn  15432: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15433: 
1.243     albertel 15434: =back
                   15435: 
                   15436: =head2 Network Status Functions
                   15437: 
                   15438: =over 4
1.191     harris41 15439: 
                   15440: =item *
                   15441: 
1.1137    raeburn  15442: dirlist() : return directory list based on URI (first arg).
                   15443: 
                   15444: Inputs: 1 required, 5 optional.
                   15445: 
                   15446: =over
                   15447: 
                   15448: =item 
                   15449: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15450: 
                   15451: =item
                   15452: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15453: 
                   15454: =item
                   15455: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15456: 
                   15457: =item
                   15458: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15459: 
                   15460: =item
                   15461: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15462: 
                   15463: =item 
                   15464: $alternateRoot - path to prepend in place of path from $uri.
                   15465: 
                   15466: =back
                   15467: 
                   15468: Returns: Array of up to two items.
                   15469: 
                   15470: =over
                   15471: 
                   15472: a reference to an array of files/subdirectories
                   15473: 
                   15474: =over
                   15475: 
                   15476: Each element in the array of files/subdirectories is a & separated list of
                   15477: item name and the result of running stat on the item.  If dirlist was requested
                   15478: for a file instead of a directory, the item name will be ''. For a directory 
                   15479: listing, if the item is a metadata file, the element will end &N&M 
                   15480: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15481: default copyright set (1).  
                   15482: 
                   15483: =back
                   15484: 
                   15485: a scalar containing error condition (if encountered).
                   15486: 
                   15487: =over
                   15488: 
                   15489: =item 
                   15490: no_host (no homeserver identified for $username:$domain).
                   15491: 
                   15492: =item 
                   15493: no_such_host (server contacted for listing not identified as valid host).
                   15494: 
                   15495: =item 
                   15496: con_lost (connection to remote server failed).
                   15497: 
                   15498: =item 
                   15499: refused (invalid $username:$domain received on lond side).
                   15500: 
                   15501: =item 
                   15502: no_such_dir (directory at specified path on lond side does not exist). 
                   15503: 
                   15504: =item 
                   15505: empty (directory at specified path on lond side is empty).
                   15506: 
                   15507: =over
                   15508: 
                   15509: This is currently not encountered because the &ls3, &ls2, 
                   15510: &ls (_handler) routines on the lond side do not filter out
                   15511: . and .. from a directory listing. 
                   15512: 
                   15513: =back
                   15514: 
                   15515: =back
                   15516: 
                   15517: =back
1.191     harris41 15518: 
                   15519: =item *
                   15520: 
1.243     albertel 15521: spareserver() : find server with least workload from spare.tab
                   15522: 
1.986     foxr     15523: 
                   15524: =item *
                   15525: 
                   15526: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15527: if there is no corresponding loncapa host.
                   15528: 
1.243     albertel 15529: =back
                   15530: 
1.986     foxr     15531: 
1.243     albertel 15532: =head2 Apache Request
                   15533: 
                   15534: =over 4
1.191     harris41 15535: 
                   15536: =item *
                   15537: 
1.243     albertel 15538: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15539: localhost, posts hash
                   15540: 
                   15541: =back
                   15542: 
                   15543: =head2 Data to String to Data
                   15544: 
                   15545: =over 4
1.191     harris41 15546: 
                   15547: =item *
                   15548: 
1.243     albertel 15549: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15550: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15551: 
                   15552: =item *
                   15553: 
1.243     albertel 15554: hashref2str($hashref) : convert a hashref into a string complete with
                   15555: escaping and '=' and '&' separators, supports elements that are
                   15556: arrayrefs and hashrefs
1.191     harris41 15557: 
                   15558: =item *
                   15559: 
1.243     albertel 15560: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15561: with escaping and '&' separators, supports elements that are arrayrefs
                   15562: and hashrefs
1.191     harris41 15563: 
                   15564: =item *
                   15565: 
1.243     albertel 15566: str2hash($string) : convert string to hash using unescaping and
                   15567: splitting on '=' and '&', supports elements that are arrayrefs and
                   15568: hashrefs
1.191     harris41 15569: 
                   15570: =item *
                   15571: 
1.243     albertel 15572: str2array($string) : convert string to hash using unescaping and
                   15573: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15574: 
                   15575: =back
                   15576: 
                   15577: =head2 Logging Routines
                   15578: 
                   15579: 
                   15580: These routines allow one to make log messages in the lonnet.log and
                   15581: lonnet.perm logfiles.
1.191     harris41 15582: 
1.1119    foxr     15583: =over 4
                   15584: 
1.191     harris41 15585: =item *
                   15586: 
1.243     albertel 15587: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15588: 
                   15589: =item *
                   15590: 
1.243     albertel 15591: logthis() : append message to the normal lonnet.log file, it gets
                   15592: preiodically rolled over and deleted.
1.191     harris41 15593: 
                   15594: =item *
                   15595: 
1.243     albertel 15596: logperm() : append a permanent message to lonnet.perm.log, this log
                   15597: file never gets deleted by any automated portion of the system, only
                   15598: messages of critical importance should go in here.
                   15599: 
1.1119    foxr     15600: 
1.243     albertel 15601: =back
                   15602: 
                   15603: =head2 General File Helper Routines
                   15604: 
                   15605: =over 4
1.191     harris41 15606: 
                   15607: =item *
                   15608: 
1.481     raeburn  15609: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15610: (a) files in /uploaded
                   15611:   (i) If a local copy of the file exists - 
                   15612:       compares modification date of local copy with last-modified date for 
                   15613:       definitive version stored on home server for course. If local copy is 
                   15614:       stale, requests a new version from the home server and stores it. 
                   15615:       If the original has been removed from the home server, then local copy 
                   15616:       is unlinked.
                   15617:   (ii) If local copy does not exist -
                   15618:       requests the file from the home server and stores it. 
                   15619:   
                   15620:   If $caller is 'uploadrep':  
                   15621:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15622:     for request for files originally uploaded via DOCS. 
                   15623:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15624:   
                   15625:   Otherwise:
                   15626:      This indicates a call from the content generation phase of the request.
                   15627:      -  returns the entire contents of the file or -1.
                   15628:      
                   15629: (b) files in /res
                   15630:    - returns the entire contents of a file or -1; 
                   15631:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15632: 
1.712     albertel 15633: 
                   15634: =item *
                   15635: 
                   15636: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15637:                   reference
                   15638: 
                   15639: returns either a stat() list of data about the file or an empty list
                   15640: if the file doesn't exist or couldn't find out about it (connection
                   15641: problems or user unknown)
                   15642: 
1.191     harris41 15643: =item *
                   15644: 
1.243     albertel 15645: filelocation($dir,$file) : returns file system location of a file
                   15646: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15647: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15648: and a file of ../bob will become /a/bob)
1.191     harris41 15649: 
                   15650: =item *
                   15651: 
                   15652: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15653: filelocation except for hrefs
                   15654: 
                   15655: =item *
                   15656: 
1.1172.2.49  raeburn  15657: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15658: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15659: 
1.243     albertel 15660: =back
                   15661: 
1.608     albertel 15662: =head2 Usererfile file routines (/uploaded*)
                   15663: 
                   15664: =over 4
                   15665: 
                   15666: =item *
                   15667: 
                   15668: userfileupload(): main rotine for putting a file in a user or course's
                   15669:                   filespace, arguments are,
                   15670: 
1.620     albertel 15671:  formname - required - this is the name of the element in $env where the
1.608     albertel 15672:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15673:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15674:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15675:  context - if coursedoc, store the file in the course of the active role
                   15676:              of the current user; 
                   15677:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15678:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15679:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15680:          if undefined, it will be placed in "unknown"
                   15681: 
                   15682:  (This routine calls clean_filename() to remove any dangerous
                   15683:  characters from the filename, and then calls finuserfileupload() to
                   15684:  complete the transaction)
                   15685: 
                   15686:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15687:  and /adm/notfound.html if unsuccessful
                   15688: 
                   15689: =item *
                   15690: 
                   15691: clean_filename(): routine for cleaing a filename up for storage in
                   15692:                  userfile space, argument is:
                   15693: 
                   15694:  filename - proposed filename
                   15695: 
                   15696: returns: the new clean filename
                   15697: 
                   15698: =item *
                   15699: 
1.1090    raeburn  15700: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15701: userspace, probably shouldn't be called directly
                   15702: 
                   15703:   docuname: username or courseid of destination for the file
                   15704:   docudom: domain of user/course of destination for the file
                   15705:   formname: same as for userfileupload()
1.1090    raeburn  15706:   fname: filename (including subdirectories) for the file
                   15707:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15708:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15709:   allfiles: reference to hash used to store objects found by parser
                   15710:   codebase: reference to hash used for codebases of java objects found by parser
                   15711:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15712:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15713:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15714:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15715:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15716:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15717:   mimetype: reference to scalar to accommodate mime type determined
                   15718:             from File::MMagic if $parser = parse.
1.608     albertel 15719: 
                   15720:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15721:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15722:  was 'overwrite').
                   15723:  
1.608     albertel 15724: 
                   15725: =item *
                   15726: 
                   15727: renameuserfile(): renames an existing userfile to a new name
                   15728: 
                   15729:   Args:
                   15730:    docuname: username or courseid of destination for the file
                   15731:    docudom: domain of user/course of destination for the file
                   15732:    old: current file name (including any subdirs under userfiles)
                   15733:    new: desired file name (including any subdirs under userfiles)
                   15734: 
                   15735: =item *
                   15736: 
                   15737: mkdiruserfile(): creates a directory is a userfiles dir
                   15738: 
                   15739:   Args:
                   15740:    docuname: username or courseid of destination for the file
                   15741:    docudom: domain of user/course of destination for the file
                   15742:    dir: dir to create (including any subdirs under userfiles)
                   15743: 
                   15744: =item *
                   15745: 
                   15746: removeuserfile(): removes a file that exists in userfiles
                   15747: 
                   15748:   Args:
                   15749:    docuname: username or courseid of destination for the file
                   15750:    docudom: domain of user/course of destination for the file
                   15751:    fname: filname to delete (including any subdirs under userfiles)
                   15752: 
                   15753: =item *
                   15754: 
                   15755: removeuploadedurl(): convience function for removeuserfile()
                   15756: 
                   15757:   Args:
                   15758:    url:  a full /uploaded/... url to delete
                   15759: 
1.747     albertel 15760: =item * 
                   15761: 
                   15762: get_portfile_permissions():
                   15763:   Args:
                   15764:     domain: domain of user or course contain the portfolio files
                   15765:     user: name of user or num of course contain the portfolio files
                   15766:   Returns:
                   15767:     hashref of a dump of the proper file_permissions.db
                   15768:    
                   15769: 
                   15770: =item * 
                   15771: 
                   15772: get_access_controls():
                   15773: 
                   15774: Args:
                   15775:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15776:   group: (optional) the group you want the files associated with
                   15777:   file: (optional) the file you want access info on
                   15778: 
                   15779: Returns:
1.749     raeburn  15780:     a hash (keys are file names) of hashes containing
                   15781:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15782:         values are XML containing access control settings (see below) 
1.747     albertel 15783: 
                   15784: Internal notes:
                   15785: 
1.749     raeburn  15786:  access controls are stored in file_permissions.db as key=value pairs.
                   15787:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15788:         where scope -> public,guest,course,group,domains or users.
                   15789:               end -> UNIX time for end of access (0 -> no end date)
                   15790:               start -> UNIX time for start of access
                   15791: 
                   15792:     value -> XML description of access control
                   15793:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15794:             <start></start>
                   15795:             <end></end>
                   15796: 
                   15797:             <password></password>  for scope type = guest
                   15798: 
                   15799:             <domain></domain>     for scope type = course or group
                   15800:             <number></number>
                   15801:             <roles id="">
                   15802:              <role></role>
                   15803:              <access></access>
                   15804:              <section></section>
                   15805:              <group></group>
                   15806:             </roles>
                   15807: 
                   15808:             <dom></dom>         for scope type = domains
                   15809: 
                   15810:             <users>             for scope type = users
                   15811:              <user>
                   15812:               <uname></uname>
                   15813:               <udom></udom>
                   15814:              </user>
                   15815:             </users>
                   15816:            </scope> 
                   15817:               
                   15818:  Access data is also aggregated for each file in an additional key=value pair:
                   15819:  key -> path to file/file_name\0accesscontrol 
                   15820:  value -> reference to hash
                   15821:           hash contains key = value pairs
                   15822:           where key = uniqueID:scope_end_start
                   15823:                 value = UNIX time record was last updated
                   15824: 
                   15825:           Used to improve speed of look-ups of access controls for each file.  
                   15826:  
                   15827:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15828: 
1.1172.2.13  raeburn  15829: =item *
                   15830: 
1.749     raeburn  15831: modify_access_controls():
                   15832: 
                   15833: Modifies access controls for a portfolio file
                   15834: Args
                   15835: 1. file name
                   15836: 2. reference to hash of required changes,
                   15837: 3. domain
                   15838: 4. username
                   15839:   where domain,username are the domain of the portfolio owner 
                   15840:   (either a user or a course) 
                   15841: 
                   15842: Returns:
                   15843: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15844: 2. result of deletions ('ok' or 'error', with error message).
                   15845: 3. reference to hash of any new or updated access controls.
                   15846: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15847:    key = integer (inbound ID)
1.1172.2.13  raeburn  15848:    value = uniqueID
                   15849: 
                   15850: =item *
                   15851: 
                   15852: get_timebased_id():
                   15853: 
                   15854: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15855: course via the Course Editor (e.g., folders, composite pages,
                   15856: group bulletin boards).
                   15857: 
                   15858: Args: (first three required; six others optional)
                   15859: 
                   15860: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15861:    docssequence, or name of group
                   15862: 
                   15863: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15864:    e.g., num, boardids
                   15865: 
                   15866: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15867:    file will be named nohist_namespace.db
                   15868: 
                   15869: 4. cdom: domain of course; default is current course domain from %env
                   15870: 
                   15871: 5. cnum: course number; default is current course number from %env
                   15872: 
                   15873: 6. idtype: set to concat if an additional digit is to be appended to the
                   15874:    unix timestamp to form the suffix, if the plain timestamp is already
                   15875:    in use.  Default is to not do this, but simply increment the unix
                   15876:    timestamp by 1 until a unique key is obtained.
                   15877: 
                   15878: 7. who: holder of locking key; defaults to user:domain for user.
                   15879: 
                   15880: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15881:    retrying); default is 3.
                   15882: 
                   15883: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15884: 
                   15885: Returns:
                   15886: 
                   15887: 1. suffix obtained (numeric)
                   15888: 
                   15889: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15890: 
                   15891: 3. error: contains (localized) error message if an error occurred.
                   15892: 
1.747     albertel 15893: 
1.608     albertel 15894: =back
                   15895: 
1.243     albertel 15896: =head2 HTTP Helper Routines
                   15897: 
                   15898: =over 4
                   15899: 
1.191     harris41 15900: =item *
                   15901: 
                   15902: escape() : unpack non-word characters into CGI-compatible hex codes
                   15903: 
                   15904: =item *
                   15905: 
                   15906: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15907: 
1.243     albertel 15908: =back
                   15909: 
                   15910: =head1 PRIVATE SUBROUTINES
                   15911: 
                   15912: =head2 Underlying communication routines (Shouldn't call)
                   15913: 
                   15914: =over 4
                   15915: 
                   15916: =item *
                   15917: 
                   15918: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15919: 
                   15920: =item *
                   15921: 
                   15922: reply() : uses subreply to send a message to remote machine, logs all failures
                   15923: 
                   15924: =item *
                   15925: 
                   15926: critical() : passes a critical message to another server; if cannot
                   15927: get through then place message in connection buffer directory and
                   15928: returns con_delayed, if incapable of saving message, returns
                   15929: con_failed
                   15930: 
                   15931: =item *
                   15932: 
                   15933: reconlonc() : tries to reconnect lonc client processes.
                   15934: 
                   15935: =back
                   15936: 
                   15937: =head2 Resource Access Logging
                   15938: 
                   15939: =over 4
                   15940: 
                   15941: =item *
                   15942: 
                   15943: flushcourselogs() : flush (save) buffer logs and access logs
                   15944: 
                   15945: =item *
                   15946: 
                   15947: courselog($what) : save message for course in hash
                   15948: 
                   15949: =item *
                   15950: 
                   15951: courseacclog($what) : save message for course using &courselog().  Perform
                   15952: special processing for specific resource types (problems, exams, quizzes, etc).
                   15953: 
1.191     harris41 15954: =item *
                   15955: 
                   15956: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15957: as a PerlChildExitHandler
1.243     albertel 15958: 
                   15959: =back
                   15960: 
                   15961: =head2 Other
                   15962: 
                   15963: =over 4
                   15964: 
                   15965: =item *
                   15966: 
                   15967: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15968: 
                   15969: =back
                   15970: 
                   15971: =cut
1.877     foxr     15972: 

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