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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .11(raeb    4:-20): # $Id: lonnet.pm,v 1.1172.2.118.2.10 2020/10/25 23:51:53 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.9  raeburn   128:         my $logentry = {
                    129:                          $id => {
                    130:                                   'exe_uname' => $env{'user.name'},
                    131:                                   'exe_udom'  => $env{'user.domain'},
                    132:                                   'exe_time'  => $now,
                    133:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    134:                                   'delflag'   => $delflag,
                    135:                                   'logentry'  => $storehash,
                    136:                                   'uname'     => $uname,
                    137:                                   'udom'      => $udom,
                    138:                                 }
                    139:                        };
                    140:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       141:     }
                    142: }
1.1       albertel  143: 
1.163     harris41  144: sub logtouch {
                    145:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  146:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   147: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  148: 	close $fh;
                    149:     }
                    150:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    151:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    152: }
                    153: 
1.1       albertel  154: sub logthis {
                    155:     my $message=shift;
                    156:     my $execdir=$perlvar{'lonDaemons'};
                    157:     my $now=time;
                    158:     my $local=localtime($now);
1.1172.2.96  raeburn   159:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      160: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    161: 	print $fh $logstring;
1.448     albertel  162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
                    167: sub logperm {
                    168:     my $message=shift;
                    169:     my $execdir=$perlvar{'lonDaemons'};
                    170:     my $now=time;
                    171:     my $local=localtime($now);
1.1172.2.96  raeburn   172:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  173: 	print $fh "$now:$message:$local\n";
                    174: 	close($fh);
                    175:     }
1.1       albertel  176:     return 1;
                    177: }
                    178: 
1.850     albertel  179: sub create_connection {
1.853     albertel  180:     my ($hostname,$lonid) = @_;
1.851     albertel  181:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  182: 				     Type    => SOCK_STREAM,
                    183: 				     Timeout => 10);
                    184:     return 0 if (!$client);
1.890     albertel  185:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  186:     my $result = <$client>;
                    187:     chomp($result);
                    188:     return 1 if ($result eq 'done');
                    189:     return 0;
                    190: }
                    191: 
1.983     raeburn   192: sub get_server_timezone {
                    193:     my ($cnum,$cdom) = @_;
                    194:     my $home=&homeserver($cnum,$cdom);
                    195:     if ($home ne 'no_host') {
                    196:         my $cachetime = 24*3600;
                    197:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    198:         if (defined($cached)) {
                    199:             return $timezone;
                    200:         } else {
                    201:             my $timezone = &reply('servertimezone',$home);
                    202:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    203:         }
                    204:     }
                    205: }
1.850     albertel  206: 
1.1106    raeburn   207: sub get_server_distarch {
                    208:     my ($lonhost,$ignore_cache) = @_;
                    209:     if (defined($lonhost)) {
                    210:         if (!defined(&hostname($lonhost))) {
                    211:             return;
                    212:         }
                    213:         my $cachetime = 12*3600;
                    214:         if (!$ignore_cache) {
                    215:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    216:             if (defined($cached)) {
                    217:                 return $distarch;
                    218:             }
                    219:         }
                    220:         my $rep = &reply('serverdistarch',$lonhost);
                    221:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    222:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    223:                 $rep eq '') {
                    224:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    225:         }
                    226:     }
                    227:     return;
                    228: }
                    229: 
1.993     raeburn   230: sub get_server_loncaparev {
1.1073    raeburn   231:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   232:     if (defined($lonhost)) {
                    233:         if (!defined(&hostname($lonhost))) {
                    234:             undef($lonhost);
                    235:         }
                    236:     }
                    237:     if (!defined($lonhost)) {
                    238:         if (defined(&domain($dom,'primary'))) {
                    239:             $lonhost=&domain($dom,'primary');
                    240:             if ($lonhost eq 'no_host') {
                    241:                 undef($lonhost);
                    242:             }
                    243:         }
                    244:     }
                    245:     if (defined($lonhost)) {
1.1073    raeburn   246:         my $cachetime = 12*3600;
                    247:         if (!$ignore_cache) {
                    248:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    249:             if (defined($cached)) {
                    250:                 return $loncaparev;
                    251:             }
                    252:         }
                    253:         my ($answer,$loncaparev);
                    254:         my @ids=&current_machine_ids();
                    255:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    256:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   257:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   258:                 $loncaparev = $1;
                    259:             }
                    260:         } else {
                    261:             $answer = &reply('serverloncaparev',$lonhost);
                    262:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    263:                 if ($caller eq 'loncron') {
                    264:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   265:                     $ua->timeout(4);
1.1172.2.118.  .3(raebu  266:20):                     my $hostname = &hostname($lonhost);
1.1073    raeburn   267:                     my $protocol = $protocol{$lonhost};
                    268:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu  269:20):                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   270:                     my $request=new HTTP::Request('GET',$url);
                    271:                     my $response=$ua->request($request);
                    272:                     unless ($response->is_error()) {
                    273:                         my $content = $response->content;
1.1081    raeburn   274:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   275:                             $loncaparev = $1;
                    276:                         }
                    277:                     }
                    278:                 } else {
                    279:                     $loncaparev = $loncaparevs{$lonhost};
                    280:                 }
1.1081    raeburn   281:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   282:                 $loncaparev = $1;
                    283:             }
1.993     raeburn   284:         }
1.1073    raeburn   285:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   286:     }
                    287: }
                    288: 
1.1074    raeburn   289: sub get_server_homeID {
                    290:     my ($hostname,$ignore_cache,$caller) = @_;
                    291:     unless ($ignore_cache) {
                    292:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    293:         if (defined($cached)) {
                    294:             return $serverhomeID;
                    295:         }
                    296:     }
                    297:     my $cachetime = 12*3600;
                    298:     my $serverhomeID;
                    299:     if ($caller eq 'loncron') { 
                    300:         my @machine_ids = &machine_ids($hostname);
                    301:         foreach my $id (@machine_ids) {
                    302:             my $response = &reply('serverhomeID',$id);
                    303:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    304:                 $serverhomeID = $response;
                    305:                 last;
                    306:             }
                    307:         }
                    308:         if ($serverhomeID eq '') {
                    309:             $serverhomeID = $machine_ids[-1];
                    310:         }
                    311:     } else {
                    312:         $serverhomeID = $serverhomeIDs{$hostname};
                    313:     }
                    314:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    315: }
                    316: 
1.1121    raeburn   317: sub get_remote_globals {
                    318:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   319:     my ($result,%returnhash,%whatneeded);
                    320:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   321:         foreach my $what (sort(keys(%{$whathash}))) {
                    322:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   323:             my ($response,$cached);
1.1121    raeburn   324:             unless ($ignore_cache) {
1.1125    raeburn   325:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   326:             }
                    327:             if (defined($cached)) {
1.1125    raeburn   328:                 $returnhash{$what} = $response;
1.1121    raeburn   329:             } else {
1.1125    raeburn   330:                 $whatneeded{$what} = 1;
1.1121    raeburn   331:             }
                    332:         }
1.1125    raeburn   333:         if (keys(%whatneeded) == 0) {
                    334:             $result = 'ok';
                    335:         } else {
1.1121    raeburn   336:             my $requested = &freeze_escape(\%whatneeded);
                    337:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   338:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    339:                 ($rep eq 'unknown_cmd')) {
                    340:                 $result = $rep;
                    341:             } else {
                    342:                 $result = 'ok';
1.1121    raeburn   343:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   344:                 foreach my $item (@pairs) {
                    345:                     my ($key,$value)=split(/=/,$item,2);
                    346:                     my $what = &unescape($key);
                    347:                     my $hashid = $lonhost.'-'.$what;
                    348:                     $returnhash{$what}=&thaw_unescape($value);
                    349:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   350:                 }
                    351:             }
                    352:         }
                    353:     }
1.1125    raeburn   354:     return ($result,\%returnhash);
1.1121    raeburn   355: }
                    356: 
1.1124    raeburn   357: sub remote_devalidate_cache {
1.1172.2.35  raeburn   358:     my ($lonhost,$cachekeys) = @_;
                    359:     my $items;
                    360:     return unless (ref($cachekeys) eq 'ARRAY');
                    361:     my $cachestr = join('&',@{$cachekeys});
                    362:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   363: }
                    364: 
1.1       albertel  365: # -------------------------------------------------- Non-critical communication
                    366: sub subreply {
                    367:     my ($cmd,$server)=@_;
1.838     albertel  368:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      369:     #
                    370:     #  With loncnew process trimming, there's a timing hole between lonc server
                    371:     #  process exit and the master server picking up the listen on the AF_UNIX
                    372:     #  socket.  In that time interval, a lock file will exist:
                    373: 
                    374:     my $lockfile=$peerfile.".lock";
                    375:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   376: 	sleep(0.1);
1.549     foxr      377:     }
                    378:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      379:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      380:     #
1.550     foxr      381:     #   We'll give the connection a few tries before abandoning it.  If
                    382:     #   connection is not possible, we'll con_lost back to the client.
                    383:     #   
                    384:     my $client;
                    385:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    386: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    387: 				      Type    => SOCK_STREAM,
                    388: 				      Timeout => 10);
1.869     albertel  389: 	if ($client) {
1.550     foxr      390: 	    last;		# Connected!
1.850     albertel  391: 	} else {
1.853     albertel  392: 	    &create_connection(&hostname($server),$server);
1.550     foxr      393: 	}
1.1172.2.79  raeburn   394:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      395:     }
                    396:     my $answer;
                    397:     if ($client) {
1.704     albertel  398: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      399: 	$answer=<$client>;
                    400: 	if (!$answer) { $answer="con_lost"; }
                    401: 	chomp($answer);
                    402:     } else {
                    403: 	$answer = 'con_lost';	# Failed connection.
                    404:     }
1.1       albertel  405:     return $answer;
                    406: }
                    407: 
                    408: sub reply {
                    409:     my ($cmd,$server)=@_;
1.838     albertel  410:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  411:     my $answer=subreply($cmd,$server);
1.65      www       412:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   413:         my $logged = $cmd;
                    414:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    415:             my $subcmd = $1;
                    416:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    417:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    418:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    419:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    420:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    421:                     splice(@rest,2,1,'Hidden');
                    422:                 } elsif ($subcmd eq 'passwd') {
                    423:                     splice(@rest,2,2,('Hidden','Hidden'));
                    424:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    425:                          ($subcmd eq 'autoexportgrades')) {
                    426:                     splice(@rest,3,1,'Hidden');
                    427:                 }
                    428:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    429:             }
                    430:         }
                    431:         &logthis("<font color=\"blue\">WARNING:".
                    432:                  " $logged to $server returned $answer</font>");
1.12      www       433:     }
1.1       albertel  434:     return $answer;
                    435: }
                    436: 
                    437: # ----------------------------------------------------------- Send USR1 to lonc
                    438: 
                    439: sub reconlonc {
1.891     albertel  440:     my ($lonid) = @_;
                    441:     if ($lonid) {
1.1172.2.72  raeburn   442:         my $hostname = &hostname($lonid);
1.891     albertel  443: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    444: 	if ($hostname && -e $peerfile) {
                    445: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    446: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    447: 					     Type    => SOCK_STREAM,
                    448: 					     Timeout => 10);
                    449: 	    if ($client) {
                    450: 		print $client ("reset_retries\n");
                    451: 		my $answer=<$client>;
                    452: 		#reset just this one.
                    453: 	    }
                    454: 	}
                    455: 	return;
                    456:     }
                    457: 
1.836     www       458:     &logthis("Trying to reconnect lonc");
1.1       albertel  459:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   460:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  461: 	my $loncpid=<$fh>;
                    462:         chomp($loncpid);
                    463:         if (kill 0 => $loncpid) {
                    464: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    465:             kill USR1 => $loncpid;
                    466:             sleep 1;
1.836     www       467:          } else {
1.12      www       468: 	    &logthis(
1.672     albertel  469:                "<font color=\"blue\">WARNING:".
1.12      www       470:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  471:         }
                    472:     } else {
1.836     www       473: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  474:     }
                    475: }
                    476: 
                    477: # ------------------------------------------------------ Critical communication
1.12      www       478: 
1.1       albertel  479: sub critical {
                    480:     my ($cmd,$server)=@_;
1.838     albertel  481:     unless (&hostname($server)) {
1.672     albertel  482:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       483:                " Critical message to unknown server ($server)</font>");
                    484:         return 'no_such_host';
                    485:     }
1.1       albertel  486:     my $answer=reply($cmd,$server);
                    487:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   488: 	&reconlonc($server);
1.589     albertel  489: 	my $answer=reply($cmd,$server);
1.1       albertel  490:         if ($answer eq 'con_lost') {
                    491:             my $now=time;
                    492:             my $middlename=$cmd;
1.5       www       493:             $middlename=substr($middlename,0,16);
1.1       albertel  494:             $middlename=~s/\W//g;
                    495:             my $dfilename=
1.305     www       496:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    497:             $dumpcount++;
1.1       albertel  498:             {
1.448     albertel  499: 		my $dfh;
1.1172.2.96  raeburn   500: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  501: 		    print $dfh "$cmd\n"; 
                    502: 		    close($dfh);
                    503: 		}
1.1       albertel  504:             }
1.1172.2.79  raeburn   505:             sleep 1;
1.1       albertel  506:             my $wcmd='';
                    507:             {
1.448     albertel  508: 		my $dfh;
1.1172.2.96  raeburn   509: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  510: 		    $wcmd=<$dfh>; 
                    511: 		    close($dfh);
                    512: 		}
1.1       albertel  513:             }
                    514:             chomp($wcmd);
1.7       www       515:             if ($wcmd eq $cmd) {
1.672     albertel  516: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       517:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  518:                 &logperm("D:$server:$cmd");
                    519: 	        return 'con_delayed';
                    520:             } else {
1.672     albertel  521:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       522:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  523:                 &logperm("F:$server:$cmd");
                    524:                 return 'con_failed';
                    525:             }
                    526:         }
                    527:     }
                    528:     return $answer;
1.405     albertel  529: }
                    530: 
1.755     albertel  531: # ------------------------------------------- check if return value is an error
                    532: 
                    533: sub error {
                    534:     my ($result) = @_;
1.756     albertel  535:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  536: 	if ($2 == 2) { return undef; }
                    537: 	return $1;
                    538:     }
                    539:     return undef;
                    540: }
                    541: 
1.783     albertel  542: sub convert_and_load_session_env {
                    543:     my ($lonidsdir,$handle)=@_;
                    544:     my @profile;
                    545:     {
1.917     albertel  546: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    547: 	if (!$opened) {
1.915     albertel  548: 	    return 0;
                    549: 	}
1.783     albertel  550: 	flock($idf,LOCK_SH);
                    551: 	@profile=<$idf>;
                    552: 	close($idf);
                    553:     }
                    554:     my %temp_env;
                    555:     foreach my $line (@profile) {
1.786     albertel  556: 	if ($line !~ m/=/) {
                    557: 	    return 0;
                    558: 	}
1.783     albertel  559: 	chomp($line);
                    560: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    561: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    562:     }
                    563:     unlink("$lonidsdir/$handle.id");
                    564:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    565: 	    0640)) {
                    566: 	%disk_env = %temp_env;
                    567: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    568: 	untie(%disk_env);
                    569:     }
1.786     albertel  570:     return 1;
1.783     albertel  571: }
                    572: 
1.374     www       573: # ------------------------------------------- Transfer profile into environment
1.780     albertel  574: my $env_loaded;
                    575: sub transfer_profile_to_env {
1.788     albertel  576:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    577:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       578: 
1.720     albertel  579:     if (!defined($lonidsdir)) {
                    580: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    581:     }
                    582:     if (!defined($handle)) {
                    583:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    584:     }
                    585: 
1.786     albertel  586:     my $convert;
                    587:     {
1.917     albertel  588:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    589: 	if (!$opened) {
1.915     albertel  590: 	    return;
                    591: 	}
1.786     albertel  592: 	flock($idf,LOCK_SH);
                    593: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    594: 		&GDBM_READER(),0640)) {
                    595: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    596: 	    untie(%disk_env);
                    597: 	} else {
                    598: 	    $convert = 1;
                    599: 	}
                    600:     }
                    601:     if ($convert) {
                    602: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    603: 	    &logthis("Failed to load session, or convert session.");
                    604: 	}
1.374     www       605:     }
1.783     albertel  606: 
1.786     albertel  607:     my %remove;
1.783     albertel  608:     while ( my $envname = each(%env) ) {
1.433     matthew   609:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    610:             if ($time < time-300) {
1.783     albertel  611:                 $remove{$key}++;
1.433     matthew   612:             }
                    613:         }
                    614:     }
1.783     albertel  615: 
1.619     albertel  616:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  617:     $env_loaded=1;
1.783     albertel  618:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   619:         &delenv($expired_key);
1.374     www       620:     }
1.1       albertel  621: }
                    622: 
1.916     albertel  623: # ---------------------------------------------------- Check for valid session 
                    624: sub check_for_valid_session {
1.1172.2.96  raeburn   625:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  626:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   627:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   628:     if ($name eq 'lonDAV') {
                    629:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    630:     } else {
                    631:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   632:         if ($name eq '') {
                    633:             $name = 'lonID';
                    634:         }
                    635:     }
                    636:     if ($name eq 'lonID') {
                    637:         $secure = 'lonSID';
                    638:         $linkname = 'lonLinkID';
                    639:         $pubname = 'lonPubID';
                    640:         if (exists($cookies{$secure})) {
                    641:             $lonid=$cookies{$secure};
                    642:         } elsif (exists($cookies{$name})) {
                    643:             $lonid=$cookies{$name};
                    644:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    645:             $lonid=$cookies{$linkname};
                    646:         } elsif (exists($cookies{$pubname})) {
                    647:             $lonid=$cookies{$pubname};
                    648:         }
                    649:     } else {
                    650:         $lonid=$cookies{$name};
                    651:     }
                    652:     return undef if (!$lonid);
                    653: 
                    654:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    655:     if (-l "$lonidsdir/$handle.id") {
                    656:         my $link = readlink("$lonidsdir/$handle.id");
                    657:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    658:             $handle = $1;
                    659:         }
1.1155    raeburn   660:     }
1.1172.2.96  raeburn   661:     if (!-e "$lonidsdir/$handle.id") {
                    662:         if ((ref($domref)) && ($name eq 'lonID') &&
                    663:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    664:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    665:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    666:                 $$domref = $possudom;
                    667:             }
                    668:         }
                    669:         return undef;
                    670:     }
1.916     albertel  671: 
1.917     albertel  672:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    673:     return undef if (!$opened);
1.916     albertel  674: 
                    675:     flock($idf,LOCK_SH);
                    676:     my %disk_env;
                    677:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    678: 	    &GDBM_READER(),0640)) {
                    679: 	return undef;	
                    680:     }
                    681: 
                    682:     if (!defined($disk_env{'user.name'})
                    683: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   684:         untie(%disk_env);
1.916     albertel  685: 	return undef;
                    686:     }
1.1172.2.18  raeburn   687: 
1.1172.2.36  raeburn   688:     if (ref($userhashref) eq 'HASH') {
                    689:         $userhashref->{'name'} = $disk_env{'user.name'};
                    690:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   691:     }
1.1172.2.107  raeburn   692:     untie(%disk_env);
1.1172.2.18  raeburn   693: 
1.916     albertel  694:     return $handle;
                    695: }
                    696: 
1.830     albertel  697: sub timed_flock {
                    698:     my ($file,$lock_type) = @_;
                    699:     my $failed=0;
                    700:     eval {
                    701: 	local $SIG{__DIE__}='DEFAULT';
                    702: 	local $SIG{ALRM}=sub {
                    703: 	    $failed=1;
                    704: 	    die("failed lock");
                    705: 	};
                    706: 	alarm(13);
                    707: 	flock($file,$lock_type);
                    708: 	alarm(0);
                    709:     };
                    710:     if ($failed) {
                    711: 	return undef;
                    712:     } else {
                    713: 	return 1;
                    714:     }
                    715: }
                    716: 
1.1172.2.107  raeburn   717: sub get_sessionfile_vars {
                    718:     my ($handle,$lonidsdir,$storearr) = @_;
                    719:     my %returnhash;
                    720:     unless (ref($storearr) eq 'ARRAY') {
                    721:         return %returnhash;
                    722:     }
                    723:     if (-l "$lonidsdir/$handle.id") {
                    724:         my $link = readlink("$lonidsdir/$handle.id");
                    725:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    726:             $handle = $1;
                    727:         }
                    728:     }
                    729:     if ((-e "$lonidsdir/$handle.id") &&
                    730:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    731:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    732:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    733:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    734:                 flock($idf,LOCK_SH);
                    735:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    736:                         &GDBM_READER(),0640)) {
                    737:                     foreach my $item (@{$storearr}) {
                    738:                         $returnhash{$item} = $disk_env{$item};
                    739:                     }
                    740:                     untie(%disk_env);
                    741:                 }
                    742:             }
                    743:         }
                    744:     }
                    745:     return %returnhash;
                    746: }
                    747: 
1.5       www       748: # ---------------------------------------------------------- Append Environment
                    749: 
                    750: sub appenv {
1.949     raeburn   751:     my ($newenv,$roles) = @_;
                    752:     if (ref($newenv) eq 'HASH') {
                    753:         foreach my $key (keys(%{$newenv})) {
                    754:             my $refused = 0;
                    755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    756:                 $refused = 1;
                    757:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    760:                         $refused = 0;
                    761:                     }
                    762:                 }
                    763:             }
                    764:             if ($refused) {
                    765:                 &logthis("<font color=\"blue\">WARNING: ".
                    766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    767:                          .'</font>');
                    768: 	        delete($newenv->{$key});
                    769:             } else {
                    770:                 $env{$key}=$newenv->{$key};
                    771:             }
                    772:         }
1.1172.2.96  raeburn   773:         my $lonids = $perlvar{'lonIDsDir'};
                    774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    776:             if ($opened
                    777: 	        && &timed_flock($env_file,LOCK_EX)
                    778: 	        &&
                    779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    781: 	        while (my ($key,$value) = each(%{$newenv})) {
                    782: 	            $disk_env{$key} = $value;
                    783: 	        }
                    784: 	        untie(%disk_env);
                    785:             }
1.35      www       786:         }
1.191     harris41  787:     }
1.56      www       788:     return 'ok';
                    789: }
                    790: # ----------------------------------------------------- Delete from Environment
                    791: 
                    792: sub delenv {
1.1104    raeburn   793:     my ($delthis,$regexp,$roles) = @_;
                    794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    795:         my $refused = 1;
                    796:         if (ref($roles) eq 'ARRAY') {
                    797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    798:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    799:                 $refused = 0;
                    800:             }
                    801:         }
                    802:         if ($refused) {
                    803:             &logthis("<font color=\"blue\">WARNING: ".
                    804:                      "Attempt to delete from environment ".$delthis);
                    805:             return 'error';
                    806:         }
1.56      www       807:     }
1.917     albertel  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    809:     if ($opened
1.915     albertel  810: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  811: 	&&
                    812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  814: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   815: 	    if ($regexp) {
                    816:                 if ($key=~/^$delthis/) {
                    817:                     delete($env{$key});
                    818:                     delete($disk_env{$key});
                    819:                 } 
                    820:             } else {
                    821:                 if ($key=~/^\Q$delthis\E/) {
                    822: 		    delete($env{$key});
                    823: 		    delete($disk_env{$key});
                    824: 	        }
                    825:             }
1.448     albertel  826: 	}
1.783     albertel  827: 	untie(%disk_env);
1.5       www       828:     }
                    829:     return 'ok';
1.369     albertel  830: }
                    831: 
1.790     albertel  832: sub get_env_multiple {
                    833:     my ($name) = @_;
                    834:     my @values;
                    835:     if (defined($env{$name})) {
                    836:         # exists is it an array
                    837:         if (ref($env{$name})) {
                    838:             @values=@{ $env{$name} };
                    839:         } else {
                    840:             $values[0]=$env{$name};
                    841:         }
                    842:     }
                    843:     return(@values);
                    844: }
                    845: 
1.958     www       846: # ------------------------------------------------------------------- Locking
                    847: 
                    848: sub set_lock {
                    849:     my ($text)=@_;
                    850:     $locknum++;
                    851:     my $id=$$.'-'.$locknum;
                    852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    853:              'session.lock.'.$id => $text});
                    854:     return $id;
                    855: }
                    856: 
                    857: sub get_locks {
                    858:     my $num=0;
                    859:     my %texts=();
                    860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    861:        if ($lock=~/\w/) {
                    862:           $num++;
                    863:           $texts{$lock}=$env{'session.lock.'.$lock};
                    864:        }
                    865:    }
                    866:    return ($num,%texts);
                    867: }
                    868: 
                    869: sub remove_lock {
                    870:     my ($id)=@_;
                    871:     my $newlocks='';
                    872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    873:        if (($lock=~/\w/) && ($lock ne $id)) {
                    874:           $newlocks.=','.$lock;
                    875:        }
                    876:     }
                    877:     &appenv({'session.locks' => $newlocks});
                    878:     &delenv('session.lock.'.$id);
                    879: }
                    880: 
                    881: sub remove_all_locks {
                    882:     my $activelocks=$env{'session.locks'};
                    883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    884:        if ($lock=~/\w/) {
                    885:           &remove_lock($lock);
                    886:        }
                    887:     }
                    888: }
                    889: 
                    890: 
1.369     albertel  891: # ------------------------------------------ Find out current server userload
                    892: sub userload {
                    893:     my $numusers=0;
                    894:     {
                    895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    896: 	my $filename;
                    897: 	my $curtime=time;
                    898: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  899: 	    next if ($filename eq '.' || $filename eq '..');
                    900: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   901:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  902: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  903: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  904: 	}
                    905: 	closedir(LONIDS);
                    906:     }
                    907:     my $userloadpercent=0;
                    908:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    909:     if ($maxuserload) {
1.371     albertel  910: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  911:     }
1.372     albertel  912:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  913:     return $userloadpercent;
1.283     www       914: }
                    915: 
1.1       albertel  916: # ------------------------------ Find server with least workload from spare.tab
1.11      www       917: 
1.1       albertel  918: sub spareserver {
1.1083    raeburn   919:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  920:     my $spare_server;
1.370     albertel  921:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  922:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    923:                                                      :  $userloadpercent;
1.1083    raeburn   924:     my ($uint_dom,$remotesessions);
                    925:     if (($udom ne '') && (&domain($udom) ne '')) {
                    926:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    927:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    928:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    929:         $remotesessions = $udomdefaults{'remotesessions'};
                    930:     }
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   935:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    936:                                              $try_server));
1.1123    raeburn   937: 	        ($spare_server, $lowest_load) =
                    938: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    939:             }
1.1083    raeburn   940:         }
1.784     albertel  941: 
1.1123    raeburn   942:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    943: 
                    944:         if (!$found_server) {
                    945:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    946: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   947:                     next unless (&spare_can_host($udom,$uint_dom,
                    948:                                                  $remotesessions,$try_server));
1.1123    raeburn   949: 	            ($spare_server, $lowest_load) =
                    950: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    951:                 }
                    952: 	    }
                    953:         }
1.784     albertel  954:     }
                    955: 
                    956:     if (!$want_server_name) {
1.1001    raeburn   957:         if (defined($spare_server)) {
                    958:             my $hostname = &hostname($spare_server);
1.1083    raeburn   959:             if (defined($hostname)) {
1.1172.2.118.  .3(raebu  960:20):                 my $protocol = 'http';
                    961:20):                 if ($protocol{$spare_server} eq 'https') {
                    962:20):                     $protocol = $protocol{$spare_server};
                    963:20):                 }
1.1001    raeburn   964: 	        $spare_server = $protocol.'://'.$hostname;
                    965:             }
                    966:         }
1.784     albertel  967:     }
                    968:     return $spare_server;
                    969: }
                    970: 
                    971: sub compare_server_load {
1.1172.2.41  raeburn   972:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    973: 
                    974:     if ($required) {
                    975:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    976:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    977:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    978:         if (($major eq '' && $minor eq '') ||
                    979:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    980:             return ($spare_server,$lowest_load);
                    981:         }
                    982:     }
1.784     albertel  983: 
                    984:     my $loadans     = &reply('load',    $try_server);
                    985:     my $userloadans = &reply('userload',$try_server);
                    986: 
                    987:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   988: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  989:     }
                    990: 
                    991:     my $load;
                    992:     if ($loadans =~ /\d/) {
                    993: 	if ($userloadans =~ /\d/) {
                    994: 	    #both are numbers, pick the bigger one
                    995: 	    $load = ($loadans > $userloadans) ? $loadans 
                    996: 		                              : $userloadans;
1.411     albertel  997: 	} else {
1.784     albertel  998: 	    $load = $loadans;
1.411     albertel  999: 	}
1.784     albertel 1000:     } else {
                   1001: 	$load = $userloadans;
                   1002:     }
                   1003: 
                   1004:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1005: 	$spare_server = $try_server;
                   1006: 	$lowest_load  = $load;
1.370     albertel 1007:     }
1.784     albertel 1008:     return ($spare_server,$lowest_load);
1.202     matthew  1009: }
1.914     albertel 1010: 
                   1011: # --------------------------- ask offload servers if user already has a session
                   1012: sub find_existing_session {
                   1013:     my ($udom,$uname) = @_;
1.1123    raeburn  1014:     my $spareshash = &this_host_spares($udom);
                   1015:     if (ref($spareshash) eq 'HASH') {
                   1016:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1017:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1018:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1019:             }
                   1020:         }
                   1021:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1022:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1023:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1024:             }
                   1025:         }
1.914     albertel 1026:     }
                   1027:     return;
                   1028: }
                   1029: 
1.1172.2.107  raeburn  1030: # check if user's browser sent load balancer cookie and server still has session
                   1031: # and is not overloaded.
                   1032: sub check_for_balancer_cookie {
                   1033:     my ($r,$update_mtime) = @_;
                   1034:     my ($otherserver,$cookie);
                   1035:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1036:     if (exists($cookies{'balanceID'})) {
                   1037:         my $balid = $cookies{'balanceID'};
                   1038:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1039:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1040:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1041:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1042:                 my ($possudom,$possuname) = ($1,$2);
                   1043:                 my $has_session = 0;
                   1044:                 if ((&domain($possudom) ne '') &&
                   1045:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1046:                     my $try_server;
                   1047:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1048:                     if ($opened) {
                   1049:                         flock($idf,LOCK_SH);
                   1050:                         while (my $line = <$idf>) {
                   1051:                             chomp($line);
                   1052:                             if (&hostname($line) ne '') {
                   1053:                                 $try_server = $line;
                   1054:                                 last;
                   1055:                             }
                   1056:                         }
                   1057:                         close($idf);
                   1058:                         if (($try_server) &&
                   1059:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1060:                             my $lowest_load = 30000;
                   1061:                             ($otherserver,$lowest_load) =
                   1062:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1063:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1064:                                 $has_session = 1;
                   1065:                             } else {
                   1066:                                 undef($otherserver);
                   1067:                             }
                   1068:                         }
                   1069:                     }
                   1070:                 }
                   1071:                 if ($has_session) {
                   1072:                     if ($update_mtime) {
                   1073:                         my $atime = my $mtime = time;
                   1074:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1075:                     }
                   1076:                 } else {
                   1077:                     unlink("$balancedir/$cookie.id");
                   1078:                 }
                   1079:             }
                   1080:         }
                   1081:     }
                   1082:     return ($otherserver,$cookie);
                   1083: }
                   1084: 
1.1172.2.118.  .11(raeb 1085:-20): sub updatebalcookie {
                   1086:-20):     my ($cookie,$balancer,$lastentry)=@_;
                   1087:-20):     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1088:-20):         my ($udom,$uname) = ($1,$2);
                   1089:-20):         my $uprimary_id = &domain($udom,'primary');
                   1090:-20):         my $uintdom = &internet_dom($uprimary_id);
                   1091:-20):         my $intdom = &internet_dom($balancer);
                   1092:-20):         my $serverhomedom = &host_domain($balancer);
                   1093:-20):         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1094:-20):             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1095:-20):         }
                   1096:-20):     }
                   1097:-20):     return;
                   1098:-20): }
                   1099:-20): 
1.1172.2.107  raeburn  1100: sub delbalcookie {
                   1101:     my ($cookie,$balancer) =@_;
                   1102:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1103:         my ($udom,$uname) = ($1,$2);
                   1104:         my $uprimary_id = &domain($udom,'primary');
                   1105:         my $uintdom = &internet_dom($uprimary_id);
                   1106:         my $intdom = &internet_dom($balancer);
                   1107:         my $serverhomedom = &host_domain($balancer);
                   1108:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.118.  .11(raeb 1109:-20):             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1110:         }
                   1111:     }
                   1112: }
                   1113: 
1.914     albertel 1114: # -------------------------------- ask if server already has a session for user
                   1115: sub has_user_session {
                   1116:     my ($lonid,$udom,$uname) = @_;
                   1117:     my $result = &reply(join(':','userhassession',
                   1118: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1119:     return 1 if ($result eq 'ok');
                   1120: 
                   1121:     return 0;
                   1122: }
                   1123: 
1.1076    raeburn  1124: # --------- determine least loaded server in a user's domain which allows login
                   1125: 
                   1126: sub choose_server {
1.1172.2.47  raeburn  1127:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1128:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1129:     my %servers = &get_servers($udom);
1.1076    raeburn  1130:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1131:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1132:     if ($skiploadbal) {
                   1133:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1134:         unless (defined($cached)) {
                   1135:             my $cachetime = 60*60*24;
                   1136:             my %domconfig =
                   1137:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1138:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1139:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1140:                                            $cachetime);
                   1141:             }
                   1142:         }
                   1143:     }
1.1076    raeburn  1144:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1145:         my $loginvia;
1.1172.2.47  raeburn  1146:         if ($skiploadbal) {
                   1147:             if (ref($balancers) eq 'HASH') {
                   1148:                 next if (exists($balancers->{$lonhost}));
                   1149:             }
                   1150:         }
1.1115    raeburn  1151:         if ($checkloginvia) {
                   1152:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1153:             if ($loginvia) {
                   1154:                 my ($server,$path) = split(/:/,$loginvia);
                   1155:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1156:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1157:                 if ($login_host eq $server) {
                   1158:                     $portal_path = $path;
1.1151    raeburn  1159:                     $isredirect = 1;
1.1116    raeburn  1160:                 }
                   1161:             } else {
                   1162:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1163:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1164:                 if ($login_host eq $lonhost) {
                   1165:                     $portal_path = '';
1.1151    raeburn  1166:                     $isredirect = ''; 
1.1116    raeburn  1167:                 }
                   1168:             }
                   1169:         } else {
1.1076    raeburn  1170:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1171:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1172:         }
                   1173:     }
                   1174:     if ($login_host ne '') {
1.1116    raeburn  1175:         $hostname = &hostname($login_host);
1.1076    raeburn  1176:     }
1.1172.2.88  raeburn  1177:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1178: }
                   1179: 
1.1172.2.118.  .5(raebu 1180:20): sub get_course_sessions {
                   1181:20):     my ($cnum,$cdom,$lastactivity) = @_;
                   1182:20):     my %servers = &internet_dom_servers($cdom);
                   1183:20):     my %returnhash;
                   1184:20):     foreach my $server (sort(keys(%servers))) {
                   1185:20):         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1186:20):         my @pairs=split(/\&/,$rep);
                   1187:20):         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1188:20):             foreach my $item (@pairs) {
                   1189:20):                 my ($key,$value)=split(/=/,$item,2);
                   1190:20):                 $key = &unescape($key);
                   1191:20):                 next if ($key =~ /^error: 2 /);
                   1192:20):                 if (exists($returnhash{$key})) {
                   1193:20):                     next if ($value < $returnhash{$key});
                   1194:20):                 }
                   1195:20):                 $returnhash{$key}=$value;
                   1196:20):             }
                   1197:20):         }
                   1198:20):     }
                   1199:20):     return %returnhash;
                   1200:20): }
                   1201:20): 
1.202     matthew  1202: # --------------------------------------------- Try to change a user's password
                   1203: 
                   1204: sub changepass {
1.799     raeburn  1205:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1206:     $currentpass = &escape($currentpass);
                   1207:     $newpass     = &escape($newpass);
1.1030    raeburn  1208:     my $lonhost = $perlvar{'lonHostID'};
                   1209:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1210: 		       $server);
                   1211:     if (! $answer) {
                   1212: 	&logthis("No reply on password change request to $server ".
                   1213: 		 "by $uname in domain $udom.");
                   1214:     } elsif ($answer =~ "^ok") {
                   1215:         &logthis("$uname in $udom successfully changed their password ".
                   1216: 		 "on $server.");
                   1217:     } elsif ($answer =~ "^pwchange_failure") {
                   1218: 	&logthis("$uname in $udom was unable to change their password ".
                   1219: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1220: 		 "or pwchange");
                   1221:     } elsif ($answer =~ "^non_authorized") {
                   1222:         &logthis("$uname in $udom did not get their password correct when ".
                   1223: 		 "attempting to change it on $server.");
                   1224:     } elsif ($answer =~ "^auth_mode_error") {
                   1225:         &logthis("$uname in $udom attempted to change their password despite ".
                   1226: 		 "not being locally or internally authenticated on $server.");
                   1227:     } elsif ($answer =~ "^unknown_user") {
                   1228:         &logthis("$uname in $udom attempted to change their password ".
                   1229: 		 "on $server but were unable to because $server is not ".
                   1230: 		 "their home server.");
                   1231:     } elsif ($answer =~ "^refused") {
                   1232: 	&logthis("$server refused to change $uname in $udom password because ".
                   1233: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1234:     } elsif ($answer =~ "invalid_client") {
                   1235:         &logthis("$server refused to change $uname in $udom password because ".
                   1236:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1237:     } elsif ($answer =~ "^prioruse") {
                   1238:        &logthis("$server refused to change $uname in $udom password because ".
                   1239:                 "the password had been used before");
1.202     matthew  1240:     }
                   1241:     return $answer;
1.1       albertel 1242: }
                   1243: 
1.169     harris41 1244: # ----------------------- Try to determine user's current authentication scheme
                   1245: 
                   1246: sub queryauthenticate {
                   1247:     my ($uname,$udom)=@_;
1.456     albertel 1248:     my $uhome=&homeserver($uname,$udom);
                   1249:     if (!$uhome) {
                   1250: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1251: 	return 'no_host';
                   1252:     }
                   1253:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1254:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1255: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1256:     }
1.456     albertel 1257:     return $answer;
1.169     harris41 1258: }
                   1259: 
1.1       albertel 1260: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1261: 
1.1       albertel 1262: sub authenticate {
1.1073    raeburn  1263:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1264:     $upass=&escape($upass);
                   1265:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1266:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1267:     my $newhome;
1.836     www      1268:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1269: # Maybe the machine was offline and only re-appeared again recently?
                   1270:         &reconlonc();
                   1271: # One more
1.952     raeburn  1272: 	$uhome=&homeserver($uname,$udom,1);
                   1273:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1274:             if (defined(&domain($udom,'primary'))) {
                   1275:                 $newhome=&domain($udom,'primary');
                   1276:             }
                   1277:             if ($newhome ne '') {
                   1278:                 $uhome = $newhome;
                   1279:             }
                   1280:         }
1.836     www      1281: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1282: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1283: 	    return 'no_host';
                   1284:         }
1.1       albertel 1285:     }
1.1073    raeburn  1286:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1287:     if ($answer eq 'authorized') {
1.952     raeburn  1288:         if ($newhome) {
                   1289:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1290:             return 'no_account_on_host'; 
                   1291:         } else {
                   1292:             &logthis("User $uname at $udom authorized by $uhome");
                   1293:             return $uhome;
                   1294:         }
1.471     albertel 1295:     }
                   1296:     if ($answer eq 'non_authorized') {
                   1297: 	&logthis("User $uname at $udom rejected by $uhome");
                   1298: 	return 'no_host'; 
1.9       www      1299:     }
1.471     albertel 1300:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1301:     return 'no_host';
                   1302: }
                   1303: 
1.1073    raeburn  1304: sub can_host_session {
1.1074    raeburn  1305:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1306:     my $canhost = 1;
1.1074    raeburn  1307:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1308:     if (ref($remotesessions) eq 'HASH') {
                   1309:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1310:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1311:                 $canhost = 0;
                   1312:             } else {
                   1313:                 $canhost = 1;
                   1314:             }
                   1315:         }
                   1316:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1317:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1318:                 $canhost = 1;
                   1319:             } else {
                   1320:                 $canhost = 0;
                   1321:             }
                   1322:         }
                   1323:         if ($canhost) {
                   1324:             if ($remotesessions->{'version'} ne '') {
                   1325:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1326:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1327:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1328:                         my $major = $1;
                   1329:                         my $minor = $2;
                   1330:                         if (($major < $reqmajor ) ||
                   1331:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1332:                             $canhost = 0;
                   1333:                         }
                   1334:                     } else {
                   1335:                         $canhost = 0;
                   1336:                     }
                   1337:                 }
                   1338:             }
                   1339:         }
                   1340:     }
                   1341:     if ($canhost) {
                   1342:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1343:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1344:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1345:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1346:                 if (($uint_dom ne '') && 
                   1347:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1348:                     $canhost = 0;
                   1349:                 } else {
                   1350:                     $canhost = 1;
                   1351:                 }
                   1352:             }
                   1353:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1354:                 if (($uint_dom ne '') && 
                   1355:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1356:                     $canhost = 1;
                   1357:                 } else {
                   1358:                     $canhost = 0;
                   1359:                 }
                   1360:             }
                   1361:         }
                   1362:     }
                   1363:     return $canhost;
                   1364: }
                   1365: 
1.1083    raeburn  1366: sub spare_can_host {
                   1367:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1368:     my $canhost=1;
1.1172.2.62  raeburn  1369:     my $try_server_hostname = &hostname($try_server);
                   1370:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1371:     my $serverhomedom = &host_domain($serverhomeID);
                   1372:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1373:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1374:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1375:             $canhost = 0;
                   1376:         }
                   1377:     }
                   1378:     if (($canhost) && ($uint_dom)) {
                   1379:         my @intdoms;
                   1380:         my $internet_names = &get_internet_names($try_server);
                   1381:         if (ref($internet_names) eq 'ARRAY') {
                   1382:             @intdoms = @{$internet_names};
                   1383:         }
                   1384:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1385:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1386:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1387:                                          $remotesessions,
                   1388:                                          $defdomdefaults{'hostedsessions'});
                   1389:         }
1.1083    raeburn  1390:     }
                   1391:     return $canhost;
                   1392: }
                   1393: 
1.1123    raeburn  1394: sub this_host_spares {
                   1395:     my ($dom) = @_;
1.1126    raeburn  1396:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1397:     my @hosts = &current_machine_ids();
                   1398:     foreach my $lonhost (@hosts) {
                   1399:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1400:             $dom_in_use = $dom;
                   1401:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1402:             last;
                   1403:         }
                   1404:     }
1.1126    raeburn  1405:     if ($dom_in_use ne '') {
                   1406:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1407:     }
                   1408:     if (ref($result) ne 'HASH') {
                   1409:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1410:         $dom_in_use = &host_domain($lonhost_in_use);
                   1411:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1412:         if (ref($result) ne 'HASH') {
                   1413:             $result = \%spareid;
                   1414:         }
                   1415:     }
                   1416:     return $result;
                   1417: }
                   1418: 
                   1419: sub spares_for_offload  {
                   1420:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1421:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1422:     if (defined($cached)) {
                   1423:         return $result;
                   1424:     } else {
1.1126    raeburn  1425:         my $cachetime = 60*60*24;
                   1426:         my %domconfig =
                   1427:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1428:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1429:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1430:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1431:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1432:                 }
                   1433:             }
                   1434:         }
                   1435:     }
1.1126    raeburn  1436:     return;
1.1123    raeburn  1437: }
                   1438: 
1.1129    raeburn  1439: sub get_lonbalancer_config {
                   1440:     my ($servers) = @_;
                   1441:     my ($currbalancer,$currtargets);
                   1442:     if (ref($servers) eq 'HASH') {
                   1443:         foreach my $server (keys(%{$servers})) {
                   1444:             my %what = (
                   1445:                          spareid => 1,
                   1446:                          perlvar => 1,
                   1447:                        );
                   1448:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1449:             if ($result eq 'ok') {
                   1450:                 if (ref($returnhash) eq 'HASH') {
                   1451:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1452:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1453:                             $currbalancer = $server;
                   1454:                             $currtargets = {};
                   1455:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1456:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1457:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1458:                                 }
                   1459:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1460:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1461:                                 }
                   1462:                             }
                   1463:                             last;
                   1464:                         }
                   1465:                     }
                   1466:                 }
                   1467:             }
                   1468:         }
                   1469:     }
                   1470:     return ($currbalancer,$currtargets);
                   1471: }
                   1472: 
                   1473: sub check_loadbalancing {
1.1172.2.88  raeburn  1474:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1475:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1476:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1477:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1478:     my @hosts = &current_machine_ids();
1.1129    raeburn  1479:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1480:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1481:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1482:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1483:     my $domneedscache; 
1.1129    raeburn  1484:     my $cachetime = 60*60*24;
                   1485: 
                   1486:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1487:         $dom_in_use = $udom;
                   1488:         $homeintdom = 1;
                   1489:     } else {
                   1490:         $dom_in_use = $serverhomedom;
                   1491:     }
                   1492:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1493:     unless (defined($cached)) {
                   1494:         my %domconfig =
                   1495:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1496:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1497:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1498:         } else {
                   1499:             $domneedscache = $dom_in_use;
1.1129    raeburn  1500:         }
                   1501:     }
                   1502:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1503:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1504:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1505:         if ($is_balancer) {
                   1506:             if (ref($currrules) eq 'HASH') {
                   1507:                 if ($homeintdom) {
                   1508:                     if ($uname ne '') {
                   1509:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1510:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1511:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1512:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1513:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1514:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1515:                             }
                   1516:                         }
                   1517:                         if ($rule_in_effect eq '') {
                   1518:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1519:                             if ($userenv{'inststatus'} ne '') {
                   1520:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1521:                                 my ($othertitle,$usertypes,$types) =
                   1522:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1523:                                 if (ref($types) eq 'ARRAY') {
                   1524:                                     foreach my $type (@{$types}) {
                   1525:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1526:                                             if (exists($currrules->{$type})) {
                   1527:                                                 $rule_in_effect = $currrules->{$type};
                   1528:                                             }
                   1529:                                         }
                   1530:                                     }
                   1531:                                 }
                   1532:                             } else {
                   1533:                                 if (exists($currrules->{'default'})) {
                   1534:                                     $rule_in_effect = $currrules->{'default'};
                   1535:                                 }
                   1536:                             }
                   1537:                         }
                   1538:                     } else {
                   1539:                         if (exists($currrules->{'default'})) {
                   1540:                             $rule_in_effect = $currrules->{'default'};
                   1541:                         }
                   1542:                     }
                   1543:                 } else {
                   1544:                     if ($currrules->{'_LC_external'} ne '') {
                   1545:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1546:                     }
                   1547:                 }
                   1548:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1549:                                                        $uname,$udom);
                   1550:             }
                   1551:         }
                   1552:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1553:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1554:         unless (defined($cached)) {
                   1555:             my %domconfig =
                   1556:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1557:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1558:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1559:             } else {
                   1560:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1561:             }
                   1562:         }
                   1563:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1564:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1565:                 &check_balancer_result($result,@hosts);
                   1566:             if ($is_balancer) {
1.1129    raeburn  1567:                 if (ref($currrules) eq 'HASH') {
                   1568:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1569:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1570:                     }
                   1571:                 }
                   1572:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1573:                                                        $uname,$udom);
                   1574:             }
                   1575:         } else {
                   1576:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1577:                 $is_balancer = 1;
                   1578:                 $offloadto = &this_host_spares($dom_in_use);
                   1579:             }
1.1172.2.75  raeburn  1580:             unless (defined($cached)) {
                   1581:                 $domneedscache = $serverhomedom;
                   1582:             }
1.1129    raeburn  1583:         }
                   1584:     } else {
                   1585:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1586:             $is_balancer = 1;
                   1587:             $offloadto = &this_host_spares($dom_in_use);
                   1588:         }
1.1172.2.75  raeburn  1589:         unless (defined($cached)) {
                   1590:             $domneedscache = $serverhomedom;
                   1591:         }
                   1592:     }
                   1593:     if ($domneedscache) {
                   1594:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1595:     }
1.1172.2.118.  .11(raeb 1596:-20):     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1597:         my $lowest_load = 30000;
                   1598:         if (ref($offloadto) eq 'HASH') {
                   1599:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1600:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1601:                     ($otherserver,$lowest_load) =
                   1602:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1603:                 }
1.1129    raeburn  1604:             }
1.1172.2.5  raeburn  1605:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1606: 
1.1172.2.5  raeburn  1607:             if (!$found_server) {
                   1608:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1609:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1610:                         ($otherserver,$lowest_load) =
                   1611:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1612:                     }
                   1613:                 }
                   1614:             }
                   1615:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1616:             if (@{$offloadto} == 1) {
                   1617:                 $otherserver = $offloadto->[0];
                   1618:             } elsif (@{$offloadto} > 1) {
                   1619:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1620:                     ($otherserver,$lowest_load) =
                   1621:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1622:                 }
                   1623:             }
                   1624:         }
1.1172.2.88  raeburn  1625:         unless ($caller eq 'login') {
                   1626:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1627:                 $is_balancer = 0;
                   1628:                 if ($uname ne '' && $udom ne '') {
                   1629:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1630:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1631:                                  'user.loadbalcheck.time' => time});
                   1632:                     }
1.1172.2.5  raeburn  1633:                 }
1.1129    raeburn  1634:             }
                   1635:         }
1.1172.2.118.  .11(raeb 1636:-20):     }
                   1637:-20):     if (($is_balancer) && (!$homeintdom)) {
                   1638:-20):         undef($setcookie);
1.1129    raeburn  1639:     }
1.1172.2.107  raeburn  1640:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1641: }
                   1642: 
1.1172.2.12  raeburn  1643: sub check_balancer_result {
                   1644:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1645:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1646:     if (ref($result) eq 'HASH') {
                   1647:         if ($result->{'lonhost'} ne '') {
                   1648:             my $currbalancer = $result->{'lonhost'};
                   1649:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1650:                 $is_balancer = 1;
                   1651:                 $currtargets = $result->{'targets'};
                   1652:                 $currrules = $result->{'rules'};
                   1653:             }
                   1654:         } else {
                   1655:             foreach my $key (keys(%{$result})) {
                   1656:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1657:                     (ref($result->{$key}) eq 'HASH')) {
                   1658:                     $is_balancer = 1;
                   1659:                     $currrules = $result->{$key}{'rules'};
                   1660:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1661:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1662:                     last;
                   1663:                 }
                   1664:             }
                   1665:         }
                   1666:     }
1.1172.2.107  raeburn  1667:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1668: }
                   1669: 
1.1129    raeburn  1670: sub get_loadbalancer_targets {
                   1671:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1672:     my $offloadto;
1.1172.2.4  raeburn  1673:     if ($rule_in_effect eq 'none') {
                   1674:         return [$perlvar{'lonHostID'}];
                   1675:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1676:         $offloadto = $currtargets;
                   1677:     } else {
                   1678:         if ($rule_in_effect eq 'homeserver') {
                   1679:             my $homeserver = &homeserver($uname,$udom);
                   1680:             if ($homeserver ne 'no_host') {
                   1681:                 $offloadto = [$homeserver];
                   1682:             }
                   1683:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1684:             my %domconfig =
                   1685:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1686:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1687:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1688:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1689:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1690:                     }
                   1691:                 }
                   1692:             } else {
1.1172.2.7  raeburn  1693:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1694:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1695:                 if (&hostname($remotebalancer) ne '') {
                   1696:                     $offloadto = [$remotebalancer];
                   1697:                 }
                   1698:             }
                   1699:         } elsif (&hostname($rule_in_effect) ne '') {
                   1700:             $offloadto = [$rule_in_effect];
                   1701:         }
                   1702:     }
                   1703:     return $offloadto;
                   1704: }
                   1705: 
1.1127    raeburn  1706: sub internet_dom_servers {
                   1707:     my ($dom) = @_;
                   1708:     my (%uniqservers,%servers);
                   1709:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1710:     my @machinedoms = &machine_domains($primaryserver);
                   1711:     foreach my $mdom (@machinedoms) {
                   1712:         my %currservers = %servers;
                   1713:         my %server = &get_servers($mdom);
                   1714:         %servers = (%currservers,%server);
                   1715:     }
                   1716:     my %by_hostname;
                   1717:     foreach my $id (keys(%servers)) {
                   1718:         push(@{$by_hostname{$servers{$id}}},$id);
                   1719:     }
                   1720:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1721:         if (@{$by_hostname{$hostname}} > 1) {
                   1722:             my $match = 0;
                   1723:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1724:                 if (&host_domain($id) eq $dom) {
                   1725:                     $uniqservers{$id} = $hostname;
                   1726:                     $match = 1;
                   1727:                 }
                   1728:             }
                   1729:             unless ($match) {
                   1730:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1731:             }
                   1732:         } else {
                   1733:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1734:         }
                   1735:     }
                   1736:     return %uniqservers;
                   1737: }
                   1738: 
1.1       albertel 1739: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1740: 
1.599     albertel 1741: my %homecache;
1.1       albertel 1742: sub homeserver {
1.230     stredwic 1743:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1744:     my $index="$uname:$udom";
1.426     albertel 1745: 
1.599     albertel 1746:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1747: 
                   1748:     my %servers = &get_servers($udom,'library');
                   1749:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1750:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1751: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1752: 
                   1753: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1754: 	if ($answer eq 'found') {
                   1755: 	    delete($badServerCache{$tryserver}); 
                   1756: 	    return $homecache{$index}=$tryserver;
                   1757: 	} elsif ($answer eq 'no_host') {
                   1758: 	    $badServerCache{$tryserver}=1;
                   1759: 	}
1.1       albertel 1760:     }    
                   1761:     return 'no_host';
1.70      www      1762: }
                   1763: 
                   1764: # ------------------------------------- Find the usernames behind a list of IDs
                   1765: 
                   1766: sub idget {
                   1767:     my ($udom,@ids)=@_;
                   1768:     my %returnhash=();
                   1769:     
1.841     albertel 1770:     my %servers = &get_servers($udom,'library');
                   1771:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1772: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1773: 	$idlist=~tr/A-Z/a-z/; 
                   1774: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1775: 	my @answer=();
                   1776: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1777: 	    @answer=split(/\&/,$reply);
                   1778: 	}                    ;
                   1779: 	my $i;
                   1780: 	for ($i=0;$i<=$#ids;$i++) {
                   1781: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1782: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1783: 	    } 
                   1784: 	}
                   1785:     } 
1.70      www      1786:     return %returnhash;
                   1787: }
                   1788: 
                   1789: # ------------------------------------- Find the IDs behind a list of usernames
                   1790: 
                   1791: sub idrget {
                   1792:     my ($udom,@unames)=@_;
                   1793:     my %returnhash=();
1.800     albertel 1794:     foreach my $uname (@unames) {
                   1795:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1796:     }
1.70      www      1797:     return %returnhash;
                   1798: }
                   1799: 
                   1800: # ------------------------------- Store away a list of names and associated IDs
                   1801: 
                   1802: sub idput {
                   1803:     my ($udom,%ids)=@_;
                   1804:     my %servers=();
1.800     albertel 1805:     foreach my $uname (keys(%ids)) {
                   1806: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1807:         my $uhom=&homeserver($uname,$udom);
1.70      www      1808:         if ($uhom ne 'no_host') {
1.800     albertel 1809:             my $id=&escape($ids{$uname});
1.70      www      1810:             $id=~tr/A-Z/a-z/;
1.800     albertel 1811:             my $esc_unam=&escape($uname);
1.70      www      1812: 	    if ($servers{$uhom}) {
1.800     albertel 1813: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1814:             } else {
1.800     albertel 1815:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1816:             }
                   1817:         }
1.191     harris41 1818:     }
1.800     albertel 1819:     foreach my $server (keys(%servers)) {
                   1820:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1821:     }
1.344     www      1822: }
                   1823: 
1.1172.2.30  raeburn  1824: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1825: 
                   1826: sub iddel {
                   1827:     my ($udom,$idshashref,$uhome)=@_;
                   1828:     my %result=();
                   1829:     unless (ref($idshashref) eq 'HASH') {
                   1830:         return %result;
                   1831:     }
                   1832:     my %servers=();
                   1833:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1834:         my $uhom;
                   1835:         if ($uhome) {
                   1836:             $uhom = $uhome;
                   1837:         } else {
                   1838:             $uhom=&homeserver($uname,$udom);
                   1839:         }
                   1840:         if ($uhom ne 'no_host') {
                   1841:             if ($servers{$uhom}) {
                   1842:                 $servers{$uhom}.='&'.&escape($id);
                   1843:             } else {
                   1844:                 $servers{$uhom}=&escape($id);
                   1845:             }
                   1846:         }
                   1847:     }
                   1848:     foreach my $server (keys(%servers)) {
                   1849:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1850:     }
                   1851:     return %result;
                   1852: }
                   1853: 
1.1023    raeburn  1854: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1855: sub dump_dom {
1.1165    droeschl 1856:     my ($namespace, $udom, $regexp) = @_;
                   1857: 
                   1858:     $udom ||= $env{'user.domain'};
                   1859: 
                   1860:     return () unless $udom;
                   1861: 
                   1862:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1863: }
                   1864: 
1.1023    raeburn  1865: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1866: 
                   1867: sub get_dom {
1.860     raeburn  1868:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1869:     return if ($udom eq 'public');
1.806     raeburn  1870:     my $items='';
                   1871:     foreach my $item (@$storearr) {
                   1872:         $items.=&escape($item).'&';
                   1873:     }
                   1874:     $items=~s/\&$//;
1.860     raeburn  1875:     if (!$udom) {
                   1876:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1877:         return if ($udom eq 'public');
1.860     raeburn  1878:         if (defined(&domain($udom,'primary'))) {
                   1879:             $uhome=&domain($udom,'primary');
                   1880:         } else {
1.874     albertel 1881:             undef($uhome);
1.860     raeburn  1882:         }
                   1883:     } else {
                   1884:         if (!$uhome) {
                   1885:             if (defined(&domain($udom,'primary'))) {
                   1886:                 $uhome=&domain($udom,'primary');
                   1887:             }
                   1888:         }
                   1889:     }
                   1890:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.118.  .1(raebu 1891:20):         my $rep;
                   1892:20):         if ($namespace =~ /^enc/) {
                   1893:20):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1894:20):         } else {
                   1895:20):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1896:20):         }
1.866     raeburn  1897:         my %returnhash;
1.875     albertel 1898:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1899:             return %returnhash;
                   1900:         }
1.806     raeburn  1901:         my @pairs=split(/\&/,$rep);
                   1902:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1903:             return @pairs;
                   1904:         }
                   1905:         my $i=0;
                   1906:         foreach my $item (@$storearr) {
                   1907:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1908:             $i++;
                   1909:         }
                   1910:         return %returnhash;
                   1911:     } else {
1.880     banghart 1912:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1913:     }
                   1914: }
                   1915: 
                   1916: # -------------------------------------------- put items in domain db files 
                   1917: 
                   1918: sub put_dom {
1.860     raeburn  1919:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1920:     if (!$udom) {
                   1921:         $udom=$env{'user.domain'};
                   1922:         if (defined(&domain($udom,'primary'))) {
                   1923:             $uhome=&domain($udom,'primary');
                   1924:         } else {
1.874     albertel 1925:             undef($uhome);
1.860     raeburn  1926:         }
                   1927:     } else {
                   1928:         if (!$uhome) {
                   1929:             if (defined(&domain($udom,'primary'))) {
                   1930:                 $uhome=&domain($udom,'primary');
                   1931:             }
                   1932:         }
                   1933:     } 
                   1934:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1935:         my $items='';
                   1936:         foreach my $item (keys(%$storehash)) {
                   1937:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1938:         }
                   1939:         $items=~s/\&$//;
1.1172.2.118.  .1(raebu 1940:20):         if ($namespace =~ /^enc/) {
                   1941:20):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1942:20):         } else {
                   1943:20):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1944:20):         }
1.806     raeburn  1945:     } else {
1.860     raeburn  1946:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1947:     }
                   1948: }
                   1949: 
1.1023    raeburn  1950: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1951: sub newput_dom {
1.1023    raeburn  1952:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1953:     my $result;
                   1954:     if (!$udom) {
                   1955:         $udom=$env{'user.domain'};
                   1956:     }
1.1023    raeburn  1957:     if ($udom) {
                   1958:         my $uname = &get_domainconfiguser($udom);
                   1959:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1960:     }
                   1961:     return $result;
                   1962: }
                   1963: 
1.1023    raeburn  1964: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1965: sub del_dom {
1.1023    raeburn  1966:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1967:     if (ref($storearr) eq 'ARRAY') {
                   1968:         if (!$udom) {
                   1969:             $udom=$env{'user.domain'};
                   1970:         }
1.1023    raeburn  1971:         if ($udom) {
                   1972:             my $uname = &get_domainconfiguser($udom); 
                   1973:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1974:         }
                   1975:     }
                   1976: }
                   1977: 
1.1023    raeburn  1978: # ----------------------------------construct domainconfig user for a domain 
                   1979: sub get_domainconfiguser {
                   1980:     my ($udom) = @_;
                   1981:     return $udom.'-domainconfig';
                   1982: }
                   1983: 
1.837     raeburn  1984: sub retrieve_inst_usertypes {
                   1985:     my ($udom) = @_;
                   1986:     my (%returnhash,@order);
1.989     raeburn  1987:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1988:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1989:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1990:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1991:     } else {
                   1992:         if (defined(&domain($udom,'primary'))) {
                   1993:             my $uhome=&domain($udom,'primary');
                   1994:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1995:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1996:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1997:                 return (\%returnhash,\@order);
                   1998:             }
                   1999:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2000:             my @pairs=split(/\&/,$hashitems);
                   2001:             foreach my $item (@pairs) {
                   2002:                 my ($key,$value)=split(/=/,$item,2);
                   2003:                 $key = &unescape($key);
                   2004:                 next if ($key =~ /^error: 2 /);
                   2005:                 $returnhash{$key}=&thaw_unescape($value);
                   2006:             }
                   2007:             my @esc_order = split(/\&/,$orderitems);
                   2008:             foreach my $item (@esc_order) {
                   2009:                 push(@order,&unescape($item));
                   2010:             }
                   2011:         } else {
1.1172.2.44  raeburn  2012:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2013:         }
1.1172.2.44  raeburn  2014:         return (\%returnhash,\@order);
1.837     raeburn  2015:     }
                   2016: }
                   2017: 
1.868     raeburn  2018: sub is_domainimage {
                   2019:     my ($url) = @_;
1.1172.2.74  raeburn  2020:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2021:         if (&domain($1) ne '') {
                   2022:             return '1';
                   2023:         }
                   2024:     }
                   2025:     return;
                   2026: }
                   2027: 
1.899     raeburn  2028: sub inst_directory_query {
                   2029:     my ($srch) = @_;
                   2030:     my $udom = $srch->{'srchdomain'};
                   2031:     my %results;
                   2032:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2033:     my $outcome;
1.899     raeburn  2034:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2035:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2036:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2037:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2038:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2039:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2040:                     (($major == 2) && ($minor < 11)) ||
                   2041:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2042:                     return;
                   2043:                 }
                   2044:             }
                   2045:         }
1.904     albertel 2046: 	my $queryid=&reply("querysend:instdirsearch:".
                   2047: 			   &escape($srch->{'srchby'}).':'.
                   2048: 			   &escape($srch->{'srchterm'}).':'.
                   2049: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2050: 	my $host=&hostname($homeserver);
                   2051: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2052: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2053: 	    return;
                   2054: 	}
                   2055: 	my $response = &get_query_reply($queryid);
                   2056: 	my $maxtries = 5;
                   2057: 	my $tries = 1;
                   2058: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2059: 	    $response = &get_query_reply($queryid);
                   2060: 	    $tries ++;
                   2061: 	}
                   2062: 
                   2063:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2064:             if ($response eq 'unavailable') {
                   2065:                 $outcome = $response;
                   2066:             } else {
                   2067:                 $outcome = 'ok';
                   2068:                 my @matches = split(/\n/,$response);
                   2069:                 foreach my $match (@matches) {
                   2070:                     my ($key,$value) = split(/=/,$match);
                   2071:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2072:                 }
1.899     raeburn  2073:             }
                   2074:         }
                   2075:     }
1.909     raeburn  2076:     return ($outcome,%results);
1.899     raeburn  2077: }
                   2078: 
                   2079: sub usersearch {
                   2080:     my ($srch) = @_;
                   2081:     my $dom = $srch->{'srchdomain'};
                   2082:     my %results;
                   2083:     my %libserv = &all_library();
                   2084:     my $query = 'usersearch';
                   2085:     foreach my $tryserver (keys(%libserv)) {
                   2086:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2087:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2088:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2089:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118.  .2(raebu 2090:20):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2091:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2092:                              (($major == 2) && ($minor < 11)) ||
                   2093:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2094:                 }
                   2095:             }
1.899     raeburn  2096:             my $host=&hostname($tryserver);
                   2097:             my $queryid=
1.911     raeburn  2098:                 &reply("querysend:".&escape($query).':'.
                   2099:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2100:                        &escape($srch->{'srchtype'}).':'.
                   2101:                        &escape($srch->{'srchterm'}),$tryserver);
                   2102:             if ($queryid !~/^\Q$host\E\_/) {
                   2103:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2104:                 next;
1.899     raeburn  2105:             }
                   2106:             my $reply = &get_query_reply($queryid);
                   2107:             my $maxtries = 1;
                   2108:             my $tries = 1;
                   2109:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2110:                 $reply = &get_query_reply($queryid);
                   2111:                 $tries ++;
                   2112:             }
                   2113:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2114:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2115:             } else {
1.911     raeburn  2116:                 my @matches;
                   2117:                 if ($reply =~ /\n/) {
                   2118:                     @matches = split(/\n/,$reply);
                   2119:                 } else {
                   2120:                     @matches = split(/\&/,$reply);
                   2121:                 }
1.899     raeburn  2122:                 foreach my $match (@matches) {
                   2123:                     my ($uname,$udom,%userhash);
1.911     raeburn  2124:                     foreach my $entry (split(/:/,$match)) {
                   2125:                         my ($key,$value) =
                   2126:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2127:                         $userhash{$key} = $value;
                   2128:                         if ($key eq 'username') {
                   2129:                             $uname = $value;
                   2130:                         } elsif ($key eq 'domain') {
                   2131:                             $udom = $value;
1.911     raeburn  2132:                         }
1.899     raeburn  2133:                     }
                   2134:                     $results{$uname.':'.$udom} = \%userhash;
                   2135:                 }
                   2136:             }
                   2137:         }
                   2138:     }
                   2139:     return %results;
                   2140: }
                   2141: 
1.912     raeburn  2142: sub get_instuser {
                   2143:     my ($udom,$uname,$id) = @_;
                   2144:     my $homeserver = &domain($udom,'primary');
                   2145:     my ($outcome,%results);
                   2146:     if ($homeserver ne '') {
                   2147:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2148:                            &escape($id).':'.&escape($udom),$homeserver);
                   2149:         my $host=&hostname($homeserver);
                   2150:         if ($queryid !~/^\Q$host\E\_/) {
                   2151:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2152:             return;
                   2153:         }
                   2154:         my $response = &get_query_reply($queryid);
                   2155:         my $maxtries = 5;
                   2156:         my $tries = 1;
                   2157:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2158:             $response = &get_query_reply($queryid);
                   2159:             $tries ++;
                   2160:         }
                   2161:         if (!&error($response) && $response ne 'refused') {
                   2162:             if ($response eq 'unavailable') {
                   2163:                 $outcome = $response;
                   2164:             } else {
                   2165:                 $outcome = 'ok';
                   2166:                 my @matches = split(/\n/,$response);
                   2167:                 foreach my $match (@matches) {
                   2168:                     my ($key,$value) = split(/=/,$match);
                   2169:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2170:                 }
                   2171:             }
                   2172:         }
                   2173:     }
                   2174:     my %userinfo;
                   2175:     if (ref($results{$uname}) eq 'HASH') {
                   2176:         %userinfo = %{$results{$uname}};
                   2177:     } 
                   2178:     return ($outcome,%userinfo);
                   2179: }
                   2180: 
1.1172.2.69  raeburn  2181: sub get_multiple_instusers {
                   2182:     my ($udom,$users,$caller) = @_;
                   2183:     my ($outcome,$results);
                   2184:     if (ref($users) eq 'HASH') {
                   2185:         my $count = keys(%{$users});
                   2186:         my $requested = &freeze_escape($users);
                   2187:         my $homeserver = &domain($udom,'primary');
                   2188:         if ($homeserver ne '') {
                   2189:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2190:             my $host=&hostname($homeserver);
                   2191:             if ($queryid !~/^\Q$host\E\_/) {
                   2192:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2193:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2194:                 return ($outcome,$results);
                   2195:             }
                   2196:             my $response = &get_query_reply($queryid);
                   2197:             my $maxtries = 5;
                   2198:             if ($count > 100) {
                   2199:                 $maxtries = 1+int($count/20);
                   2200:             }
                   2201:             my $tries = 1;
                   2202:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2203:                 $response = &get_query_reply($queryid);
                   2204:                 $tries ++;
                   2205:             }
                   2206:             if ($response eq '') {
                   2207:                 $results = {};
                   2208:                 foreach my $key (keys(%{$users})) {
                   2209:                     my ($uname,$id);
                   2210:                     if ($caller eq 'id') {
                   2211:                         $id = $key;
                   2212:                     } else {
                   2213:                         $uname = $key;
                   2214:                     }
                   2215:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2216:                     $outcome = $resp;
                   2217:                     if ($resp eq 'ok') {
                   2218:                         %{$results} = (%{$results}, %info);
                   2219:                     } else {
                   2220:                         last;
                   2221:                     }
                   2222:                 }
                   2223:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2224:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2225:                     $outcome = $response;
                   2226:                 } else {
                   2227:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2228:                     if ($outcome eq 'ok') {
                   2229:                         $results = &thaw_unescape($userdata);
                   2230:                     }
                   2231:                 }
                   2232:             }
                   2233:         }
                   2234:     }
                   2235:     return ($outcome,$results);
                   2236: }
                   2237: 
1.912     raeburn  2238: sub inst_rulecheck {
1.923     raeburn  2239:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2240:     my %returnhash;
                   2241:     if ($udom ne '') {
                   2242:         if (ref($rules) eq 'ARRAY') {
                   2243:             @{$rules} = map {&escape($_);} (@{$rules});
                   2244:             my $rulestr = join(':',@{$rules});
                   2245:             my $homeserver=&domain($udom,'primary');
                   2246:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2247:                 my $response;
                   2248:                 if ($item eq 'username') {                
                   2249:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2250:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2251:                                               $homeserver));
1.923     raeburn  2252:                 } elsif ($item eq 'id') {
                   2253:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2254:                                               ':'.&escape($id).':'.$rulestr,
                   2255:                                               $homeserver));
1.945     raeburn  2256:                 } elsif ($item eq 'selfcreate') {
                   2257:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2258:                                                &escape($udom).':'.&escape($uname).
                   2259:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2260:                 }
1.912     raeburn  2261:                 if ($response ne 'refused') {
                   2262:                     my @pairs=split(/\&/,$response);
                   2263:                     foreach my $item (@pairs) {
                   2264:                         my ($key,$value)=split(/=/,$item,2);
                   2265:                         $key = &unescape($key);
                   2266:                         next if ($key =~ /^error: 2 /);
                   2267:                         $returnhash{$key}=&thaw_unescape($value);
                   2268:                     }
                   2269:                 }
                   2270:             }
                   2271:         }
                   2272:     }
                   2273:     return %returnhash;
                   2274: }
                   2275: 
                   2276: sub inst_userrules {
1.923     raeburn  2277:     my ($udom,$check) = @_;
1.912     raeburn  2278:     my (%ruleshash,@ruleorder);
                   2279:     if ($udom ne '') {
                   2280:         my $homeserver=&domain($udom,'primary');
                   2281:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2282:             my $response;
                   2283:             if ($check eq 'id') {
                   2284:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2285:                                  $homeserver);
1.943     raeburn  2286:             } elsif ($check eq 'email') {
                   2287:                 $response=&reply('instemailrules:'.&escape($udom),
                   2288:                                  $homeserver);
1.923     raeburn  2289:             } else {
                   2290:                 $response=&reply('instuserrules:'.&escape($udom),
                   2291:                                  $homeserver);
                   2292:             }
1.912     raeburn  2293:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2294:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2295:                 ($response ne 'no_such_host')) {
                   2296:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2297:                 my @pairs=split(/\&/,$hashitems);
                   2298:                 foreach my $item (@pairs) {
                   2299:                     my ($key,$value)=split(/=/,$item,2);
                   2300:                     $key = &unescape($key);
                   2301:                     next if ($key =~ /^error: 2 /);
                   2302:                     $ruleshash{$key}=&thaw_unescape($value);
                   2303:                 }
                   2304:                 my @esc_order = split(/\&/,$orderitems);
                   2305:                 foreach my $item (@esc_order) {
                   2306:                     push(@ruleorder,&unescape($item));
                   2307:                 }
                   2308:             }
                   2309:         }
                   2310:     }
                   2311:     return (\%ruleshash,\@ruleorder);
                   2312: }
                   2313: 
1.976     raeburn  2314: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2315: 
                   2316: sub get_domain_defaults {
1.1172.2.35  raeburn  2317:     my ($domain,$ignore_cache) = @_;
                   2318:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2319:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2320:     unless ($ignore_cache) {
                   2321:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2322:         if (defined($cached)) {
                   2323:             if (ref($result) eq 'HASH') {
                   2324:                 return %{$result};
                   2325:             }
1.943     raeburn  2326:         }
                   2327:     }
                   2328:     my %domdefaults;
                   2329:     my %domconfig =
1.989     raeburn  2330:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2331:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2332:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2333:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2334:                                   'coursecategories','autoenroll',
                   2335:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2336:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2337:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2338:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2339:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2340:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2341:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2342:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2343:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2344:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2345:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2346:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2347:     } else {
                   2348:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2349:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2350:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2351:     }
1.976     raeburn  2352:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2353:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2354:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2355:         } else {
                   2356:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2357:         }
1.1172.2.6  raeburn  2358:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2359:         foreach my $item (@usertools) {
                   2360:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2361:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2362:             }
                   2363:         }
1.1172.2.29  raeburn  2364:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2365:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2366:         }
1.976     raeburn  2367:     }
1.985     raeburn  2368:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2369:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2370:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2371:         }
                   2372:     }
1.1172.2.9  raeburn  2373:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2374:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2375:     }
1.989     raeburn  2376:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2377:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2378:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2379:         }
                   2380:     }
1.1047    raeburn  2381:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2382:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2383:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2384:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2385:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2386:         }
1.1172.2.41  raeburn  2387:         foreach my $type (@coursetypes) {
                   2388:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2389:                 unless ($type eq 'community') {
                   2390:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2391:                 }
                   2392:             }
                   2393:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2394:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2395:             }
1.1172.2.60  raeburn  2396:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2397:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2398:                     $domdefaults{$type.'postsubtimeout'} =
                   2399:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2400:                 }
                   2401:             }
1.1172.2.30  raeburn  2402:         }
1.1172.2.67  raeburn  2403:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2404:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2405:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2406:                 if (@clonecodes) {
                   2407:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2408:                 }
                   2409:             }
                   2410:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2411:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2412:         }
1.1172.2.103  raeburn  2413:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2414:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2415:         }
1.1047    raeburn  2416:     }
1.1073    raeburn  2417:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2418:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2419:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2420:         }
                   2421:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2422:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2423:         }
1.1172.2.62  raeburn  2424:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2425:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2426:         }
1.1073    raeburn  2427:     }
1.1172.2.41  raeburn  2428:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2429:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2430:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2431:                             'approval','limit');
                   2432:             foreach my $type (@coursetypes) {
                   2433:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2434:                     my @mgrdc = ();
                   2435:                     foreach my $item (@settings) {
                   2436:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2437:                             push(@mgrdc,$item);
                   2438:                         }
                   2439:                     }
                   2440:                     if (@mgrdc) {
                   2441:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2442:                     }
                   2443:                 }
                   2444:             }
                   2445:         }
                   2446:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2447:             foreach my $type (@coursetypes) {
                   2448:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2449:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2450:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2451:                     }
                   2452:                 }
                   2453:             }
                   2454:         }
                   2455:     }
1.1172.2.46  raeburn  2456:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2457:         $domdefaults{'catauth'} = 'std';
                   2458:         $domdefaults{'catunauth'} = 'std';
                   2459:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2460:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2461:         }
                   2462:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2463:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2464:         }
                   2465:     }
1.1172.2.76  raeburn  2466:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2467:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2468:     }
1.1172.2.89  raeburn  2469:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2470:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2471:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2472:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2473:         }
                   2474:     }
1.1172.2.23  raeburn  2475:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2476:     return %domdefaults;
                   2477: }
                   2478: 
1.1172.2.106  raeburn  2479: sub get_dom_cats {
                   2480:     my ($dom) = @_;
                   2481:     return unless (&domain($dom));
                   2482:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2483:     unless (defined($cached)) {
                   2484:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2485:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2486:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2487:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2488:             } else {
                   2489:                 $cats = {};
                   2490:             }
                   2491:         } else {
                   2492:             $cats = {};
                   2493:         }
                   2494:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2495:     }
                   2496:     return $cats;
                   2497: }
                   2498: 
                   2499: sub get_dom_instcats {
                   2500:     my ($dom) = @_;
                   2501:     return unless (&domain($dom));
                   2502:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2503:     unless (defined($cached)) {
                   2504:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2505:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2506:         if ($totcodes > 0) {
                   2507:             my $caller = 'global';
                   2508:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2509:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2510:                 $instcats = {
                   2511:                                 codes => \%codes,
                   2512:                                 codetitles => \@codetitles,
                   2513:                                 cat_titles => \%cat_titles,
                   2514:                                 cat_order => \%cat_order,
                   2515:                             };
                   2516:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2517:             }
                   2518:         }
                   2519:     }
                   2520:     return $instcats;
                   2521: }
                   2522: 
                   2523: sub retrieve_instcodes {
                   2524:     my ($coursecodes,$dom) = @_;
                   2525:     my $totcodes;
                   2526:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2527:     foreach my $course (keys(%courses)) {
                   2528:         if (ref($courses{$course}) eq 'HASH') {
                   2529:             if ($courses{$course}{'inst_code'} ne '') {
                   2530:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2531:                 $totcodes ++;
                   2532:             }
                   2533:         }
                   2534:     }
                   2535:     return $totcodes;
                   2536: }
                   2537: 
1.1172.2.113  raeburn  2538: # --------------------------------------------- Get domain config for passwords
                   2539: 
                   2540: sub get_passwdconf {
                   2541:     my ($dom) = @_;
                   2542:     my (%passwdconf,$gotconf,$lookup);
                   2543:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2544:     if (defined($cached)) {
                   2545:         if (ref($result) eq 'HASH') {
                   2546:             %passwdconf = %{$result};
                   2547:             $gotconf = 1;
                   2548:         }
                   2549:     }
                   2550:     unless ($gotconf) {
                   2551:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2552:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2553:             %passwdconf = %{$domconfig{'passwords'}};
                   2554:         }
                   2555:         my $cachetime = 24*60*60;
                   2556:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2557:     }
                   2558:     return %passwdconf;
                   2559: }
                   2560: 
1.1172.2.118.  .1(raebu 2561:20): sub course_portal_url {
                   2562:20):     my ($cnum,$cdom) = @_;
                   2563:20):     my $chome = &homeserver($cnum,$cdom);
                   2564:20):     my $hostname = &hostname($chome);
                   2565:20):     my $protocol = $protocol{$chome};
                   2566:20):     $protocol = 'http' if ($protocol ne 'https');
                   2567:20):     my %domdefaults = &get_domain_defaults($cdom);
                   2568:20):     my $firsturl;
                   2569:20):     if ($domdefaults{'portal_def'}) {
                   2570:20):         $firsturl = $domdefaults{'portal_def'};
                   2571:20):     } else {
                   2572:20):         $firsturl = $protocol.'://'.$hostname;
                   2573:20):     }
                   2574:20):     return $firsturl;
                   2575:20): }
                   2576:20): 
1.344     www      2577: # --------------------------------------------------- Assign a key to a student
                   2578: 
                   2579: sub assign_access_key {
1.364     www      2580: #
                   2581: # a valid key looks like uname:udom#comments
                   2582: # comments are being appended
                   2583: #
1.498     www      2584:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2585:     $kdom=
1.620     albertel 2586:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2587:     $knum=
1.620     albertel 2588:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2589:     $cdom=
1.620     albertel 2590:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2591:     $cnum=
1.620     albertel 2592:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2593:     $udom=$env{'user.name'} unless (defined($udom));
                   2594:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2595:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2596:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2597:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2598:                                                   # assigned to this person
                   2599:                                                   # - this should not happen,
1.345     www      2600:                                                   # unless something went wrong
                   2601:                                                   # the first time around
                   2602: # ready to assign
1.364     www      2603:         $logentry=$1.'; '.$logentry;
1.496     www      2604:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2605:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2606: # key now belongs to user
1.346     www      2607: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2608:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2609:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2610:                 return 'ok';
                   2611:             } else {
                   2612:                 return 
                   2613:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2614: 	    }
                   2615:         } else {
                   2616:             return 'error: Could not assign key, try again later.';
                   2617:         }
1.364     www      2618:     } elsif (!$existing{$ckey}) {
1.345     www      2619: # the key does not exist
                   2620: 	return 'error: The key does not exist';
                   2621:     } else {
                   2622: # the key is somebody else's
                   2623: 	return 'error: The key is already in use';
                   2624:     }
1.344     www      2625: }
                   2626: 
1.364     www      2627: # ------------------------------------------ put an additional comment on a key
                   2628: 
                   2629: sub comment_access_key {
                   2630: #
                   2631: # a valid key looks like uname:udom#comments
                   2632: # comments are being appended
                   2633: #
                   2634:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2635:     $cdom=
1.620     albertel 2636:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2637:     $cnum=
1.620     albertel 2638:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2639:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2640:     if ($existing{$ckey}) {
                   2641:         $existing{$ckey}.='; '.$logentry;
                   2642: # ready to assign
1.367     www      2643:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2644:                                                  $cdom,$cnum) eq 'ok') {
                   2645: 	    return 'ok';
                   2646:         } else {
                   2647: 	    return 'error: Count not store comment.';
                   2648:         }
                   2649:     } else {
                   2650: # the key does not exist
                   2651: 	return 'error: The key does not exist';
                   2652:     }
                   2653: }
                   2654: 
1.344     www      2655: # ------------------------------------------------------ Generate a set of keys
                   2656: 
                   2657: sub generate_access_keys {
1.364     www      2658:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2659:     $cdom=
1.620     albertel 2660:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2661:     $cnum=
1.620     albertel 2662:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2663:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2664:     unless (($cdom) && ($cnum)) { return 0; }
                   2665:     if ($number>10000) { return 0; }
                   2666:     sleep(2); # make sure don't get same seed twice
                   2667:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2668:     my $total=0;
                   2669:     for (my $i=1;$i<=$number;$i++) {
                   2670:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2671:                   sprintf("%lx",int(100000*rand)).'-'.
                   2672:                   sprintf("%lx",int(100000*rand));
                   2673:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2674:        $newkey=~s/0/h/g; # and also 0 and O
                   2675:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2676:        if ($existing{$newkey}) {
                   2677:            $i--;
                   2678:        } else {
1.364     www      2679: 	  if (&put('accesskeys',
                   2680:               { $newkey => '# generated '.localtime().
1.620     albertel 2681:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2682:                            '; '.$logentry },
                   2683: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2684:               $total++;
                   2685: 	  }
                   2686:        }
                   2687:     }
1.620     albertel 2688:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2689:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2690:     return $total;
                   2691: }
                   2692: 
                   2693: # ------------------------------------------------------- Validate an accesskey
                   2694: 
                   2695: sub validate_access_key {
                   2696:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2697:     $cdom=
1.620     albertel 2698:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2699:     $cnum=
1.620     albertel 2700:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2701:     $udom=$env{'user.domain'} unless (defined($udom));
                   2702:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2703:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2704:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2705: }
                   2706: 
                   2707: # ------------------------------------- Find the section of student in a course
1.652     albertel 2708: sub devalidate_getsection_cache {
                   2709:     my ($udom,$unam,$courseid)=@_;
                   2710:     my $hashid="$udom:$unam:$courseid";
                   2711:     &devalidate_cache_new('getsection',$hashid);
                   2712: }
1.298     matthew  2713: 
1.815     albertel 2714: sub courseid_to_courseurl {
                   2715:     my ($courseid) = @_;
                   2716:     #already url style courseid
                   2717:     return $courseid if ($courseid =~ m{^/});
                   2718: 
                   2719:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2720: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2721: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2722: 	return "/$cdom/$cnum";
                   2723:     }
                   2724: 
                   2725:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2726:     if (exists($courseinfo{'num'})) {
                   2727: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2728:     }
                   2729: 
                   2730:     return undef;
                   2731: }
                   2732: 
1.298     matthew  2733: sub getsection {
                   2734:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2735:     my $cachetime=1800;
1.551     albertel 2736: 
                   2737:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2738:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2739:     if (defined($cached)) { return $result; }
                   2740: 
1.298     matthew  2741:     my %Pending; 
                   2742:     my %Expired;
                   2743:     #
                   2744:     # Each role can either have not started yet (pending), be active, 
                   2745:     #    or have expired.
                   2746:     #
                   2747:     # If there is an active role, we are done.
                   2748:     #
                   2749:     # If there is more than one role which has not started yet, 
                   2750:     #     choose the one which will start sooner
                   2751:     # If there is one role which has not started yet, return it.
                   2752:     #
                   2753:     # If there is more than one expired role, choose the one which ended last.
                   2754:     # If there is a role which has expired, return it.
                   2755:     #
1.815     albertel 2756:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2757:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2758:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2759:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2760:         my $section=$1;
                   2761:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2762:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2763:         my $now=time;
1.548     albertel 2764:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2765:             $Expired{$end}=$section;
                   2766:             next;
                   2767:         }
1.548     albertel 2768:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2769:             $Pending{$start}=$section;
                   2770:             next;
                   2771:         }
1.599     albertel 2772:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2773:     }
                   2774:     #
                   2775:     # Presumedly there will be few matching roles from the above
                   2776:     # loop and the sorting time will be negligible.
                   2777:     if (scalar(keys(%Pending))) {
                   2778:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2779:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2780:     } 
                   2781:     if (scalar(keys(%Expired))) {
                   2782:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2783:         my $time = pop(@sorted);
1.599     albertel 2784:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2785:     }
1.599     albertel 2786:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2787: }
1.70      www      2788: 
1.599     albertel 2789: sub save_cache {
                   2790:     &purge_remembered();
1.722     albertel 2791:     #&Apache::loncommon::validate_page();
1.620     albertel 2792:     undef(%env);
1.780     albertel 2793:     undef($env_loaded);
1.599     albertel 2794: }
1.452     albertel 2795: 
1.599     albertel 2796: my $to_remember=-1;
                   2797: my %remembered;
                   2798: my %accessed;
                   2799: my $kicks=0;
                   2800: my $hits=0;
1.849     albertel 2801: sub make_key {
                   2802:     my ($name,$id) = @_;
1.872     albertel 2803:     if (length($id) > 65 
                   2804: 	&& length(&escape($id)) > 200) {
                   2805: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2806:     }
1.849     albertel 2807:     return &escape($name.':'.$id);
                   2808: }
                   2809: 
1.599     albertel 2810: sub devalidate_cache_new {
                   2811:     my ($name,$id,$debug) = @_;
                   2812:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2813:     my $remembered_id=$name.':'.$id;
1.849     albertel 2814:     $id=&make_key($name,$id);
1.599     albertel 2815:     $memcache->delete($id);
1.1172.2.81  raeburn  2816:     delete($remembered{$remembered_id});
                   2817:     delete($accessed{$remembered_id});
1.599     albertel 2818: }
                   2819: 
                   2820: sub is_cached_new {
                   2821:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2822:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2823:                                      # keys in %remembered hash, which persists for
                   2824:                                      # duration of request (no restriction on key length).
                   2825:     if (exists($remembered{$remembered_id})) {
                   2826: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2827: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2828: 	$hits++;
1.1172.2.81  raeburn  2829: 	return ($remembered{$remembered_id},1);
1.599     albertel 2830:     }
1.1172.2.81  raeburn  2831:     $id=&make_key($name,$id);
1.599     albertel 2832:     my $value = $memcache->get($id);
                   2833:     if (!(defined($value))) {
                   2834: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2835: 	return (undef,undef);
1.416     albertel 2836:     }
1.599     albertel 2837:     if ($value eq '__undef__') {
                   2838: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2839: 	$value=undef;
                   2840:     }
1.1172.2.81  raeburn  2841:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2842:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2843:     return ($value,1);
                   2844: }
                   2845: 
                   2846: sub do_cache_new {
                   2847:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2848:     my $remembered_id=$name.':'.$id;
1.849     albertel 2849:     $id=&make_key($name,$id);
1.599     albertel 2850:     my $setvalue=$value;
                   2851:     if (!defined($setvalue)) {
                   2852: 	$setvalue='__undef__';
                   2853:     }
1.623     albertel 2854:     if (!defined($time) ) {
                   2855: 	$time=600;
                   2856:     }
1.599     albertel 2857:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2858:     my $result = $memcache->set($id,$setvalue,$time);
                   2859:     if (! $result) {
1.872     albertel 2860: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2861: 	$memcache->disconnect_all();
1.872     albertel 2862:     }
1.600     albertel 2863:     # need to make a copy of $value
1.1172.2.81  raeburn  2864:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2865:     return $value;
                   2866: }
                   2867: 
                   2868: sub make_room {
1.1172.2.81  raeburn  2869:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2870: 
1.1172.2.81  raeburn  2871:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2872:                                     : $value;
1.599     albertel 2873:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2874:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2875:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2876:     my $to_kick;
                   2877:     my $max_time=0;
                   2878:     foreach my $other (keys(%accessed)) {
                   2879: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2880: 	    $to_kick=$other;
                   2881: 	    $max_time=&tv_interval($accessed{$other});
                   2882: 	}
                   2883:     }
                   2884:     delete($remembered{$to_kick});
                   2885:     delete($accessed{$to_kick});
                   2886:     $kicks++;
                   2887:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2888:     return;
                   2889: }
                   2890: 
1.599     albertel 2891: sub purge_remembered {
1.604     albertel 2892:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2893:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2894:     undef(%remembered);
                   2895:     undef(%accessed);
1.428     albertel 2896: }
1.70      www      2897: # ------------------------------------- Read an entry from a user's environment
                   2898: 
                   2899: sub userenvironment {
                   2900:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2901:     my $items;
                   2902:     foreach my $item (@what) {
                   2903:         $items.=&escape($item).'&';
                   2904:     }
                   2905:     $items=~s/\&$//;
1.70      www      2906:     my %returnhash=();
1.1009    raeburn  2907:     my $uhome = &homeserver($unam,$udom);
                   2908:     unless ($uhome eq 'no_host') {
                   2909:         my @answer=split(/\&/, 
                   2910:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2911:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2912:             return %returnhash;
                   2913:         }
1.1009    raeburn  2914:         my $i;
                   2915:         for ($i=0;$i<=$#what;$i++) {
                   2916: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2917:         }
1.70      www      2918:     }
                   2919:     return %returnhash;
1.1       albertel 2920: }
                   2921: 
1.617     albertel 2922: # ---------------------------------------------------------- Get a studentphoto
                   2923: sub studentphoto {
                   2924:     my ($udom,$unam,$ext) = @_;
                   2925:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2926:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2927:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2928:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2929:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2930:             } else {
                   2931:                 my ($result,$perm_reqd)=
1.707     albertel 2932: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2933:                 if ($result eq 'ok') {
                   2934:                     if (!($perm_reqd eq 'yes')) {
                   2935:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2936:                     }
                   2937:                 }
                   2938:             }
                   2939:         }
                   2940:     } else {
                   2941:         my ($result,$perm_reqd) = 
1.707     albertel 2942: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2943:         if ($result eq 'ok') {
                   2944:             if (!($perm_reqd eq 'yes')) {
                   2945:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2946:             }
                   2947:         }
                   2948:     }
                   2949:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2950: }
                   2951: 
                   2952: sub retrievestudentphoto {
                   2953:     my ($udom,$unam,$ext,$type) = @_;
                   2954:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2955:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2956:     if ($ret eq 'ok') {
                   2957:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2958:         if ($type eq 'thumbnail') {
                   2959:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2960:         }
                   2961:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2962:         return $tokenurl;
                   2963:     } else {
                   2964:         if ($type eq 'thumbnail') {
                   2965:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2966:         } else { 
                   2967:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2968:         }
1.617     albertel 2969:     }
                   2970: }
                   2971: 
1.263     www      2972: # -------------------------------------------------------------------- New chat
                   2973: 
                   2974: sub chatsend {
1.724     raeburn  2975:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2976:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2977:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2978:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2979:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2980: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2981: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2982: }
                   2983: 
                   2984: # ------------------------------------------ Find current version of a resource
                   2985: 
                   2986: sub getversion {
                   2987:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2988:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2989:     return &currentversion(&filelocation('',$fname));
                   2990: }
                   2991: 
                   2992: sub currentversion {
                   2993:     my $fname=shift;
                   2994:     my $author=$fname;
                   2995:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2996:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2997:     my $home=&homeserver($uname,$udom);
1.292     www      2998:     if ($home eq 'no_host') { 
                   2999:         return -1; 
                   3000:     }
1.1112    www      3001:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3002:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3003: 	return -1;
                   3004:     }
1.1112    www      3005:     return $answer;
1.263     www      3006: }
                   3007: 
1.1111    www      3008: #
                   3009: # Return special version number of resource if set by override, empty otherwise
                   3010: #
                   3011: sub usedversion {
                   3012:     my $fname=shift;
                   3013:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3014:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3015:     if ($urlversion) { return $urlversion; }
                   3016:     return '';
                   3017: }
                   3018: 
1.1       albertel 3019: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3020: 
1.1       albertel 3021: sub subscribe {
                   3022:     my $fname=shift;
1.761     raeburn  3023:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3024:     $fname=~s/[\n\r]//g;
1.1       albertel 3025:     my $author=$fname;
                   3026:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3027:     my ($udom,$uname)=split(/\//,$author);
                   3028:     my $home=homeserver($uname,$udom);
1.335     albertel 3029:     if ($home eq 'no_host') {
                   3030:         return 'not_found';
1.1       albertel 3031:     }
                   3032:     my $answer=reply("sub:$fname",$home);
1.64      www      3033:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3034: 	$answer.=' by '.$home;
                   3035:     }
1.1       albertel 3036:     return $answer;
                   3037: }
                   3038:     
1.8       www      3039: # -------------------------------------------------------------- Replicate file
                   3040: 
                   3041: sub repcopy {
                   3042:     my $filename=shift;
1.23      www      3043:     $filename=~s/\/+/\//g;
1.1142    raeburn  3044:     my $londocroot = $perlvar{'lonDocRoot'};
                   3045:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3046:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3047:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3048: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3049: 	return &repcopy_userfile($filename);
                   3050:     }
1.532     albertel 3051:     $filename=~s/[\n\r]//g;
1.8       www      3052:     my $transname="$filename.in.transfer";
1.828     www      3053: # FIXME: this should flock
1.607     raeburn  3054:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3055:     my $remoteurl=subscribe($filename);
1.64      www      3056:     if ($remoteurl =~ /^con_lost by/) {
                   3057: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3058:            return 'unavailable';
1.8       www      3059:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3060: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3061: 	   return 'not_found';
1.64      www      3062:     } elsif ($remoteurl =~ /^rejected by/) {
                   3063: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3064:            return 'forbidden';
1.20      www      3065:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3066:            return 'ok';
1.8       www      3067:     } else {
1.290     www      3068:         my $author=$filename;
                   3069:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3070:         my ($udom,$uname)=split(/\//,$author);
                   3071:         my $home=homeserver($uname,$udom);
                   3072:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3073:            my @parts=split(/\//,$filename);
                   3074:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3075:            if ($path ne "$londocroot/res") {
1.8       www      3076:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3077: 	       return 'bad_request';
1.8       www      3078:            }
                   3079:            my $count;
                   3080:            for ($count=5;$count<$#parts;$count++) {
                   3081:                $path.="/$parts[$count]";
                   3082:                if ((-e $path)!=1) {
                   3083: 		   mkdir($path,0777);
                   3084:                }
                   3085:            }
                   3086:            my $ua=new LWP::UserAgent;
                   3087:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3088:            my $response=$ua->request($request,$transname);
                   3089:            if ($response->is_error()) {
                   3090: 	       unlink($transname);
                   3091:                my $message=$response->status_line;
1.672     albertel 3092:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3093:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3094:                return 'unavailable';
1.8       www      3095:            } else {
1.16      www      3096: 	       if ($remoteurl!~/\.meta$/) {
                   3097:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3098:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3099:                   if ($mresponse->is_error()) {
                   3100: 		      unlink($filename.'.meta');
                   3101:                       &logthis(
1.672     albertel 3102:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3103:                   }
                   3104: 	       }
1.8       www      3105:                rename($transname,$filename);
1.607     raeburn  3106:                return 'ok';
1.8       www      3107:            }
1.290     www      3108:        }
1.8       www      3109:     }
1.330     www      3110: }
                   3111: 
1.1172.2.118.  .5(raebu 3112:20): # ------------------------------------------------- Unsubscribe from a resource
                   3113:20): 
                   3114:20): sub unsubscribe {
                   3115:20):     my ($fname) = @_;
                   3116:20):     my $answer;
                   3117:20):     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3118:20):     $fname=~s/[\n\r]//g;
                   3119:20):     my $author=$fname;
                   3120:20):     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3121:20):     my ($udom,$uname)=split(/\//,$author);
                   3122:20):     my $home=homeserver($uname,$udom);
                   3123:20):     if ($home eq 'no_host') {
                   3124:20):         $answer = 'no_host';
                   3125:20):     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3126:20):         $answer = 'home';
                   3127:20):     } else {
          .7(raebu 3128:20):         $answer = reply("unsub:$fname",$home);
          .5(raebu 3129:20):     }
                   3130:20):     return $answer;
                   3131:20): }
                   3132:20): 
1.330     www      3133: # ------------------------------------------------ Get server side include body
                   3134: sub ssi_body {
1.381     albertel 3135:     my ($filelink,%form)=@_;
1.606     matthew  3136:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3137:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3138:     }
1.953     www      3139:     my $output='';
                   3140:     my $response;
1.980     raeburn  3141:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3142:        ($output,$response)=&externalssi($filelink);
1.953     www      3143:     } else {
1.1004    droeschl 3144:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3145:        $filelink .= 'inhibitmenu=yes';
1.953     www      3146:        ($output,$response)=&ssi($filelink,%form);
                   3147:     }
1.778     albertel 3148:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3149:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3150:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3151:     if (wantarray) {
                   3152:         return ($output, $response);
                   3153:     } else {
                   3154:         return $output;
                   3155:     }
1.8       www      3156: }
                   3157: 
1.15      www      3158: # --------------------------------------------------------- Server Side Include
                   3159: 
1.782     albertel 3160: sub absolute_url {
                   3161:     my ($host_name) = @_;
                   3162:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3163:     if ($host_name eq '') {
                   3164: 	$host_name = $ENV{'SERVER_NAME'};
                   3165:     }
                   3166:     return $protocol.$host_name;
                   3167: }
                   3168: 
1.942     foxr     3169: #
                   3170: #   Server side include.
                   3171: # Parameters:
                   3172: #  fn     Possibly encrypted resource name/id.
                   3173: #  form   Hash that describes how the rendering should be done
                   3174: #         and other things.
1.944     foxr     3175: # Returns:
1.950     raeburn  3176: #   Scalar context: The content of the response.
                   3177: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3178: #     
1.15      www      3179: sub ssi {
                   3180: 
1.944     foxr     3181:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3182:     my ($request,$response);
1.711     albertel 3183: 
                   3184:     $form{'no_update_last_known'}=1;
1.895     albertel 3185:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3186:     if (%form) {
1.782     albertel 3187:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3188:       $request->content(join('&',map {
                   3189:             my $name = escape($_);
                   3190:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3191:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3192:             : &escape($form{$_}) );
                   3193:         } keys(%form)));
1.23      www      3194:     } else {
1.782     albertel 3195:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3196:     }
                   3197: 
1.15      www      3198:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3199: 
1.1172.2.101  raeburn  3200:     if (($env{'request.course.id'}) &&
                   3201:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3202:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3203:         ($form{'grade_symb'} ne '') &&
                   3204:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3205:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3206:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3207:             my $ua=new LWP::UserAgent;
                   3208:             $ua->local_address('127.0.0.1');
                   3209:             $response = $ua->request($request);
                   3210:         } else {
                   3211:             {
                   3212:                 require LWP::Protocol::http;
                   3213:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3214:                 my $ua=new LWP::UserAgent;
                   3215:                 $response = $ua->request($request);
                   3216:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3217:             }
                   3218:         }
                   3219:     } else {
                   3220:         my $ua=new LWP::UserAgent;
                   3221:         $response = $ua->request($request);
                   3222:     }
1.944     foxr     3223:     if (wantarray) {
1.1172.2.3  raeburn  3224: 	return ($response->content, $response);
1.944     foxr     3225:     } else {
1.1172.2.3  raeburn  3226: 	return $response->content;
1.942     foxr     3227:     }
1.324     www      3228: }
                   3229: 
                   3230: sub externalssi {
                   3231:     my ($url)=@_;
                   3232:     my $ua=new LWP::UserAgent;
                   3233:     my $request=new HTTP::Request('GET',$url);
                   3234:     my $response=$ua->request($request);
1.954     raeburn  3235:     if (wantarray) {
                   3236:         return ($response->content, $response);
                   3237:     } else {
                   3238:         return $response->content;
                   3239:     }
1.15      www      3240: }
1.254     www      3241: 
1.1172.2.98  raeburn  3242: # If the local copy of a replicated resource is outdated, trigger a
                   3243: # connection from the homeserver to flush the delayed queue. If no update
                   3244: # happens, remove local copies of outdated resource (and corresponding
                   3245: # metadata file).
                   3246: 
                   3247: sub remove_stale_resfile {
                   3248:     my ($url) = @_;
                   3249:     my $removed;
                   3250:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3251:         my $audom = $1;
                   3252:         my $auname = $2;
                   3253:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3254:             my $homeserver = &homeserver($auname,$audom);
                   3255:             unless (($homeserver eq 'no_host') ||
                   3256:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3257:                 my $fname = &filelocation('',$url);
                   3258:                 if (-e $fname) {
                   3259:                     my $hostname = &hostname($homeserver);
                   3260:                     if ($hostname) {
1.1172.2.118.  .3(raebu 3261:20):                         my $protocol = $protocol{$homeserver};
                   3262:20):                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3263:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.118.  .3(raebu 3264:20):                         my $ua=new LWP::UserAgent;
                   3265:20):                         $ua->timeout(5);
1.1172.2.98  raeburn  3266:                         my $request=new HTTP::Request('HEAD',$uri);
                   3267:                         my $response=$ua->request($request);
                   3268:                         if ($response->is_success()) {
                   3269:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3270:                             my $locmodtime = (stat($fname))[9];
                   3271:                             if ($locmodtime < $remmodtime) {
                   3272:                                 my $stale;
                   3273:                                 my $answer = &reply('pong',$homeserver);
                   3274:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3275:                                     sleep(0.2);
                   3276:                                     $locmodtime = (stat($fname))[9];
                   3277:                                     if ($locmodtime < $remmodtime) {
                   3278:                                         my $posstransfer = $fname.'.in.transfer';
                   3279:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3280:                                             $removed = 1;
                   3281:                                         } else {
                   3282:                                             $stale = 1;
                   3283:                                         }
                   3284:                                     } else {
                   3285:                                         $removed = 1;
                   3286:                                     }
                   3287:                                 } else {
                   3288:                                     $stale = 1;
                   3289:                                 }
                   3290:                                 if ($stale) {
1.1172.2.118.  .5(raebu 3291:20):                                     if (unlink($fname)) {
                   3292:20):                                         if ($uri!~/\.meta$/) {
                   3293:20):                                             if (-e $fname.'.meta') {
                   3294:20):                                                 unlink($fname.'.meta');
                   3295:20):                                             }
                   3296:20):                                         }
                   3297:20):                                         my $unsubresult = &unsubscribe($fname);
                   3298:20):                                         unless ($unsubresult eq 'ok') {
                   3299:20):                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3300:20):                                         }
                   3301:20):                                         $removed = 1;
1.1172.2.98  raeburn  3302:                                     }
                   3303:                                 }
                   3304:                             }
                   3305:                         }
                   3306:                     }
                   3307:                 }
                   3308:             }
                   3309:         }
                   3310:     }
                   3311:     return $removed;
                   3312: }
                   3313: 
1.492     albertel 3314: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3315: 
                   3316: sub allowuploaded {
                   3317:     my ($srcurl,$url)=@_;
                   3318:     $url=&clutter(&declutter($url));
                   3319:     my $dir=$url;
                   3320:     $dir=~s/\/[^\/]+$//;
                   3321:     my %httpref=();
                   3322:     my $httpurl=&hreflocation('',$url);
                   3323:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3324:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3325: }
1.477     raeburn  3326: 
1.1172.2.13  raeburn  3327: #
                   3328: # Determine if the current user should be able to edit a particular resource,
                   3329: # when viewing in course context.
                   3330: # (a) When viewing resource used to determine if "Edit" item is included in
                   3331: #     Functions.
                   3332: # (b) When displaying folder contents in course editor, used to determine if
                   3333: #     "Edit" link will be displayed alongside resource.
                   3334: #
                   3335: #  input: six args -- filename (decluttered), course number, course domain,
                   3336: #                   url, symb (if registered) and group (if this is a group
                   3337: #                   item -- e.g., bulletin board, group page etc.).
                   3338: #  output: array of five scalars --
                   3339: #          $cfile -- url for file editing if editable on current server
                   3340: #          $home -- homeserver of resource (i.e., for author if published,
                   3341: #                                           or course if uploaded.).
                   3342: #          $switchserver --  1 if server switch will be needed.
                   3343: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3344: #          $forceview -- 1 if icon/link should be to go to view mode
                   3345: #
                   3346: 
                   3347: sub can_edit_resource {
                   3348:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3349:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3350: #
                   3351: # For aboutme pages user can only edit his/her own.
                   3352: #
                   3353:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3354:         my ($sdom,$sname) = ($1,$2);
                   3355:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3356:             $home = $env{'user.home'};
                   3357:             $cfile = $resurl;
                   3358:             if ($env{'form.forceedit'}) {
                   3359:                 $forceview = 1;
                   3360:             } else {
                   3361:                 $forceedit = 1;
                   3362:             }
                   3363:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3364:         } else {
                   3365:             return;
                   3366:         }
                   3367:     }
                   3368: 
                   3369:     if ($env{'request.course.id'}) {
                   3370:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3371:         if ($group ne '') {
                   3372: # if this is a group homepage or group bulletin board, check group privs
                   3373:             my $allowed = 0;
                   3374:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3375:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3376:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3377:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3378:                     $allowed = 1;
                   3379:                 }
                   3380:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3381:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3382:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3383:                     $allowed = 1;
                   3384:                 }
                   3385:             }
                   3386:             if ($allowed) {
                   3387:                 $home=&homeserver($cnum,$cdom);
                   3388:                 if ($env{'form.forceedit'}) {
                   3389:                     $forceview = 1;
                   3390:                 } else {
                   3391:                     $forceedit = 1;
                   3392:                 }
                   3393:                 $cfile = $resurl;
                   3394:             } else {
                   3395:                 return;
                   3396:             }
                   3397:         } else {
1.1172.2.15  raeburn  3398:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3399:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3400:                     return;
                   3401:                 }
                   3402:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3403: #
                   3404: # No edit allowed where CC has switched to student role.
                   3405: #
                   3406:                 return;
                   3407:             }
                   3408:         }
                   3409:     }
                   3410: 
                   3411:     if ($file ne '') {
                   3412:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3413:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3414:                 $uploaded = 1;
                   3415:                 $incourse = 1;
                   3416:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3417:                     $cfile = &hreflocation('',$file);
                   3418:                     if ($env{'form.forceedit'}) {
                   3419:                         $forceview = 1;
                   3420:                     } else {
                   3421:                         $forceedit = 1;
                   3422:                     }
                   3423:                 }
                   3424:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3425:                 $incourse = 1;
                   3426:                 if ($env{'form.forceedit'}) {
                   3427:                     $forceview = 1;
                   3428:                 } else {
                   3429:                     $forceedit = 1;
                   3430:                 }
                   3431:                 $cfile = $resurl;
                   3432:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3433:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3434:                     $incourse = 1;
                   3435:                     if ($env{'form.forceedit'}) {
                   3436:                         $forceview = 1;
                   3437:                     } else {
                   3438:                         $forceedit = 1;
                   3439:                     }
                   3440:                     $cfile = $resurl;
                   3441:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3442:                     $incourse = 1;
                   3443:                     $cfile = $resurl.'/smpedit';
                   3444:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3445:                     $incourse = 1;
                   3446:                     if ($env{'form.forceedit'}) {
                   3447:                         $forceview = 1;
                   3448:                     } else {
                   3449:                         $forceedit = 1;
                   3450:                     }
                   3451:                     $cfile = $resurl;
1.1172.2.118.  .5(raebu 3452:20):                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3453:20):                     my ($map,$id,$res) = &decode_symb($symb);
                   3454:20):                     if ($map =~ /\.page$/) {
                   3455:20):                         $incourse = 1;
                   3456:20):                         if ($env{'form.forceedit'}) {
                   3457:20):                             $forceview = 1;
                   3458:20):                             $cfile = $map;
                   3459:20):                         } else {
                   3460:20):                             $forceedit = 1;
                   3461:20):                             $cfile =  '/adm/wrapper'.$resurl;
                   3462:20):                         }
                   3463:20):                     }
          .1(raebu 3464:20):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3465:20):                     $incourse = 1;
                   3466:20):                     if ($env{'form.forceedit'}) {
                   3467:20):                         $forceview = 1;
                   3468:20):                     } else {
                   3469:20):                         $forceedit = 1;
                   3470:20):                     }
                   3471:20):                     $cfile = $resurl;
1.1172.2.15  raeburn  3472:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3473:                     $incourse = 1;
                   3474:                     if ($env{'form.forceedit'}) {
                   3475:                         $forceview = 1;
                   3476:                     } else {
                   3477:                         $forceedit = 1;
                   3478:                     }
                   3479:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3480:                 }
                   3481:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3482:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3483:                 if (&is_on_map($template)) {
                   3484:                     $incourse = 1;
                   3485:                     $forceview = 1;
                   3486:                     $cfile = $template;
                   3487:                 }
                   3488:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3489:                 $incourse = 1;
                   3490:                 if ($env{'form.forceedit'}) {
                   3491:                     $forceview = 1;
                   3492:                 } else {
                   3493:                     $forceedit = 1;
                   3494:                 }
                   3495:                 $cfile = $resurl;
1.1172.2.118.  .1(raebu 3496:20):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3497:20):                 $incourse = 1;
                   3498:20):                 if ($env{'form.forceedit'}) {
                   3499:20):                     $forceview = 1;
                   3500:20):                 } else {
                   3501:20):                     $forceedit = 1;
                   3502:20):                 }
                   3503:20):                 $cfile = $resurl;
1.1172.2.13  raeburn  3504:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3505:                 $incourse = 1;
                   3506:                 $forceview = 1;
                   3507:                 if ($symb) {
                   3508:                     my ($map,$id,$res)=&decode_symb($symb);
                   3509:                     $env{'request.symb'} = $symb;
                   3510:                     $cfile = &clutter($res);
                   3511:                 } else {
                   3512:                     $cfile = $env{'form.suppurl'};
1.1172.2.118.  .1(raebu 3513:20):                     my $escfile = &unescape($cfile);
                   3514:20):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3515:20):                         $cfile = '/adm/wrapper'.$escfile;
                   3516:20):                     } else {
                   3517:20):                         $escfile =~ s{^http://}{};
                   3518:20):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3519:20):                     }
1.1172.2.13  raeburn  3520:                 }
1.1172.2.31  raeburn  3521:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3522:                 if ($env{'form.forceedit'}) {
                   3523:                     $forceview = 1;
                   3524:                 } else {
                   3525:                     $forceedit = 1;
                   3526:                 }
                   3527:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3528:             }
                   3529:         }
                   3530:         if ($uploaded || $incourse) {
                   3531:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3532:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3533:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3534:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3535:             # Check that the user has permission to edit this resource
                   3536:             my $setpriv = 1;
                   3537:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3538:             if (defined($cfudom)) {
                   3539:                 $home=&homeserver($cfuname,$cfudom);
                   3540:                 $cfile=$file;
                   3541:             }
                   3542:         }
                   3543:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3544:             (($home ne '') && ($home ne 'no_host'))) {
                   3545:             my @ids=&current_machine_ids();
                   3546:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3547:                 $switchserver=1;
                   3548:             }
                   3549:         }
                   3550:     }
                   3551:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3552: }
                   3553: 
                   3554: sub is_course_upload {
                   3555:     my ($file,$cnum,$cdom) = @_;
                   3556:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3557:     $uploadpath =~ s{^\/}{};
                   3558:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3559:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3560:         return 1;
                   3561:     }
                   3562:     return;
                   3563: }
                   3564: 
                   3565: sub in_course {
                   3566:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3567:     if ($hideprivileged) {
                   3568:         my $skipuser;
1.1172.2.23  raeburn  3569:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3570:         my @possdoms = ($cdom);
                   3571:         if ($coursehash{'checkforpriv'}) {
                   3572:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3573:         }
                   3574:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3575:             $skipuser = 1;
                   3576:             if ($coursehash{'nothideprivileged'}) {
                   3577:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3578:                     my $user;
                   3579:                     if ($item =~ /:/) {
                   3580:                         $user = $item;
                   3581:                     } else {
                   3582:                         $user = join(':',split(/[\@]/,$item));
                   3583:                     }
                   3584:                     if ($user eq $uname.':'.$udom) {
                   3585:                         undef($skipuser);
                   3586:                         last;
                   3587:                     }
                   3588:                 }
                   3589:             }
                   3590:             if ($skipuser) {
                   3591:                 return 0;
                   3592:             }
                   3593:         }
                   3594:     }
                   3595:     $type ||= 'any';
                   3596:     if (!defined($cdom) || !defined($cnum)) {
                   3597:         my $cid  = $env{'request.course.id'};
                   3598:         $cdom = $env{'course.'.$cid.'.domain'};
                   3599:         $cnum = $env{'course.'.$cid.'.num'};
                   3600:     }
                   3601:     my $typesref;
                   3602:     if (($type eq 'any') || ($type eq 'all')) {
                   3603:         $typesref = ['active','previous','future'];
                   3604:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3605:         $typesref = [$type];
                   3606:     }
                   3607:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3608:                               $typesref,undef,[$cdom]);
                   3609:     my ($tmp) = keys(%roles);
                   3610:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3611:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3612:     if (@course_roles > 0) {
                   3613:         return 1;
                   3614:     }
                   3615:     return 0;
                   3616: }
                   3617: 
1.478     albertel 3618: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3619: # input: action, courseID, current domain, intended
1.637     raeburn  3620: #        path to file, source of file, instruction to parse file for objects,
                   3621: #        ref to hash for embedded objects,
                   3622: #        ref to hash for codebase of java objects.
1.1095    raeburn  3623: #        reference to scalar to accommodate mime type determined
                   3624: #          from File::MMagic if $parser = parse.
1.637     raeburn  3625: #
1.485     raeburn  3626: # output: url to file (if action was uploaddoc), 
                   3627: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3628: #
1.478     albertel 3629: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3630: # course.
1.477     raeburn  3631: #
1.478     albertel 3632: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3633: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3634: #          course's home server.
1.477     raeburn  3635: #
1.478     albertel 3636: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3637: #          be copied from $source (current location) to 
                   3638: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3639: #         and will then be copied to
                   3640: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3641: #         course's home server.
1.485     raeburn  3642: #
1.481     raeburn  3643: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3644: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3645: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3646: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3647: #         in course's home server.
1.637     raeburn  3648: #
1.477     raeburn  3649: 
                   3650: sub process_coursefile {
1.1095    raeburn  3651:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3652:         $mimetype)=@_;
1.477     raeburn  3653:     my $fetchresult;
1.638     albertel 3654:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3655:     if ($action eq 'propagate') {
1.638     albertel 3656:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3657: 			     $home);
1.481     raeburn  3658:     } else {
1.477     raeburn  3659:         my $fpath = '';
                   3660:         my $fname = $file;
1.478     albertel 3661:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3662:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3663:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3664:         if ($action eq 'copy') {
                   3665:             if ($source eq '') {
                   3666:                 $fetchresult = 'no source file';
                   3667:                 return $fetchresult;
                   3668:             } else {
                   3669:                 my $destination = $filepath.'/'.$fname;
                   3670:                 rename($source,$destination);
                   3671:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3672:                                  $home);
1.481     raeburn  3673:             }
                   3674:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3675:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3676:             print $fh $env{'form.'.$source};
1.481     raeburn  3677:             close($fh);
1.637     raeburn  3678:             if ($parser eq 'parse') {
1.1024    raeburn  3679:                 my $mm = new File::MMagic;
1.1095    raeburn  3680:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3681:                 if ($type eq 'text/html') {
1.1024    raeburn  3682:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3683:                     unless ($parse_result eq 'ok') {
                   3684:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3685:                     }
1.637     raeburn  3686:                 }
1.1095    raeburn  3687:                 if (ref($mimetype)) {
                   3688:                     $$mimetype = $type;
                   3689:                 } 
1.637     raeburn  3690:             }
1.477     raeburn  3691:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3692:                                  $home);
1.481     raeburn  3693:             if ($fetchresult eq 'ok') {
                   3694:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3695:             } else {
                   3696:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3697:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3698:                 return '/adm/notfound.html';
                   3699:             }
1.477     raeburn  3700:         }
                   3701:     }
1.485     raeburn  3702:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3703:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3704:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3705:     }
                   3706:     return $fetchresult;
                   3707: }
                   3708: 
1.637     raeburn  3709: sub build_filepath {
                   3710:     my ($fpath) = @_;
                   3711:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3712:     unless ($fpath eq '') {
                   3713:         my @parts=split('/',$fpath);
                   3714:         foreach my $part (@parts) {
                   3715:             $filepath.= '/'.$part;
                   3716:             if ((-e $filepath)!=1) {
                   3717:                 mkdir($filepath,0777);
                   3718:             }
                   3719:         }
                   3720:     }
                   3721:     return $filepath;
                   3722: }
                   3723: 
                   3724: sub store_edited_file {
1.638     albertel 3725:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3726:     my $file = $primary_url;
                   3727:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3728:     my $fpath = '';
                   3729:     my $fname = $file;
                   3730:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3731:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3732:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3733:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3734:     print $fh $content;
                   3735:     close($fh);
1.638     albertel 3736:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3737:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3738: 			  $home);
1.637     raeburn  3739:     if ($$fetchresult eq 'ok') {
                   3740:         return '/uploaded/'.$fpath.'/'.$fname;
                   3741:     } else {
1.638     albertel 3742:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3743: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3744:         return '/adm/notfound.html';
                   3745:     }
                   3746: }
                   3747: 
1.531     albertel 3748: sub clean_filename {
1.831     albertel 3749:     my ($fname,$args)=@_;
1.315     www      3750: # Replace Windows backslashes by forward slashes
1.257     www      3751:     $fname=~s/\\/\//g;
1.831     albertel 3752:     if (!$args->{'keep_path'}) {
                   3753:         # Get rid of everything but the actual filename
                   3754: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3755:     }
1.315     www      3756: # Replace spaces by underscores
                   3757:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3758: # Transliterate non-ascii text to ascii
                   3759:     my $lang = &Apache::lonlocal::current_language();
                   3760:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3761: # Replace all other weird characters by nothing
1.831     albertel 3762:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3763: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3764: # numbers
                   3765:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3766:     return $fname;
                   3767: }
1.1172.2.110  raeburn  3768: 
1.1051    raeburn  3769: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3770: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3771: # image with the same aspect ratio as the original, but with dimensions which do 
                   3772: # not exceed $resizewidth and $resizeheight.
                   3773:  
1.984     neumanie 3774: sub resizeImage {
1.1051    raeburn  3775:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3776:     my $ima = Image::Magick->new;
                   3777:     my $resized;
                   3778:     if (-e $img_path) {
                   3779:         $ima->Read($img_path);
                   3780:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3781:             my $width = $ima->Get('width');
                   3782:             my $height = $ima->Get('height');
                   3783:             if ($width > $resizewidth) {
                   3784: 	        my $factor = $width/$resizewidth;
                   3785:                 my $newheight = $height/$factor;
                   3786:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3787:                 $resized = 1;
                   3788:             }
                   3789:         }
                   3790:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3791:             my $width = $ima->Get('width');
                   3792:             my $height = $ima->Get('height');
                   3793:             if ($height > $resizeheight) {
                   3794:                 my $factor = $height/$resizeheight;
                   3795:                 my $newwidth = $width/$factor;
                   3796:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3797:                 $resized = 1;
                   3798:             }
                   3799:         }
                   3800:         if ($resized) {
                   3801:             $ima->Write($img_path);
                   3802:         }
                   3803:     }
                   3804:     return;
1.977     amueller 3805: }
                   3806: 
1.608     albertel 3807: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3808: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3809: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3810: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3811: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3812: #                   if 'coursedoc': upload to the current course
                   3813: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3814: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3815: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3816: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3817: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3818: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3819: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3820: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3821: #        $allfiles - reference to hash for embedded objects
                   3822: #        $codebase - reference to hash for codebase of java objects
                   3823: #        $desuname - username for permanent storage of uploaded file
                   3824: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3825: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3826: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3827: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3828: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3829: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3830: #                    from File::MMagic.
1.858     raeburn  3831: # 
1.686     albertel 3832: # output: url of file in userspace, or error: <message> 
                   3833: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3834: 
1.531     albertel 3835: sub userfileupload {
1.1090    raeburn  3836:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3837:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3838:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3839:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3840:     $fname=&clean_filename($fname);
1.1090    raeburn  3841:     # See if there is anything left
1.257     www      3842:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3843:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3844:     if ($fname =~ /^\./) {
                   3845:         my ($s,$usec) = &gettimeofday();
                   3846:         while (length($usec) < 6) {
                   3847:             $usec = '0'.$usec;
                   3848:         }
                   3849:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3850:     }
1.1090    raeburn  3851:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3852:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3853:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3854:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3855:         my $now = time;
1.1090    raeburn  3856:         my $filepath;
1.1095    raeburn  3857:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3858:              $filepath = 'tmp/helprequests/'.$now;
                   3859:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3860:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3861:                          '_'.$env{'user.domain'}.'/pending';
                   3862:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3863:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3864:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3865:                 $docudom = $destudom;
                   3866:             } else {
                   3867:                 $docudom = $env{'user.domain'};
                   3868:             }
1.1172.2.96  raeburn  3869:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3870:                 $docuname = $destuname;
                   3871:             } else {
                   3872:                 $docuname = $env{'user.name'};
                   3873:             }
                   3874:             if (exists($env{'form.group'})) {
                   3875:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3876:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3877:             }
                   3878:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3879:             if ($context eq 'canceloverwrite') {
                   3880:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3881:                 if (-e  $tempfile) {
                   3882:                     my @info = stat($tempfile);
                   3883:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3884:                         unlink($tempfile);
                   3885:                     }
                   3886:                 }
                   3887:                 return;
1.523     raeburn  3888:             }
                   3889:         }
1.1090    raeburn  3890:         # Create the directory if not present
1.741     raeburn  3891:         my @parts=split(/\//,$filepath);
                   3892:         my $fullpath = $perlvar{'lonDaemons'};
                   3893:         for (my $i=0;$i<@parts;$i++) {
                   3894:             $fullpath .= '/'.$parts[$i];
                   3895:             if ((-e $fullpath)!=1) {
                   3896:                 mkdir($fullpath,0777);
                   3897:             }
                   3898:         }
1.1172.2.96  raeburn  3899:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3900:         print $fh $env{'form.'.$formname};
                   3901:         close($fh);
1.1090    raeburn  3902:         if ($context eq 'existingfile') {
                   3903:             my @info = stat($fullpath.'/'.$fname);
                   3904:             return ($fullpath.'/'.$fname,$info[9]);
                   3905:         } else {
                   3906:             return $fullpath.'/'.$fname;
                   3907:         }
1.523     raeburn  3908:     }
1.995     raeburn  3909:     if ($subdir eq 'scantron') {
                   3910:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3911:     } else {
1.995     raeburn  3912:         $fname="$subdir/$fname";
                   3913:     }
1.1090    raeburn  3914:     if ($context eq 'coursedoc') {
1.638     albertel 3915: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3916: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3917:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3918:             return &finishuserfileupload($docuname,$docudom,
                   3919: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3920: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3921:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3922:         } else {
1.1172.2.21  raeburn  3923:             if ($env{'form.folder'}) {
                   3924:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3925:             }
1.638     albertel 3926:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3927: 				       $fname,$formname,$parser,
1.1095    raeburn  3928: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3929:         }
1.719     banghart 3930:     } elsif (defined($destuname)) {
                   3931:         my $docuname=$destuname;
                   3932:         my $docudom=$destudom;
1.860     raeburn  3933: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3934: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3935:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3936:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3937:     } else {
1.638     albertel 3938:         my $docuname=$env{'user.name'};
                   3939:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3940:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3941:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3942:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3943:         }
1.860     raeburn  3944: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3945: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3946:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3947:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3948:     }
1.271     www      3949: }
                   3950: 
                   3951: sub finishuserfileupload {
1.860     raeburn  3952:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3953:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3954:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3955:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3956:   
1.860     raeburn  3957:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3958:     $file=$fname;
                   3959:     if ($fname=~m|/|) {
                   3960:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3961: 	$path.=$fnamepath.'/';
                   3962:     }
1.259     www      3963:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3964:     my $count;
                   3965:     for ($count=4;$count<=$#parts;$count++) {
                   3966:         $filepath.="/$parts[$count]";
                   3967:         if ((-e $filepath)!=1) {
                   3968: 	    mkdir($filepath,0777);
                   3969:         }
                   3970:     }
1.984     neumanie 3971: 
1.258     www      3972: # Save the file
                   3973:     {
1.1172.2.96  raeburn  3974: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3975: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3976: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3977: 	    return '/adm/notfound.html';
                   3978: 	}
1.1090    raeburn  3979:         if ($context eq 'overwrite') {
1.1117    foxr     3980:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3981:             my $target = $filepath.'/'.$file;
                   3982:             if (-e $source) {
                   3983:                 my @info = stat($source);
                   3984:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3985:                     unless (&File::Copy::move($source,$target)) {
                   3986:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3987:                         return "Moving from $source failed";
                   3988:                     }
                   3989:                 } else {
                   3990:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3991:                 }
                   3992:             } else {
                   3993:                 return "Temporary file: $source missing";
                   3994:             }
                   3995:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3996: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3997: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3998: 	    return '/adm/notfound.html';
                   3999: 	}
1.570     albertel 4000: 	close(FH);
1.1051    raeburn  4001:         if ($resizewidth && $resizeheight) {
                   4002:             my $mm = new File::MMagic;
                   4003:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4004:             if ($mime_type =~ m{^image/}) {
                   4005: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4006:             }  
1.977     amueller 4007: 	}
1.258     www      4008:     }
1.1152    raeburn  4009:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4010:         if (ref($mimetype)) {
                   4011:             if ($$mimetype eq '') {
                   4012:                 my $mm = new File::MMagic;
                   4013:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4014:                 $$mimetype = $type;
                   4015:             }
                   4016:         }
                   4017:     }
1.1172.2.109  raeburn  4018:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4019:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4020:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4021:                                                        $allfiles,$codebase);
                   4022:             unless ($parse_result eq 'ok') {
                   4023:                 &logthis('Failed to parse '.$filepath.$file.
                   4024: 	   	         ' for embedded media: '.$parse_result); 
                   4025:             }
1.637     raeburn  4026:         }
1.1172.2.109  raeburn  4027:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4028:         my $format = $env{'form.scantron_format'};
                   4029:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4030:     }
1.860     raeburn  4031:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4032:         my $input = $filepath.'/'.$file;
                   4033:         my $output = $filepath.'/'.'tn-'.$file;
                   4034:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4035:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4036:         system({$args[0]} @args);
1.860     raeburn  4037:         if (-e $filepath.'/'.'tn-'.$file) {
                   4038:             $fetchthumb  = 1; 
                   4039:         }
                   4040:     }
1.858     raeburn  4041:  
1.259     www      4042: # Notify homeserver to grep it
                   4043: #
1.984     neumanie 4044:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4045:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4046:     if ($fetchresult eq 'ok') {
1.860     raeburn  4047:         if ($fetchthumb) {
                   4048:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4049:             if ($thumbresult ne 'ok') {
                   4050:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4051:                          $docuhome.': '.$thumbresult);
                   4052:             }
                   4053:         }
1.259     www      4054: #
1.258     www      4055: # Return the URL to it
1.494     albertel 4056:         return '/uploaded/'.$path.$file;
1.263     www      4057:     } else {
1.494     albertel 4058:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4059: 		 ': '.$fetchresult);
1.263     www      4060:         return '/adm/notfound.html';
1.858     raeburn  4061:     }
1.493     albertel 4062: }
                   4063: 
1.637     raeburn  4064: sub extract_embedded_items {
1.961     raeburn  4065:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4066:     my @state = ();
1.1164    raeburn  4067:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4068:     my %javafiles = (
                   4069:                       codebase => '',
                   4070:                       code => '',
                   4071:                       archive => ''
                   4072:                     );
                   4073:     my %mediafiles = (
                   4074:                       src => '',
                   4075:                       movie => '',
                   4076:                      );
1.648     raeburn  4077:     my $p;
                   4078:     if ($content) {
                   4079:         $p = HTML::LCParser->new($content);
                   4080:     } else {
1.961     raeburn  4081:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4082:     }
1.641     albertel 4083:     while (my $t=$p->get_token()) {
1.640     albertel 4084: 	if ($t->[0] eq 'S') {
                   4085: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4086: 	    push(@state, $tagname);
1.648     raeburn  4087:             if (lc($tagname) eq 'allow') {
                   4088:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4089:             }
1.640     albertel 4090: 	    if (lc($tagname) eq 'img') {
                   4091: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4092: 	    }
1.886     albertel 4093: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4094:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4095: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4096:                 }
1.886     albertel 4097: 	    }
1.645     raeburn  4098:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4099:                 my $src;
1.645     raeburn  4100:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4101:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4102:                 } else {
1.1164    raeburn  4103:                     if ($attr->{'src'} ne '') {
                   4104:                         $src = $attr->{'src'};
                   4105:                         &add_filetype($allfiles,$src,'src');
                   4106:                     }
                   4107:                 }
                   4108:                 my $text = $p->get_trimmed_text();
                   4109:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4110:                     my @swfargs = split(/,/,$1);
                   4111:                     foreach my $item (@swfargs) {
                   4112:                         $item =~ s/["']//g;
                   4113:                         $item =~ s/^\s+//;
                   4114:                         $item =~ s/\s+$//;
                   4115:                     }
                   4116:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4117:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4118:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4119:                         } else {
                   4120:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4121:                         }
                   4122:                     }
1.645     raeburn  4123:                 }
                   4124:             }
                   4125:             if (lc($tagname) eq 'link') {
                   4126:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4127:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4128:                 }
                   4129:             }
1.640     albertel 4130: 	    if (lc($tagname) eq 'object' ||
                   4131: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4132: 		foreach my $item (keys(%javafiles)) {
                   4133: 		    $javafiles{$item} = '';
                   4134: 		}
1.1164    raeburn  4135:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4136:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4137:                 }
1.640     albertel 4138: 	    }
                   4139: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4140: 		my $name = lc($attr->{'name'});
                   4141: 		foreach my $item (keys(%javafiles)) {
                   4142: 		    if ($name eq $item) {
                   4143: 			$javafiles{$item} = $attr->{'value'};
                   4144: 			last;
                   4145: 		    }
                   4146: 		}
1.1164    raeburn  4147:                 my $pathfrom;
1.640     albertel 4148: 		foreach my $item (keys(%mediafiles)) {
                   4149: 		    if ($name eq $item) {
1.1164    raeburn  4150:                         $pathfrom = $attr->{'value'};
                   4151:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4152: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4153: 			last;
                   4154: 		    }
                   4155: 		}
1.1164    raeburn  4156:                 if ($name eq 'flashvars') {
                   4157:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4158:                 }
                   4159:                 if ($pathfrom ne '') {
                   4160:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4161:                                          $pathfrom);
                   4162:                 }
1.640     albertel 4163: 	    }
                   4164: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4165: 		foreach my $item (keys(%javafiles)) {
                   4166: 		    if ($attr->{$item}) {
                   4167: 			$javafiles{$item} = $attr->{$item};
                   4168: 			last;
                   4169: 		    }
                   4170: 		}
                   4171: 		foreach my $item (keys(%mediafiles)) {
                   4172: 		    if ($attr->{$item}) {
                   4173: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4174: 			last;
                   4175: 		    }
                   4176: 		}
1.1164    raeburn  4177:                 if (lc($tagname) eq 'embed') {
                   4178:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4179:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4180:                                              $attr->{'src'});
                   4181:                     }
                   4182:                 }
1.640     albertel 4183: 	    }
1.1172.2.35  raeburn  4184:             if (lc($tagname) eq 'iframe') {
                   4185:                 my $src = $attr->{'src'} ;
                   4186:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4187:                     &add_filetype($allfiles,$src,'src');
                   4188:                 } elsif ($src =~ m{^/}) {
                   4189:                     if ($env{'request.course.id'}) {
                   4190:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4191:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4192:                         my $url = &hreflocation('',$fullpath);
                   4193:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4194:                             my $relpath = $1;
                   4195:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4196:                                 &add_filetype($allfiles,$1,'src');
                   4197:                             }
                   4198:                         }
                   4199:                     }
                   4200:                 }
                   4201:             }
1.1164    raeburn  4202:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4203:                 pop(@state);
1.1164    raeburn  4204:             }
1.640     albertel 4205: 	} elsif ($t->[0] eq 'E') {
                   4206: 	    my ($tagname) = ($t->[1]);
                   4207: 	    if ($javafiles{'codebase'} ne '') {
                   4208: 		$javafiles{'codebase'} .= '/';
                   4209: 	    }  
                   4210: 	    if (lc($tagname) eq 'applet' ||
                   4211: 		lc($tagname) eq 'object' ||
                   4212: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4213: 		) {
                   4214: 		foreach my $item (keys(%javafiles)) {
                   4215: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4216: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4217: 			&add_filetype($allfiles,$file,$item);
                   4218: 		    }
                   4219: 		}
                   4220: 	    } 
                   4221: 	    pop @state;
                   4222: 	}
                   4223:     }
1.1164    raeburn  4224:     foreach my $id (sort(keys(%flashvars))) {
                   4225:         if ($shockwave{$id} ne '') {
                   4226:             my @pairs = split(/\&/,$flashvars{$id});
                   4227:             foreach my $pair (@pairs) {
                   4228:                 my ($key,$value) = split(/\=/,$pair);
                   4229:                 if ($key eq 'thumb') {
                   4230:                     &add_filetype($allfiles,$value,$key);
                   4231:                 } elsif ($key eq 'content') {
                   4232:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4233:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4234:                     if ($ext ne '') {
                   4235:                         &add_filetype($allfiles,$path.$value,$ext);
                   4236:                     }
                   4237:                 }
                   4238:             }
                   4239:         }
                   4240:     }
1.637     raeburn  4241:     return 'ok';
                   4242: }
                   4243: 
1.639     albertel 4244: sub add_filetype {
                   4245:     my ($allfiles,$file,$type)=@_;
                   4246:     if (exists($allfiles->{$file})) {
                   4247: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4248: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4249: 	}
                   4250:     } else {
                   4251: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4252:     }
                   4253: }
                   4254: 
1.1164    raeburn  4255: sub embedded_dependency {
                   4256:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4257:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4258:         if (($identifier ne '') &&
                   4259:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4260:             ($pathfrom ne '')) {
                   4261:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4262:             foreach my $dep (@{$related->{$identifier}}) {
                   4263:                 &add_filetype($allfiles,$path.$dep,'object');
                   4264:             }
                   4265:         }
                   4266:     }
                   4267:     return;
                   4268: }
                   4269: 
1.1172.2.109  raeburn  4270: sub bubblesheet_converter {
                   4271:     my ($cdom,$fullpath,$config,$format) = @_;
                   4272:     if ((&domain($cdom) ne '') &&
                   4273:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4274:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4275:         my (%csvcols,%csvoptions);
                   4276:         if (ref($config->{'fields'}) eq 'HASH') {
                   4277:             %csvcols = %{$config->{'fields'}};
                   4278:         }
                   4279:         if (ref($config->{'options'}) eq 'HASH') {
                   4280:             %csvoptions = %{$config->{'options'}};
                   4281:         }
                   4282:         my %csvbynum = reverse(%csvcols);
                   4283:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4284:         if (keys(%scantronconf)) {
                   4285:             my %bynum = (
                   4286:                           $scantronconf{CODEstart} => 'CODEstart',
                   4287:                           $scantronconf{IDstart}   => 'IDstart',
                   4288:                           $scantronconf{PaperID}   => 'PaperID',
                   4289:                           $scantronconf{FirstName} => 'FirstName',
                   4290:                           $scantronconf{LastName}  => 'LastName',
                   4291:                           $scantronconf{Qstart}    => 'Qstart',
                   4292:                         );
                   4293:             my @ordered;
                   4294:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4295:                 push(@ordered,$bynum{$item});
                   4296:             }
                   4297:             my %mapstart = (
                   4298:                               CODEstart => 'CODE',
                   4299:                               IDstart   => 'ID',
                   4300:                               PaperID   => 'PaperID',
                   4301:                               FirstName => 'FirstName',
                   4302:                               LastName  => 'LastName',
                   4303:                               Qstart    => 'FirstQuestion',
                   4304:                            );
                   4305:             my %maplength = (
                   4306:                               CODEstart => 'CODElength',
                   4307:                               IDstart   => 'IDlength',
                   4308:                               PaperID   => 'PaperIDlength',
                   4309:                               FirstName => 'FirstNamelength',
                   4310:                               LastName  => 'LastNamelength',
                   4311:             );
                   4312:             if (open(my $fh,'<',$fullpath)) {
                   4313:                 my $output;
                   4314:                 my %lettdig = &letter_to_digits();
                   4315:                 my %diglett = reverse(%lettdig);
                   4316:                 my $numletts = scalar(keys(%lettdig));
                   4317:                 my $num = 0;
                   4318:                 while (my $line=<$fh>) {
                   4319:                     $num ++;
                   4320:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4321:                     $line =~ s{[\r\n]+$}{};
                   4322:                     my %found;
                   4323:                     my @values = split(/,/,$line);
                   4324:                     my ($qstart,$record);
                   4325:                     for (my $i=0; $i<@values; $i++) {
                   4326:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4327:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4328:                             if ($values[$i] eq '') {
                   4329:                                 $values[$i] = $scantronconf{'Qoff'};
                   4330:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4331:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4332:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4333:                                 }
                   4334:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4335:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4336:                                     $values[$i] = $diglett{$values[$i]};
                   4337:                                 }
                   4338:                             } else {
                   4339:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4340:                                     my $digit;
                   4341:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4342:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4343:                                         if ($values[$i] eq 'J') {
                   4344:                                             $digit += $numletts;
                   4345:                                         }
                   4346:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4347:                                         $digit = $values[$i]-1;
                   4348:                                         if ($values[$i] eq '0') {
                   4349:                                             $digit += $numletts;
                   4350:                                         }
                   4351:                                     }
                   4352:                                     my $qval='';
                   4353:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4354:                                         if ($j == $digit) {
                   4355:                                             $qval .= $scantronconf{'Qon'};
                   4356:                                         } else {
                   4357:                                             $qval .= $scantronconf{'Qoff'};
                   4358:                                         }
                   4359:                                     }
                   4360:                                     $values[$i] = $qval;
                   4361:                                 }
                   4362:                             }
                   4363:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4364:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4365:                             }
                   4366:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4367:                             if ($numblank > 0) {
                   4368:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4369:                             }
                   4370:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4371:                                 $qstart = $i;
                   4372:                                 $found{$csvbynum{$i}} = $values[$i];
                   4373:                             } else {
                   4374:                                 $found{'FirstQuestion'} .= $values[$i];
                   4375:                             }
                   4376:                         } elsif (exists($csvbynum{$i})) {
                   4377:                             if ($csvoptions{'rem'}) {
                   4378:                                 $values[$i] =~ s/^\s+//;
                   4379:                             }
                   4380:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4381:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4382:                                     $values[$i] = '0'.$values[$i];
                   4383:                                 }
                   4384:                             }
                   4385:                             $found{$csvbynum{$i}} = $values[$i];
                   4386:                         }
                   4387:                     }
                   4388:                     foreach my $item (@ordered) {
                   4389:                         my $currlength = 1+length($record);
                   4390:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4391:                         if ($numspaces > 0) {
                   4392:                             $record .= (' ' x $numspaces);
                   4393:                         }
                   4394:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4395:                             unless ($item eq 'Qstart') {
                   4396:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4397:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4398:                                 }
                   4399:                             }
                   4400:                             $record .= $found{$mapstart{$item}};
                   4401:                         }
                   4402:                     }
                   4403:                     $output .= "$record\n";
                   4404:                 }
                   4405:                 close($fh);
                   4406:                 if ($output) {
                   4407:                     if (open(my $fh,'>',$fullpath)) {
                   4408:                         print $fh $output;
                   4409:                         close($fh);
                   4410:                     }
                   4411:                 }
                   4412:             }
                   4413:         }
                   4414:         return;
                   4415:     }
                   4416: }
                   4417: 
                   4418: sub letter_to_digits {
                   4419:     my %lettdig = (
                   4420:                     A => 1,
                   4421:                     B => 2,
                   4422:                     C => 3,
                   4423:                     D => 4,
                   4424:                     E => 5,
                   4425:                     F => 6,
                   4426:                     G => 7,
                   4427:                     H => 8,
                   4428:                     I => 9,
                   4429:                     J => 0,
                   4430:                   );
                   4431:     return %lettdig;
                   4432: }
                   4433: 
                   4434: sub get_scantron_config {
                   4435:     my ($which,$cdom) = @_;
                   4436:     my @lines = &get_scantronformat_file($cdom);
                   4437:     my %config;
                   4438:     #FIXME probably should move to XML it has already gotten a bit much now
                   4439:     foreach my $line (@lines) {
                   4440:         my ($name,$descrip)=split(/:/,$line);
                   4441:         if ($name ne $which ) { next; }
                   4442:         chomp($line);
                   4443:         my @config=split(/:/,$line);
                   4444:         $config{'name'}=$config[0];
                   4445:         $config{'description'}=$config[1];
                   4446:         $config{'CODElocation'}=$config[2];
                   4447:         $config{'CODEstart'}=$config[3];
                   4448:         $config{'CODElength'}=$config[4];
                   4449:         $config{'IDstart'}=$config[5];
                   4450:         $config{'IDlength'}=$config[6];
                   4451:         $config{'Qstart'}=$config[7];
                   4452:         $config{'Qlength'}=$config[8];
                   4453:         $config{'Qoff'}=$config[9];
                   4454:         $config{'Qon'}=$config[10];
                   4455:         $config{'PaperID'}=$config[11];
                   4456:         $config{'PaperIDlength'}=$config[12];
                   4457:         $config{'FirstName'}=$config[13];
                   4458:         $config{'FirstNamelength'}=$config[14];
                   4459:         $config{'LastName'}=$config[15];
                   4460:         $config{'LastNamelength'}=$config[16];
                   4461:         $config{'BubblesPerRow'}=$config[17];
                   4462:         last;
                   4463:     }
                   4464:     return %config;
                   4465: }
                   4466: 
                   4467: sub get_scantronformat_file {
                   4468:     my ($cdom) = @_;
                   4469:     if ($cdom eq '') {
                   4470:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4471:     }
                   4472:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4473:     my $gottab = 0;
                   4474:     my @lines;
                   4475:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4476:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4477:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4478:             if ($formatfile ne '-1') {
                   4479:                 @lines = split("\n",$formatfile,-1);
                   4480:                 $gottab = 1;
                   4481:             }
                   4482:         }
                   4483:     }
                   4484:     if (!$gottab) {
                   4485:         my $confname = $cdom.'-domainconfig';
                   4486:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4487:         my $formatfile = &getfile($default);
                   4488:         if ($formatfile ne '-1') {
                   4489:             @lines = split("\n",$formatfile,-1);
                   4490:             $gottab = 1;
                   4491:         }
                   4492:     }
                   4493:     if (!$gottab) {
                   4494:         my @domains = &current_machine_domains();
                   4495:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4496:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4497:                 @lines = <$fh>;
                   4498:                 close($fh);
                   4499:             }
                   4500:         } else {
                   4501:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4502:                 @lines = <$fh>;
                   4503:                 close($fh);
                   4504:             }
                   4505:         }
                   4506:     }
                   4507:     return @lines;
                   4508: }
                   4509: 
1.493     albertel 4510: sub removeuploadedurl {
1.984     neumanie 4511:     my ($url)=@_;	
                   4512:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4513:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4514: }
                   4515: 
                   4516: sub removeuserfile {
                   4517:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4518:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4519:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4520:     if ($result eq 'ok') {	
1.798     raeburn  4521:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4522:             my $metafile = $fname.'.meta';
                   4523:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4524: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4525:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4526:             my $sqlresult = 
1.823     albertel 4527:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4528:                                         'portfolio_metadata',$group,
                   4529:                                         'delete');
1.798     raeburn  4530:         }
                   4531:     }
                   4532:     return $result;
1.257     www      4533: }
1.15      www      4534: 
1.530     albertel 4535: sub mkdiruserfile {
                   4536:     my ($docuname,$docudom,$dir)=@_;
                   4537:     my $home=&homeserver($docuname,$docudom);
                   4538:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4539: }
                   4540: 
1.531     albertel 4541: sub renameuserfile {
                   4542:     my ($docuname,$docudom,$old,$new)=@_;
                   4543:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4544:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4545:                         &escape("$old").':'.&escape("$new"),$home);
                   4546:     if ($result eq 'ok') {
                   4547:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4548:             my $oldmeta = $old.'.meta';
                   4549:             my $newmeta = $new.'.meta';
                   4550:             my $metaresult = 
                   4551:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4552: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4553:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4554:             my $sqlresult = 
1.823     albertel 4555:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4556:                                         'portfolio_metadata',$group,
                   4557:                                         'delete');
1.798     raeburn  4558:         }
                   4559:     }
                   4560:     return $result;
1.531     albertel 4561: }
                   4562: 
1.14      www      4563: # ------------------------------------------------------------------------- Log
                   4564: 
                   4565: sub log {
                   4566:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4567:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4568: }
                   4569: 
                   4570: # ------------------------------------------------------------------ Course Log
1.352     www      4571: #
                   4572: # This routine flushes several buffers of non-mission-critical nature
                   4573: #
1.157     www      4574: 
                   4575: sub flushcourselogs {
1.352     www      4576:     &logthis('Flushing log buffers');
                   4577: #
                   4578: # course logs
                   4579: # This is a log of all transactions in a course, which can be used
                   4580: # for data mining purposes
                   4581: #
                   4582: # It also collects the courseid database, which lists last transaction
                   4583: # times and course titles for all courseids
                   4584: #
                   4585:     my %courseidbuffer=();
1.921     raeburn  4586:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4587:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4588: 		          &escape($courselogs{$crsid}),
                   4589: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4590: 	    delete $courselogs{$crsid};
                   4591:         } else {
                   4592:             &logthis('Failed to flush log buffer for '.$crsid);
                   4593:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4594:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4595:                         " exceeded maximum size, deleting.</font>");
                   4596:                delete $courselogs{$crsid};
                   4597:             }
1.352     www      4598:         }
1.920     raeburn  4599:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4600:             'description' => $coursedescrbuf{$crsid},
                   4601:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4602:             'type'        => $coursetypebuf{$crsid},
                   4603:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4604:         };
1.191     harris41 4605:     }
1.352     www      4606: #
                   4607: # Write course id database (reverse lookup) to homeserver of courses 
                   4608: # Is used in pickcourse
                   4609: #
1.840     albertel 4610:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4611:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4612:                                     $courseidbuffer{$crs_home},
                   4613:                                     $crs_home,'timeonly');
1.352     www      4614:     }
                   4615: #
                   4616: # File accesses
                   4617: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4618: #
1.449     matthew  4619:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4620:         if ($entry =~ /___count$/) {
                   4621:             my ($dom,$name);
1.807     albertel 4622:             ($dom,$name,undef)=
1.811     albertel 4623: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4624:             if (! defined($dom) || $dom eq '' || 
                   4625:                 ! defined($name) || $name eq '') {
1.620     albertel 4626:                 my $cid = $env{'request.course.id'};
                   4627:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4628:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4629:             }
1.450     matthew  4630:             my $value = $accesshash{$entry};
                   4631:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4632:             my %temphash=($url => $value);
1.449     matthew  4633:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4634:             if ($result eq 'ok') {
                   4635:                 delete $accesshash{$entry};
                   4636:             }
                   4637:         } else {
1.811     albertel 4638:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4639:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4640:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4641:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4642:                 delete $accesshash{$entry};
                   4643:             }
1.185     www      4644:         }
1.191     harris41 4645:     }
1.352     www      4646: #
                   4647: # Roles
                   4648: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4649: #
1.800     albertel 4650:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4651:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4652: 	    split(/\:/,$entry);
                   4653:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4654:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4655:                 $rudom,$runame) eq 'ok') {
                   4656: 	    delete $userrolehash{$entry};
                   4657:         }
                   4658:     }
1.662     raeburn  4659: #
1.1172.2.90  raeburn  4660: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4661: #
                   4662:     my %domrolebuffer = ();
1.1000    raeburn  4663:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4664:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4665:         if ($domrolebuffer{$rudom}) {
                   4666:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4667:                       '='.&escape($domainrolehash{$entry});
                   4668:         } else {
                   4669:             $domrolebuffer{$rudom}.=&escape($entry).
                   4670:                       '='.&escape($domainrolehash{$entry});
                   4671:         }
                   4672:         delete $domainrolehash{$entry};
                   4673:     }
                   4674:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4675:         my %servers;
                   4676:         if (defined(&domain($dom,'primary'))) {
                   4677:             my $primary=&domain($dom,'primary');
                   4678:             my $hostname=&hostname($primary);
                   4679:             $servers{$primary} = $hostname;
                   4680:         } else {
                   4681:             %servers = &get_servers($dom,'library');
                   4682:         }
1.841     albertel 4683: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4684: 	    if (&reply('domroleput:'.$dom.':'.
                   4685: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4686: 	        last;
                   4687: 	    } else {
1.841     albertel 4688: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4689: 	    }
1.662     raeburn  4690:         }
                   4691:     }
1.186     www      4692:     $dumpcount++;
1.157     www      4693: }
                   4694: 
                   4695: sub courselog {
                   4696:     my $what=shift;
1.158     www      4697:     $what=time.':'.$what;
1.620     albertel 4698:     unless ($env{'request.course.id'}) { return ''; }
                   4699:     $coursedombuf{$env{'request.course.id'}}=
                   4700:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4701:     $coursenumbuf{$env{'request.course.id'}}=
                   4702:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4703:     $coursehombuf{$env{'request.course.id'}}=
                   4704:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4705:     $coursedescrbuf{$env{'request.course.id'}}=
                   4706:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4707:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4708:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4709:     $courseownerbuf{$env{'request.course.id'}}=
                   4710:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4711:     $coursetypebuf{$env{'request.course.id'}}=
                   4712:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4713:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4714: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4715:     } else {
1.620     albertel 4716: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4717:     }
1.620     albertel 4718:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4719: 	&flushcourselogs();
                   4720:     }
1.158     www      4721: }
                   4722: 
                   4723: sub courseacclog {
                   4724:     my $fnsymb=shift;
1.620     albertel 4725:     unless ($env{'request.course.id'}) { return ''; }
                   4726:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4727:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4728:         $what.=':POST';
1.583     matthew  4729:         # FIXME: Probably ought to escape things....
1.800     albertel 4730: 	foreach my $key (keys(%env)) {
                   4731:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4732:                 my $formitem = $1;
                   4733:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4734:                     $what.=':'.$formitem.'='.$env{$key};
                   4735:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4736:                     $what.=':'.$formitem.'='.$env{$key};
                   4737:                 }
1.158     www      4738:             }
1.191     harris41 4739:         }
1.583     matthew  4740:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4741:         # FIXME: We should not be depending on a form parameter that someone
                   4742:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4743:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4744:             $what.= ':POST';
                   4745:             # FIXME: Probably ought to escape things....
                   4746:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4747:                                  'crsdiscuss') {
1.620     albertel 4748:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4749:             }
                   4750:         }
1.158     www      4751:     }
                   4752:     &courselog($what);
1.149     www      4753: }
                   4754: 
1.185     www      4755: sub countacc {
                   4756:     my $url=&declutter(shift);
1.458     matthew  4757:     return if (! defined($url) || $url eq '');
1.620     albertel 4758:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4759: #
                   4760: # Mark that this url was used in this course
                   4761: #
1.620     albertel 4762:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4763: #
                   4764: # Increase the access count for this resource in this child process
                   4765: #
1.281     www      4766:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4767:     $accesshash{$key}++;
1.185     www      4768: }
1.349     www      4769: 
1.361     www      4770: sub linklog {
                   4771:     my ($from,$to)=@_;
                   4772:     $from=&declutter($from);
                   4773:     $to=&declutter($to);
                   4774:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4775:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4776: }
1.1160    www      4777: 
                   4778: sub statslog {
                   4779:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4780:     if ($users<2) { return; }
                   4781:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4782:             'course'       => $env{'request.course.id'},
                   4783:             'sections'     => '"all"',
                   4784:             'num_students' => $users,
                   4785:             'part'         => $part,
                   4786:             'symb'         => $symb,
                   4787:             'mean_tries'   => $av_attempts,
                   4788:             'deg_of_diff'  => $degdiff});
                   4789:     foreach my $key (keys(%dynstore)) {
                   4790:         $accesshash{$key}=$dynstore{$key};
                   4791:     }
                   4792: }
1.361     www      4793:   
1.349     www      4794: sub userrolelog {
                   4795:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4796:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4797:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4798:        $userrolehash
                   4799:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4800:                     =$tend.':'.$tstart;
1.662     raeburn  4801:     }
1.1169    droeschl 4802:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4803:        $userrolehash
                   4804:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4805:                     =$tend.':'.$tstart;
                   4806:     }
1.1172.2.90  raeburn  4807:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4808:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4809:        $domainrolehash
                   4810:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4811:                     = $tend.':'.$tstart;
                   4812:     }
1.351     www      4813: }
                   4814: 
1.957     raeburn  4815: sub courserolelog {
                   4816:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4817:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4818:         my $cdom = $1;
                   4819:         my $cnum = $2;
                   4820:         my $sec = $3;
                   4821:         my $namespace = 'rolelog';
                   4822:         my %storehash = (
                   4823:                            role    => $trole,
                   4824:                            start   => $tstart,
                   4825:                            end     => $tend,
                   4826:                            selfenroll => $selfenroll,
                   4827:                            context    => $context,
                   4828:                         );
                   4829:         if ($trole eq 'gr') {
                   4830:             $namespace = 'groupslog';
                   4831:             $storehash{'group'} = $sec;
                   4832:         } else {
                   4833:             $storehash{'section'} = $sec;
                   4834:         }
                   4835:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4836:                    $domain,$cnum,$cdom);
                   4837:         if (($trole ne 'st') || ($sec ne '')) {
                   4838:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4839:         }
                   4840:     }
                   4841:     return;
                   4842: }
                   4843: 
1.1172.2.9  raeburn  4844: sub domainrolelog {
                   4845:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4846:     if ($area =~ m{^/($match_domain)/$}) {
                   4847:         my $cdom = $1;
                   4848:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4849:         my $namespace = 'rolelog';
                   4850:         my %storehash = (
                   4851:                            role    => $trole,
                   4852:                            start   => $tstart,
                   4853:                            end     => $tend,
                   4854:                            context => $context,
                   4855:                         );
                   4856:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4857:                    $domain,$domconfiguser,$cdom);
                   4858:     }
                   4859:     return;
                   4860: 
                   4861: }
                   4862: 
                   4863: sub coauthorrolelog {
                   4864:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4865:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4866:         my $audom = $1;
                   4867:         my $auname = $2;
                   4868:         my $namespace = 'rolelog';
                   4869:         my %storehash = (
                   4870:                            role    => $trole,
                   4871:                            start   => $tstart,
                   4872:                            end     => $tend,
                   4873:                            context => $context,
                   4874:                         );
                   4875:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4876:                    $domain,$auname,$audom);
                   4877:     }
                   4878:     return;
                   4879: }
                   4880: 
1.351     www      4881: sub get_course_adv_roles {
1.948     raeburn  4882:     my ($cid,$codes) = @_;
1.620     albertel 4883:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4884:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4885:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4886:     my %nothide=();
1.800     albertel 4887:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4888:         if ($user !~ /:/) {
                   4889: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4890:         } else {
                   4891:             $nothide{$user}=1;
                   4892:         }
1.470     www      4893:     }
1.1172.2.23  raeburn  4894:     my @possdoms = ($coursehash{'domain'});
                   4895:     if ($coursehash{'checkforpriv'}) {
                   4896:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4897:     }
1.351     www      4898:     my %returnhash=();
                   4899:     my %dumphash=
                   4900:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4901:     my $now=time;
1.997     raeburn  4902:     my %privileged;
1.1000    raeburn  4903:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4904: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4905:         if (($tstart) && ($tstart<0)) { next; }
                   4906:         if (($tend) && ($tend<$now)) { next; }
                   4907:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4908:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4909: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4910:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4911:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4912: 	if ($role eq 'cr') { next; }
1.948     raeburn  4913:         if ($codes) {
                   4914:             if ($section) { $role .= ':'.$section; }
                   4915:             if ($returnhash{$role}) {
                   4916:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4917:             } else {
                   4918:                 $returnhash{$role}=$username.':'.$domain;
                   4919:             }
1.351     www      4920:         } else {
1.988     raeburn  4921:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4922:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4923:             if ($returnhash{$key}) {
                   4924: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4925:             } else {
                   4926:                 $returnhash{$key}=$username.':'.$domain;
                   4927:             }
1.351     www      4928:         }
1.948     raeburn  4929:     }
1.400     www      4930:     return %returnhash;
                   4931: }
                   4932: 
                   4933: sub get_my_roles {
1.937     raeburn  4934:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4935:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4936:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4937:     my (%dumphash,%nothide);
1.1086    raeburn  4938:     if ($context eq 'userroles') {
1.1166    raeburn  4939:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4940:     } else {
1.1172.2.23  raeburn  4941:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4942:         if ($hidepriv) {
                   4943:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4944:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4945:                 if ($user !~ /:/) {
                   4946:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4947:                 } else {
                   4948:                     $nothide{$user} = 1;
                   4949:                 }
                   4950:             }
                   4951:         }
1.858     raeburn  4952:     }
1.400     www      4953:     my %returnhash=();
                   4954:     my $now=time;
1.999     raeburn  4955:     my %privileged;
1.800     albertel 4956:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4957:         my ($role,$tend,$tstart);
                   4958:         if ($context eq 'userroles') {
1.1149    raeburn  4959:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4960: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4961:         } else {
                   4962:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4963:         }
1.400     www      4964:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4965:         my $status = 'active';
1.939     raeburn  4966:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4967:             $status = 'previous';
                   4968:         } 
                   4969:         if (($tstart) && ($now<$tstart)) {
                   4970:             $status = 'future';
                   4971:         }
                   4972:         if (ref($types) eq 'ARRAY') {
                   4973:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4974:                 next;
                   4975:             } 
                   4976:         } else {
                   4977:             if ($status ne 'active') {
                   4978:                 next;
                   4979:             }
                   4980:         }
1.867     raeburn  4981:         my ($rolecode,$username,$domain,$section,$area);
                   4982:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4983:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4984:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4985:         } else {
                   4986:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4987:         }
1.832     raeburn  4988:         if (ref($roledoms) eq 'ARRAY') {
                   4989:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4990:                 next;
                   4991:             }
                   4992:         }
                   4993:         if (ref($roles) eq 'ARRAY') {
                   4994:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4995:                 if ($role =~ /^cr\//) {
                   4996:                     if (!grep(/^cr$/,@{$roles})) {
                   4997:                         next;
                   4998:                     }
1.1104    raeburn  4999:                 } elsif ($role =~ /^gr\//) {
                   5000:                     if (!grep(/^gr$/,@{$roles})) {
                   5001:                         next;
                   5002:                     }
1.922     raeburn  5003:                 } else {
                   5004:                     next;
                   5005:                 }
1.832     raeburn  5006:             }
1.867     raeburn  5007:         }
1.937     raeburn  5008:         if ($hidepriv) {
1.1172.2.23  raeburn  5009:             my @privroles = ('dc','su');
1.999     raeburn  5010:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5011:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5012:             } else {
1.1172.2.23  raeburn  5013:                 my $possdoms = [$domain];
                   5014:                 if (ref($roledoms) eq 'ARRAY') {
                   5015:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5016:                 }
1.1172.2.23  raeburn  5017:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5018:                     if (!$nothide{$username.':'.$domain}) {
                   5019:                         next;
                   5020:                     }
                   5021:                 }
1.937     raeburn  5022:             }
                   5023:         }
1.933     raeburn  5024:         if ($withsec) {
                   5025:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5026:                 $tstart.':'.$tend;
                   5027:         } else {
                   5028:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5029:         }
1.832     raeburn  5030:     }
1.373     www      5031:     return %returnhash;
1.399     www      5032: }
                   5033: 
1.1172.2.89  raeburn  5034: sub get_all_adhocroles {
                   5035:     my ($dom) = @_;
                   5036:     my @roles_by_num = ();
                   5037:     my %domdefaults = &get_domain_defaults($dom);
                   5038:     my (%description,%access_in_dom,%access_info);
                   5039:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5040:         my $count = 0;
                   5041:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5042:         my %ordered;
                   5043:         foreach my $role (sort(keys(%domcurrent))) {
                   5044:             my ($order,$desc,$access_in_dom);
                   5045:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5046:                 $order = $domcurrent{$role}{'order'};
                   5047:                 $desc = $domcurrent{$role}{'desc'};
                   5048:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5049:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5050:             }
                   5051:             if ($order eq '') {
                   5052:                 $order = $count;
                   5053:             }
                   5054:             $ordered{$order} = $role;
                   5055:             if ($desc ne '') {
                   5056:                 $description{$role} = $desc;
                   5057:             } else {
                   5058:                 $description{$role}= $role;
                   5059:             }
                   5060:             $count++;
                   5061:         }
                   5062:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5063:             push(@roles_by_num,$ordered{$item});
                   5064:         }
                   5065:     }
                   5066:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5067: }
                   5068: 
                   5069: sub get_my_adhocroles {
                   5070:     my ($cid,$checkreg) = @_;
                   5071:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5072:     if ($env{'request.course.id'} eq $cid) {
                   5073:         $cdom = $env{'course.'.$cid.'.domain'};
                   5074:         $cnum = $env{'course.'.$cid.'.num'};
                   5075:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5076:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5077:         $cdom = $1;
                   5078:         $cnum = $2;
                   5079:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5080:                                      $cdom,$cnum);
                   5081:     }
                   5082:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5083:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5084:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5085:         if ($rosterhash{$user} ne '') {
                   5086:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5087:             return ([],{}) if ($type eq 'auto');
                   5088:         }
                   5089:     }
                   5090:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5091:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5092:             my $then=$env{'user.login.time'};
                   5093:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5094:             if (!$update) {
                   5095:                 $update = $then;
                   5096:             }
                   5097:             my @liveroles;
                   5098:             foreach my $role ('dh','da') {
                   5099:                 if ($env{"user.role.$role./$cdom/"}) {
                   5100:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5101:                     my $limit = $update;
                   5102:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5103:                         $limit = $then;
                   5104:                     }
                   5105:                     my $activerole = 1;
                   5106:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5107:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5108:                     if ($activerole) {
                   5109:                         push(@liveroles,$role);
                   5110:                     }
                   5111:                 }
                   5112:             }
                   5113:             if (@liveroles) {
1.1172.2.89  raeburn  5114:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5115:                     my ($accessref,$accessinfo,%access_in_dom);
                   5116:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5117:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5118:                         if (@{$roles_by_num}) {
                   5119:                             my %settings;
                   5120:                             if ($env{'request.course.id'} eq $cid) {
                   5121:                                 foreach my $envkey (keys(%env)) {
                   5122:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5123:                                         $settings{$1} = $env{$envkey};
                   5124:                                     }
                   5125:                                 }
                   5126:                             } else {
                   5127:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5128:                             }
                   5129:                             my %setincrs;
                   5130:                             if ($settings{'internal.adhocaccess'}) {
                   5131:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5132:                             }
                   5133:                             my @statuses;
                   5134:                             if ($env{'environment.inststatus'}) {
                   5135:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5136:                             }
                   5137:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5138:                             if (ref($accessref) eq 'HASH') {
                   5139:                                 %access_in_dom = %{$accessref};
                   5140:                             }
                   5141:                             foreach my $role (@{$roles_by_num}) {
                   5142:                                 my ($curraccess,@okstatus,@personnel);
                   5143:                                 if ($setincrs{$role}) {
                   5144:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5145:                                     if ($curraccess eq 'status') {
                   5146:                                         @okstatus = split(/\&/,$rest);
                   5147:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5148:                                         @personnel = split(/\&/,$rest);
                   5149:                                     }
                   5150:                                 } else {
                   5151:                                     $curraccess = $access_in_dom{$role};
                   5152:                                     if (ref($accessinfo) eq 'HASH') {
                   5153:                                         if ($curraccess eq 'status') {
                   5154:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5155:                                                 @okstatus = @{$accessinfo->{$role}};
                   5156:                                             }
                   5157:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5158:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5159:                                                 @personnel = @{$accessinfo->{$role}};
                   5160:                                             }
                   5161:                                         }
                   5162:                                     }
                   5163:                                 }
                   5164:                                 if ($curraccess eq 'none') {
                   5165:                                     next;
                   5166:                                 } elsif ($curraccess eq 'all') {
                   5167:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5168:                                 } elsif ($curraccess eq 'dh') {
                   5169:                                     if (grep(/^dh$/,@liveroles)) {
                   5170:                                         push(@possroles,$role);
                   5171:                                     } else {
                   5172:                                         next;
                   5173:                                     }
                   5174:                                 } elsif ($curraccess eq 'da') {
                   5175:                                     if (grep(/^da$/,@liveroles)) {
                   5176:                                         push(@possroles,$role);
                   5177:                                     } else {
                   5178:                                         next;
                   5179:                                     }
1.1172.2.89  raeburn  5180:                                 } elsif ($curraccess eq 'status') {
                   5181:                                     if (@okstatus) {
                   5182:                                         if (!@statuses) {
                   5183:                                             if (grep(/^default$/,@okstatus)) {
                   5184:                                                 push(@possroles,$role);
                   5185:                                             }
                   5186:                                         } else {
                   5187:                                             foreach my $status (@okstatus) {
                   5188:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5189:                                                     push(@possroles,$role);
                   5190:                                                     last;
                   5191:                                                 }
                   5192:                                             }
                   5193:                                         }
                   5194:                                     }
                   5195:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5196:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5197:                                         if ($curraccess eq 'exc') {
                   5198:                                             push(@possroles,$role);
                   5199:                                         }
                   5200:                                     } elsif ($curraccess eq 'inc') {
                   5201:                                         push(@possroles,$role);
                   5202:                                     }
                   5203:                                 }
                   5204:                             }
                   5205:                         }
                   5206:                     }
                   5207:                 }
                   5208:             }
                   5209:         }
                   5210:     }
                   5211:     unless (ref($description) eq 'HASH') {
                   5212:         if (ref($roles_by_num) eq 'ARRAY') {
                   5213:             my %desc;
                   5214:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5215:             $description = \%desc;
                   5216:         } else {
                   5217:             $description = {};
                   5218:         }
                   5219:     }
                   5220:     return (\@possroles,$description);
                   5221: }
                   5222: 
1.399     www      5223: # ----------------------------------------------------- Frontpage Announcements
                   5224: #
                   5225: #
                   5226: 
                   5227: sub postannounce {
                   5228:     my ($server,$text)=@_;
1.844     albertel 5229:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5230:     unless ($text=~/\w/) { $text=''; }
                   5231:     return &reply('setannounce:'.&escape($text),$server);
                   5232: }
                   5233: 
                   5234: sub getannounce {
1.448     albertel 5235: 
1.1172.2.96  raeburn  5236:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5237: 	my $announcement='';
1.800     albertel 5238: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5239: 	close($fh);
1.399     www      5240: 	if ($announcement=~/\w/) { 
                   5241: 	    return 
                   5242:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5243:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5244: 	} else {
                   5245: 	    return '';
                   5246: 	}
                   5247:     } else {
                   5248: 	return '';
                   5249:     }
1.351     www      5250: }
1.353     www      5251: 
                   5252: # ---------------------------------------------------------- Course ID routines
                   5253: # Deal with domain's nohist_courseid.db files
                   5254: #
                   5255: 
                   5256: sub courseidput {
1.921     raeburn  5257:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5258:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5259:     my $outcome;
                   5260:     if ($caller eq 'timeonly') {
                   5261:         my $cids = '';
                   5262:         foreach my $item (keys(%$storehash)) {
                   5263:             $cids.=&escape($item).'&';
                   5264:         }
                   5265:         $cids=~s/\&$//;
                   5266:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5267:                           $coursehome);       
                   5268:     } else {
                   5269:         my $items = '';
                   5270:         foreach my $item (keys(%$storehash)) {
                   5271:             $items.= &escape($item).'='.
                   5272:                      &freeze_escape($$storehash{$item}).'&';
                   5273:         }
                   5274:         $items=~s/\&$//;
                   5275:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5276:                           $coursehome);
1.918     raeburn  5277:     }
                   5278:     if ($outcome eq 'unknown_cmd') {
                   5279:         my $what;
                   5280:         foreach my $cid (keys(%$storehash)) {
                   5281:             $what .= &escape($cid).'=';
1.921     raeburn  5282:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5283:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5284:             }
                   5285:             $what =~ s/\:$/&/;
                   5286:         }
                   5287:         $what =~ s/\&$//;  
                   5288:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5289:     } else {
                   5290:         return $outcome;
                   5291:     }
1.353     www      5292: }
                   5293: 
                   5294: sub courseiddump {
1.921     raeburn  5295:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5296:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5297:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5298:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5299:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5300:     my $as_hash = 1;
                   5301:     my %returnhash;
                   5302:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5303:     my %libserv = &all_library();
                   5304:     foreach my $tryserver (keys(%libserv)) {
                   5305:         if ( (  $hostidflag == 1 
                   5306: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5307: 	     || (!defined($hostidflag)) ) {
                   5308: 
1.918     raeburn  5309: 	    if (($domfilter eq '') ||
                   5310: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5311:                 my $rep;
                   5312:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5313:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5314:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5315:                                 &escape($descfilter), &escape($instcodefilter),
                   5316:                                 &escape($ownerfilter), &escape($coursefilter),
                   5317:                                 &escape($typefilter), &escape($regexp_ok),
                   5318:                                 $as_hash, &escape($selfenrollonly),
                   5319:                                 &escape($catfilter), $showhidden, $caller,
                   5320:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5321:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5322:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5323:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5324:                 } else {
                   5325:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5326:                              $sincefilter.':'.&escape($descfilter).':'.
                   5327:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5328:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5329:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5330:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5331:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5332:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5333:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5334:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5335:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5336:                 }
                   5337: 
1.918     raeburn  5338:                 my @pairs=split(/\&/,$rep);
                   5339:                 foreach my $item (@pairs) {
                   5340:                     my ($key,$value)=split(/\=/,$item,2);
                   5341:                     $key = &unescape($key);
                   5342:                     next if ($key =~ /^error: 2 /);
                   5343:                     my $result = &thaw_unescape($value);
                   5344:                     if (ref($result) eq 'HASH') {
                   5345:                         $returnhash{$key}=$result;
                   5346:                     } else {
1.921     raeburn  5347:                         my @responses = split(/:/,$value);
                   5348:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5349:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5350:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5351:                         }
1.1008    raeburn  5352:                     }
1.353     www      5353:                 }
                   5354:             }
                   5355:         }
                   5356:     }
                   5357:     return %returnhash;
                   5358: }
                   5359: 
1.1055    raeburn  5360: sub courselastaccess {
                   5361:     my ($cdom,$cnum,$hostidref) = @_;
                   5362:     my %returnhash;
                   5363:     if ($cdom && $cnum) {
                   5364:         my $chome = &homeserver($cnum,$cdom);
                   5365:         if ($chome ne 'no_host') {
                   5366:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5367:             &extract_lastaccess(\%returnhash,$rep);
                   5368:         }
                   5369:     } else {
                   5370:         if (!$cdom) { $cdom=''; }
                   5371:         my %libserv = &all_library();
                   5372:         foreach my $tryserver (keys(%libserv)) {
                   5373:             if (ref($hostidref) eq 'ARRAY') {
                   5374:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5375:             } 
                   5376:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5377:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5378:                 &extract_lastaccess(\%returnhash,$rep);
                   5379:             }
                   5380:         }
                   5381:     }
                   5382:     return %returnhash;
                   5383: }
                   5384: 
                   5385: sub extract_lastaccess {
                   5386:     my ($returnhash,$rep) = @_;
                   5387:     if (ref($returnhash) eq 'HASH') {
                   5388:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5389:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5390:                  $rep eq '') {
                   5391:             my @pairs=split(/\&/,$rep);
                   5392:             foreach my $item (@pairs) {
                   5393:                 my ($key,$value)=split(/\=/,$item,2);
                   5394:                 $key = &unescape($key);
                   5395:                 next if ($key =~ /^error: 2 /);
                   5396:                 $returnhash->{$key} = &thaw_unescape($value);
                   5397:             }
                   5398:         }
                   5399:     }
                   5400:     return;
                   5401: }
                   5402: 
1.658     raeburn  5403: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5404: 
                   5405: sub dcmailput {
1.685     raeburn  5406:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5407:     my $status = &Apache::lonnet::critical(
1.740     www      5408:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5409:        &escape($message),$server);
1.662     raeburn  5410:     return $status;
                   5411: }
                   5412: 
1.658     raeburn  5413: sub dcmaildump {
                   5414:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5415:     my %returnhash=();
1.846     albertel 5416: 
                   5417:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5418:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5419:                                                          &escape($enddate).':';
                   5420: 	my @esc_senders=map { &escape($_)} @$senders;
                   5421: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5422: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5423:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5424:             if (($key) && ($value)) {
                   5425:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5426:             }
                   5427:         }
                   5428:     }
                   5429:     return %returnhash;
                   5430: }
1.662     raeburn  5431: # ---------------------------------------------------------- Domain roles
                   5432: 
                   5433: sub get_domain_roles {
                   5434:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5435:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5436:         $startdate = '.';
                   5437:     }
1.1018    raeburn  5438:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5439:         $enddate = '.';
                   5440:     }
1.922     raeburn  5441:     my $rolelist;
                   5442:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5443:         $rolelist = join('&',@{$roles});
1.922     raeburn  5444:     }
1.662     raeburn  5445:     my %personnel = ();
1.841     albertel 5446: 
                   5447:     my %servers = &get_servers($dom,'library');
                   5448:     foreach my $tryserver (keys(%servers)) {
                   5449: 	%{$personnel{$tryserver}}=();
                   5450: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5451: 					    &escape($startdate).':'.
                   5452: 					    &escape($enddate).':'.
                   5453: 					    &escape($rolelist), $tryserver))) {
                   5454: 	    my ($key,$value) = split(/\=/,$line,2);
                   5455: 	    if (($key) && ($value)) {
                   5456: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5457: 	    }
                   5458: 	}
1.662     raeburn  5459:     }
                   5460:     return %personnel;
                   5461: }
1.658     raeburn  5462: 
1.1172.2.89  raeburn  5463: sub get_active_domroles {
                   5464:     my ($dom,$roles) = @_;
                   5465:     return () unless (ref($roles) eq 'ARRAY');
                   5466:     my $now = time;
                   5467:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5468:     my %domroles;
                   5469:     foreach my $server (keys(%dompersonnel)) {
                   5470:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5471:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5472:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5473:         }
                   5474:     }
                   5475:     return %domroles;
                   5476: }
                   5477: 
1.1057    www      5478: # ----------------------------------------------------------- Interval timing 
1.149     www      5479: 
1.1153    www      5480: {
                   5481: # Caches needed for speedup of navmaps
                   5482: # We don't want to cache this for very long at all (5 seconds at most)
                   5483: # 
                   5484: # The user for whom we cache
                   5485: my $cachedkey='';
                   5486: # The cached times for this user
                   5487: my %cachedtimes=();
                   5488: # When this was last done
1.1172.2.66  raeburn  5489: my $cachedtime='';
1.1153    www      5490: 
                   5491: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5492:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5493:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5494:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5495:20):         (!$ignorecache)) {
1.1154    raeburn  5496:         return;
                   5497:     }
                   5498:     $cachedtime=time;
                   5499:     $cachedkey=$uname.':'.$udom;
                   5500:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5501: }
                   5502: 
1.504     albertel 5503: sub get_first_access {
1.1172.2.118.  .1(raebu 5504:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5505:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5506:     if ($argsymb) { $symb=$argsymb; }
                   5507:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5508:     if ($argmap) { $map = $argmap; }
1.926     albertel 5509:     if ($type eq 'course') {
                   5510: 	$res='course';
                   5511:     } elsif ($type eq 'map') {
1.588     albertel 5512: 	$res=&symbread($map);
                   5513:     } else {
                   5514: 	$res=$symb;
                   5515:     }
1.1172.2.118.  .1(raebu 5516:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5517:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5518: }
                   5519: 
                   5520: sub set_first_access {
1.1162    raeburn  5521:     my ($type,$interval)=@_;
1.790     albertel 5522:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5523:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5524:     if ($type eq 'course') {
                   5525: 	$res='course';
                   5526:     } elsif ($type eq 'map') {
1.588     albertel 5527: 	$res=&symbread($map);
                   5528:     } else {
                   5529: 	$res=$symb;
                   5530:     }
1.1153    www      5531:     $cachedkey='';
1.1162    raeburn  5532:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5533:     if ($firstaccess) {
                   5534:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5535:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5536:                  "in $courseid");
                   5537:         return 'already_set';
                   5538:     } else {
1.1162    raeburn  5539:         my $start = time;
                   5540: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5541:                           $udom,$uname);
                   5542:         if ($putres eq 'ok') {
                   5543:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5544:                  $udom,$uname); 
                   5545:             &appenv(
                   5546:                      {
                   5547:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5548:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5549:                      }
                   5550:                   );
1.1172.2.97  raeburn  5551:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5552:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5553:             }
1.1172.2.102  raeburn  5554:         } elsif ($putres ne 'refused') {
                   5555:             &logthis("Result: $putres when attempting to set first access time ".
                   5556:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5557:         }
                   5558:         return $putres;
1.505     albertel 5559:     }
                   5560:     return 'already_set';
1.504     albertel 5561: }
1.1153    www      5562: }
1.1172.2.32  raeburn  5563: 
                   5564: sub checkout {
                   5565:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5566:     my $now=time;
                   5567:     my $lonhost=$perlvar{'lonHostID'};
                   5568:     my $infostr=&escape(
                   5569:                  'CHECKOUTTOKEN&'.
                   5570:                  $tuname.'&'.
                   5571:                  $tudom.'&'.
                   5572:                  $tcrsid.'&'.
                   5573:                  $symb.'&'.
                   5574:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5575:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5576:     if ($token=~/^error\:/) {
                   5577:         &logthis("<font color=\"blue\">WARNING: ".
                   5578:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5579:                  "</font>");
                   5580:         return '';
                   5581:     }
                   5582: 
                   5583:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5584:     $token=~tr/a-z/A-Z/;
                   5585: 
                   5586:     my %infohash=('resource.0.outtoken' => $token,
                   5587:                   'resource.0.checkouttime' => $now,
                   5588:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5589: 
                   5590:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5591:        return '';
                   5592:     } else {
                   5593:         &logthis("<font color=\"blue\">WARNING: ".
                   5594:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5595:                  "</font>");
                   5596:     }
                   5597: 
                   5598:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5599:                          &escape('Checkout '.$infostr.' - '.
                   5600:                                                  $token)) ne 'ok') {
                   5601:         return '';
                   5602:     } else {
                   5603:         &logthis("<font color=\"blue\">WARNING: ".
                   5604:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5605:                  "</font>");
                   5606:     }
                   5607:     return $token;
                   5608: }
                   5609: 
                   5610: # ------------------------------------------------------------ Check in an item
                   5611: 
                   5612: sub checkin {
                   5613:     my $token=shift;
                   5614:     my $now=time;
                   5615:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5616:     $lonhost=~tr/A-Z/a-z/;
                   5617:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5618:     $dtoken=~s/\W/\_/g;
                   5619:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5620:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5621: 
                   5622:     unless (($tuname) && ($tudom)) {
                   5623:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5624:         return '';
                   5625:     }
                   5626: 
                   5627:     unless (&allowed('mgr',$tcrsid)) {
                   5628:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5629:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5630:         return '';
                   5631:     }
                   5632: 
                   5633:     my %infohash=('resource.0.intoken' => $token,
                   5634:                   'resource.0.checkintime' => $now,
                   5635:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5636: 
                   5637:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5638:        return '';
                   5639:     }
                   5640: 
                   5641:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5642:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5643:         return '';
                   5644:     }
                   5645: 
                   5646:     return ($symb,$tuname,$tudom,$tcrsid);
                   5647: }
                   5648: 
1.110     www      5649: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5650: 
                   5651: sub expirespread {
                   5652:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5653:     my $cid=$env{'request.course.id'}; 
1.110     www      5654:     if ($cid) {
                   5655:        my $now=time;
                   5656:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5657:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5658:                             $env{'course.'.$cid.'.num'}.
1.110     www      5659: 	        	    ':nohist_expirationdates:'.
                   5660:                             &escape($key).'='.$now,
1.620     albertel 5661:                             $env{'course.'.$cid.'.home'})
1.110     www      5662:     }
                   5663:     return 'ok';
1.14      www      5664: }
                   5665: 
1.109     www      5666: # ----------------------------------------------------- Devalidate Spreadsheets
                   5667: 
                   5668: sub devalidate {
1.325     www      5669:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5670:     my $cid=$env{'request.course.id'}; 
1.109     www      5671:     if ($cid) {
1.391     matthew  5672:         # delete the stored spreadsheets for
                   5673:         # - the student level sheet of this user in course's homespace
                   5674:         # - the assessment level sheet for this resource 
                   5675:         #   for this user in user's homespace
1.553     albertel 5676: 	# - current conditional state info
1.325     www      5677: 	my $key=$uname.':'.$udom.':';
1.109     www      5678:         my $status=
1.299     matthew  5679: 	    &del('nohist_calculatedsheets',
1.391     matthew  5680: 		 [$key.'studentcalc:'],
1.620     albertel 5681: 		 $env{'course.'.$cid.'.domain'},
                   5682: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5683: 		.' '.
                   5684: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5685: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5686:         unless ($status eq 'ok ok') {
                   5687:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5688:                     $uname.' at '.$udom.' for '.
1.109     www      5689: 		    $symb.': '.$status);
1.133     albertel 5690:         }
1.553     albertel 5691: 	&delenv('user.state.'.$cid);
1.109     www      5692:     }
                   5693: }
                   5694: 
1.265     albertel 5695: sub get_scalar {
                   5696:     my ($string,$end) = @_;
                   5697:     my $value;
                   5698:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5699: 	$value = $1;
                   5700:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5701: 	$value = $1;
                   5702:     }
                   5703:     return &unescape($value);
                   5704: }
                   5705: 
                   5706: sub array2str {
                   5707:   my (@array) = @_;
                   5708:   my $result=&arrayref2str(\@array);
                   5709:   $result=~s/^__ARRAY_REF__//;
                   5710:   $result=~s/__END_ARRAY_REF__$//;
                   5711:   return $result;
                   5712: }
                   5713: 
1.204     albertel 5714: sub arrayref2str {
                   5715:   my ($arrayref) = @_;
1.265     albertel 5716:   my $result='__ARRAY_REF__';
1.204     albertel 5717:   foreach my $elem (@$arrayref) {
1.265     albertel 5718:     if(ref($elem) eq 'ARRAY') {
                   5719:       $result.=&arrayref2str($elem).'&';
                   5720:     } elsif(ref($elem) eq 'HASH') {
                   5721:       $result.=&hashref2str($elem).'&';
                   5722:     } elsif(ref($elem)) {
                   5723:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5724:     } else {
                   5725:       $result.=&escape($elem).'&';
                   5726:     }
                   5727:   }
                   5728:   $result=~s/\&$//;
1.265     albertel 5729:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5730:   return $result;
                   5731: }
                   5732: 
1.168     albertel 5733: sub hash2str {
1.204     albertel 5734:   my (%hash) = @_;
                   5735:   my $result=&hashref2str(\%hash);
1.265     albertel 5736:   $result=~s/^__HASH_REF__//;
                   5737:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5738:   return $result;
                   5739: }
                   5740: 
                   5741: sub hashref2str {
                   5742:   my ($hashref)=@_;
1.265     albertel 5743:   my $result='__HASH_REF__';
1.800     albertel 5744:   foreach my $key (sort(keys(%$hashref))) {
                   5745:     if (ref($key) eq 'ARRAY') {
                   5746:       $result.=&arrayref2str($key).'=';
                   5747:     } elsif (ref($key) eq 'HASH') {
                   5748:       $result.=&hashref2str($key).'=';
                   5749:     } elsif (ref($key)) {
1.265     albertel 5750:       $result.='=';
1.800     albertel 5751:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5752:     } else {
1.1132    raeburn  5753: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5754:     }
                   5755: 
1.800     albertel 5756:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5757:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5758:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5759:       $result.=&hashref2str($hashref->{$key}).'&';
                   5760:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5761:        $result.='&';
1.800     albertel 5762:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5763:     } else {
1.800     albertel 5764:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5765:     }
                   5766:   }
1.168     albertel 5767:   $result=~s/\&$//;
1.265     albertel 5768:   $result .= '__END_HASH_REF__';
1.168     albertel 5769:   return $result;
                   5770: }
                   5771: 
                   5772: sub str2hash {
1.265     albertel 5773:     my ($string)=@_;
                   5774:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5775:     return %$hash;
                   5776: }
                   5777: 
                   5778: sub str2hashref {
1.168     albertel 5779:   my ($string) = @_;
1.265     albertel 5780: 
                   5781:   my %hash;
                   5782: 
                   5783:   if($string !~ /^__HASH_REF__/) {
                   5784:       if (! ($string eq '' || !defined($string))) {
                   5785: 	  $hash{'error'}='Not hash reference';
                   5786:       }
                   5787:       return (\%hash, $string);
                   5788:   }
                   5789: 
                   5790:   $string =~ s/^__HASH_REF__//;
                   5791: 
                   5792:   while($string !~ /^__END_HASH_REF__/) {
                   5793:       #key
                   5794:       my $key='';
                   5795:       if($string =~ /^__HASH_REF__/) {
                   5796:           ($key, $string)=&str2hashref($string);
                   5797:           if(defined($key->{'error'})) {
                   5798:               $hash{'error'}='Bad data';
                   5799:               return (\%hash, $string);
                   5800:           }
                   5801:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5802:           ($key, $string)=&str2arrayref($string);
                   5803:           if($key->[0] eq 'Array reference error') {
                   5804:               $hash{'error'}='Bad data';
                   5805:               return (\%hash, $string);
                   5806:           }
                   5807:       } else {
                   5808:           $string =~ s/^(.*?)=//;
1.267     albertel 5809: 	  $key=&unescape($1);
1.265     albertel 5810:       }
                   5811:       $string =~ s/^=//;
                   5812: 
                   5813:       #value
                   5814:       my $value='';
                   5815:       if($string =~ /^__HASH_REF__/) {
                   5816:           ($value, $string)=&str2hashref($string);
                   5817:           if(defined($value->{'error'})) {
                   5818:               $hash{'error'}='Bad data';
                   5819:               return (\%hash, $string);
                   5820:           }
                   5821:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5822:           ($value, $string)=&str2arrayref($string);
                   5823:           if($value->[0] eq 'Array reference error') {
                   5824:               $hash{'error'}='Bad data';
                   5825:               return (\%hash, $string);
                   5826:           }
                   5827:       } else {
                   5828: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5829:       }
                   5830:       $string =~ s/^&//;
                   5831: 
                   5832:       $hash{$key}=$value;
1.204     albertel 5833:   }
1.265     albertel 5834: 
                   5835:   $string =~ s/^__END_HASH_REF__//;
                   5836: 
                   5837:   return (\%hash, $string);
1.204     albertel 5838: }
                   5839: 
                   5840: sub str2array {
1.265     albertel 5841:     my ($string)=@_;
                   5842:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5843:     return @$array;
                   5844: }
                   5845: 
                   5846: sub str2arrayref {
1.204     albertel 5847:   my ($string) = @_;
1.265     albertel 5848:   my @array;
                   5849: 
                   5850:   if($string !~ /^__ARRAY_REF__/) {
                   5851:       if (! ($string eq '' || !defined($string))) {
                   5852: 	  $array[0]='Array reference error';
                   5853:       }
                   5854:       return (\@array, $string);
                   5855:   }
                   5856: 
                   5857:   $string =~ s/^__ARRAY_REF__//;
                   5858: 
                   5859:   while($string !~ /^__END_ARRAY_REF__/) {
                   5860:       my $value='';
                   5861:       if($string =~ /^__HASH_REF__/) {
                   5862:           ($value, $string)=&str2hashref($string);
                   5863:           if(defined($value->{'error'})) {
                   5864:               $array[0] ='Array reference error';
                   5865:               return (\@array, $string);
                   5866:           }
                   5867:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5868:           ($value, $string)=&str2arrayref($string);
                   5869:           if($value->[0] eq 'Array reference error') {
                   5870:               $array[0] ='Array reference error';
                   5871:               return (\@array, $string);
                   5872:           }
                   5873:       } else {
                   5874: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5875:       }
                   5876:       $string =~ s/^&//;
                   5877: 
                   5878:       push(@array, $value);
1.191     harris41 5879:   }
1.265     albertel 5880: 
                   5881:   $string =~ s/^__END_ARRAY_REF__//;
                   5882: 
                   5883:   return (\@array, $string);
1.168     albertel 5884: }
                   5885: 
1.167     albertel 5886: # -------------------------------------------------------------------Temp Store
                   5887: 
1.168     albertel 5888: sub tmpreset {
                   5889:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5890:   if (!$symb) {
                   5891:     $symb=&symbread();
1.620     albertel 5892:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5893:   }
                   5894:   $symb=escape($symb);
                   5895: 
1.620     albertel 5896:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5897:   $namespace=~s/\//\_/g;
                   5898:   $namespace=~s/\W//g;
                   5899: 
1.620     albertel 5900:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5901:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5902:   if ($domain eq 'public' && $stuname eq 'public') {
                   5903:       $stuname=$ENV{'REMOTE_ADDR'};
                   5904:   }
1.1117    foxr     5905:   my $path=LONCAPA::tempdir();
1.168     albertel 5906:   my %hash;
                   5907:   if (tie(%hash,'GDBM_File',
                   5908: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5909: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5910:     foreach my $key (keys(%hash)) {
1.180     albertel 5911:       if ($key=~ /:$symb/) {
1.168     albertel 5912: 	delete($hash{$key});
                   5913:       }
                   5914:     }
                   5915:   }
                   5916: }
                   5917: 
1.167     albertel 5918: sub tmpstore {
1.168     albertel 5919:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5920: 
                   5921:   if (!$symb) {
                   5922:     $symb=&symbread();
1.620     albertel 5923:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5924:   }
                   5925:   $symb=escape($symb);
                   5926: 
                   5927:   if (!$namespace) {
                   5928:     # I don't think we would ever want to store this for a course.
                   5929:     # it seems this will only be used if we don't have a course.
1.620     albertel 5930:     #$namespace=$env{'request.course.id'};
1.168     albertel 5931:     #if (!$namespace) {
1.620     albertel 5932:       $namespace=$env{'request.state'};
1.168     albertel 5933:     #}
                   5934:   }
                   5935:   $namespace=~s/\//\_/g;
                   5936:   $namespace=~s/\W//g;
1.620     albertel 5937:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5938:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5939:   if ($domain eq 'public' && $stuname eq 'public') {
                   5940:       $stuname=$ENV{'REMOTE_ADDR'};
                   5941:   }
1.168     albertel 5942:   my $now=time;
                   5943:   my %hash;
1.1117    foxr     5944:   my $path=LONCAPA::tempdir();
1.168     albertel 5945:   if (tie(%hash,'GDBM_File',
                   5946: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5947: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5948:     $hash{"version:$symb"}++;
                   5949:     my $version=$hash{"version:$symb"};
                   5950:     my $allkeys=''; 
                   5951:     foreach my $key (keys(%$storehash)) {
                   5952:       $allkeys.=$key.':';
1.591     albertel 5953:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5954:     }
                   5955:     $hash{"$version:$symb:timestamp"}=$now;
                   5956:     $allkeys.='timestamp';
                   5957:     $hash{"$version:keys:$symb"}=$allkeys;
                   5958:     if (untie(%hash)) {
                   5959:       return 'ok';
                   5960:     } else {
                   5961:       return "error:$!";
                   5962:     }
                   5963:   } else {
                   5964:     return "error:$!";
                   5965:   }
                   5966: }
1.167     albertel 5967: 
1.168     albertel 5968: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5969: 
1.168     albertel 5970: sub tmprestore {
                   5971:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5972: 
1.168     albertel 5973:   if (!$symb) {
                   5974:     $symb=&symbread();
1.620     albertel 5975:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5976:   }
                   5977:   $symb=escape($symb);
                   5978: 
1.620     albertel 5979:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5980: 
1.620     albertel 5981:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5982:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5983:   if ($domain eq 'public' && $stuname eq 'public') {
                   5984:       $stuname=$ENV{'REMOTE_ADDR'};
                   5985:   }
1.168     albertel 5986:   my %returnhash;
                   5987:   $namespace=~s/\//\_/g;
                   5988:   $namespace=~s/\W//g;
                   5989:   my %hash;
1.1117    foxr     5990:   my $path=LONCAPA::tempdir();
1.168     albertel 5991:   if (tie(%hash,'GDBM_File',
                   5992: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5993: 	  &GDBM_READER(),0640)) {
1.168     albertel 5994:     my $version=$hash{"version:$symb"};
                   5995:     $returnhash{'version'}=$version;
                   5996:     my $scope;
                   5997:     for ($scope=1;$scope<=$version;$scope++) {
                   5998:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5999:       my @keys=split(/:/,$vkeys);
                   6000:       my $key;
                   6001:       $returnhash{"$scope:keys"}=$vkeys;
                   6002:       foreach $key (@keys) {
1.591     albertel 6003: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6004: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6005:       }
                   6006:     }
1.168     albertel 6007:     if (!(untie(%hash))) {
                   6008:       return "error:$!";
                   6009:     }
                   6010:   } else {
                   6011:     return "error:$!";
                   6012:   }
                   6013:   return %returnhash;
1.167     albertel 6014: }
                   6015: 
1.9       www      6016: # ----------------------------------------------------------------------- Store
                   6017: 
                   6018: sub store {
1.1172.2.64  raeburn  6019:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6020:     my $home='';
                   6021: 
1.168     albertel 6022:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6023: 
1.213     www      6024:     $symb=&symbclean($symb);
1.122     albertel 6025:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6026: 
1.620     albertel 6027:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6028:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6029: 
                   6030:     &devalidate($symb,$stuname,$domain);
1.109     www      6031: 
                   6032:     $symb=escape($symb);
1.187     www      6033:     if (!$namespace) { 
1.620     albertel 6034:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6035:           return ''; 
                   6036:        } 
                   6037:     }
1.620     albertel 6038:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6039: 
                   6040:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6041:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6042: 
1.12      www      6043:     my $namevalue='';
1.800     albertel 6044:     foreach my $key (keys(%$storehash)) {
                   6045:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6046:     }
1.12      www      6047:     $namevalue=~s/\&$//;
1.187     www      6048:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6049:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6050: }
                   6051: 
1.47      www      6052: # -------------------------------------------------------------- Critical Store
                   6053: 
                   6054: sub cstore {
1.1172.2.64  raeburn  6055:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6056:     my $home='';
                   6057: 
1.168     albertel 6058:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6059: 
1.213     www      6060:     $symb=&symbclean($symb);
1.122     albertel 6061:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6062: 
1.620     albertel 6063:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6064:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6065: 
                   6066:     &devalidate($symb,$stuname,$domain);
1.109     www      6067: 
                   6068:     $symb=escape($symb);
1.187     www      6069:     if (!$namespace) { 
1.620     albertel 6070:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6071:           return ''; 
                   6072:        } 
                   6073:     }
1.620     albertel 6074:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6075: 
                   6076:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6077:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6078: 
1.47      www      6079:     my $namevalue='';
1.800     albertel 6080:     foreach my $key (keys(%$storehash)) {
                   6081:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6082:     }
1.47      www      6083:     $namevalue=~s/\&$//;
1.187     www      6084:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6085:     return critical
1.1172.2.64  raeburn  6086:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6087: }
                   6088: 
1.9       www      6089: # --------------------------------------------------------------------- Restore
                   6090: 
                   6091: sub restore {
1.124     www      6092:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6093:     my $home='';
                   6094: 
1.168     albertel 6095:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6096: 
1.122     albertel 6097:     if (!$symb) {
1.1172.2.26  raeburn  6098:         return if ($namespace eq 'courserequests');
                   6099:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6100:     } else {
1.1172.2.26  raeburn  6101:         unless ($namespace eq 'courserequests') {
                   6102:             $symb=&escape(&symbclean($symb));
                   6103:         }
1.122     albertel 6104:     }
1.188     www      6105:     if (!$namespace) { 
1.620     albertel 6106:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6107:           return ''; 
                   6108:        } 
                   6109:     }
1.620     albertel 6110:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6111:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6112:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6113:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6114: 
1.12      www      6115:     my %returnhash=();
1.800     albertel 6116:     foreach my $line (split(/\&/,$answer)) {
                   6117: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6118:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6119:     }
1.75      www      6120:     my $version;
                   6121:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6122:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6123:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6124:        }
1.75      www      6125:     }
1.13      www      6126:     return %returnhash;
1.34      www      6127: }
                   6128: 
                   6129: # ---------------------------------------------------------- Course Description
1.1118    foxr     6130: #
                   6131: #  
1.34      www      6132: 
                   6133: sub coursedescription {
1.731     albertel 6134:     my ($courseid,$args)=@_;
1.34      www      6135:     $courseid=~s/^\///;
1.49      www      6136:     $courseid=~s/\_/\//g;
1.34      www      6137:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6138:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6139:     my $normalid=$cdomain.'_'.$cnum;
                   6140:     # need to always cache even if we get errors otherwise we keep 
                   6141:     # trying and trying and trying to get the course description.
                   6142:     my %envhash=();
                   6143:     my %returnhash=();
1.731     albertel 6144:     
                   6145:     my $expiretime=600;
                   6146:     if ($env{'request.course.id'} eq $normalid) {
                   6147: 	$expiretime=120;
                   6148:     }
                   6149: 
                   6150:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6151:     if (!$args->{'freshen_cache'}
                   6152: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6153: 	foreach my $key (keys(%env)) {
                   6154: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6155: 	    my ($setting) = $1;
                   6156: 	    $returnhash{$setting} = $env{$key};
                   6157: 	}
                   6158: 	return %returnhash;
                   6159:     }
                   6160: 
1.1118    foxr     6161:     # get the data again
                   6162: 
1.731     albertel 6163:     if (!$args->{'one_time'}) {
                   6164: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6165:     }
1.811     albertel 6166: 
1.34      www      6167:     if ($chome ne 'no_host') {
1.302     albertel 6168:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6169:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6170: 	   my $username = $env{'user.name'}; # Defult username
                   6171: 	   if(defined $args->{'user'}) {
                   6172: 	       $username = $args->{'user'};
                   6173: 	   }
1.129     albertel 6174:            $returnhash{'home'}= $chome;
                   6175: 	   $returnhash{'domain'} = $cdomain;
                   6176: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6177:            if (!defined($returnhash{'type'})) {
                   6178:                $returnhash{'type'} = 'Course';
                   6179:            }
1.130     albertel 6180:            while (my ($name,$value) = each %returnhash) {
1.53      www      6181:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6182:            }
1.270     www      6183:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6184:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6185: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6186:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6187:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6188:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6189:        }
                   6190:     }
1.731     albertel 6191:     if (!$args->{'one_time'}) {
1.949     raeburn  6192: 	&appenv(\%envhash);
1.731     albertel 6193:     }
1.302     albertel 6194:     return %returnhash;
1.461     www      6195: }
                   6196: 
1.1080    raeburn  6197: sub update_released_required {
                   6198:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6199:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6200:         $cid = $env{'request.course.id'};
                   6201:         $cdom = $env{'course.'.$cid.'.domain'};
                   6202:         $cnum = $env{'course.'.$cid.'.num'};
                   6203:         $chome = $env{'course.'.$cid.'.home'};
                   6204:     }
                   6205:     if ($needsrelease) {
                   6206:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6207:         my $needsupdate;
                   6208:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6209:             $needsupdate = 1;
                   6210:         } else {
                   6211:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6212:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6213:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6214:                 $needsupdate = 1;
                   6215:             }
                   6216:         }
                   6217:         if ($needsupdate) {
                   6218:             my %needshash = (
                   6219:                              'internal.releaserequired' => $needsrelease,
                   6220:                             );
                   6221:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6222:             if ($putresult eq 'ok') {
                   6223:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6224:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6225:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6226:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6227:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6228:                 }
                   6229:             }
                   6230:         }
                   6231:     }
                   6232:     return;
                   6233: }
                   6234: 
1.461     www      6235: # -------------------------------------------------See if a user is privileged
                   6236: 
                   6237: sub privileged {
1.1172.2.23  raeburn  6238:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6239:     my $now = time;
1.1172.2.23  raeburn  6240:     my $roles;
                   6241:     if (ref($possroles) eq 'ARRAY') {
                   6242:         $roles = $possroles;
                   6243:     } else {
                   6244:         $roles = ['dc','su'];
                   6245:     }
                   6246:     if (ref($possdomains) eq 'ARRAY') {
                   6247:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6248:         foreach my $dom (@{$possdomains}) {
                   6249:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6250:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6251:                 foreach my $role (@{$roles}) {
                   6252:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6253:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6254:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6255:                             return 1 unless (($end && $end < $now) ||
                   6256:                                              ($start && $start > $now));
                   6257:                         }
                   6258:                     }
                   6259:                 }
                   6260:             }
                   6261:         }
                   6262:     } else {
                   6263:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6264:         my $now = time;
1.1170    droeschl 6265: 
1.1172.2.58  raeburn  6266:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6267:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6268:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6269:                 return 1 unless ($tend && $tend < $now)
                   6270:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6271:             }
1.1172.2.23  raeburn  6272:         }
                   6273:     }
1.461     www      6274:     return 0;
1.9       www      6275: }
1.1       albertel 6276: 
1.1172.2.23  raeburn  6277: sub privileged_by_domain {
                   6278:     my ($domains,$roles) = @_;
                   6279:     my %privileged = ();
                   6280:     my $cachetime = 60*60*24;
                   6281:     my $now = time;
                   6282:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6283:         return %privileged;
                   6284:     }
                   6285:     foreach my $dom (@{$domains}) {
                   6286:         next if (ref($privileged{$dom}) eq 'HASH');
                   6287:         my $needroles;
                   6288:         foreach my $role (@{$roles}) {
                   6289:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6290:             if (defined($cached)) {
                   6291:                 if (ref($result) eq 'HASH') {
                   6292:                     $privileged{$dom}{$role} = $result;
                   6293:                 }
                   6294:             } else {
                   6295:                 $needroles = 1;
                   6296:             }
                   6297:         }
                   6298:         if ($needroles) {
                   6299:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6300:             $privileged{$dom} = {};
                   6301:             foreach my $server (keys(%dompersonnel)) {
                   6302:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6303:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6304:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6305:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6306:                         next if ($end && $end < $now);
                   6307:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6308:                             $dompersonnel{$server}{$item};
                   6309:                     }
                   6310:                 }
                   6311:             }
                   6312:             if (ref($privileged{$dom}) eq 'HASH') {
                   6313:                 foreach my $role (@{$roles}) {
                   6314:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6315:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6316:                     } else {
                   6317:                         my %hash = ();
                   6318:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6319:                     }
                   6320:                 }
                   6321:             }
                   6322:         }
                   6323:     }
                   6324:     return %privileged;
                   6325: }
                   6326: 
1.103     harris41 6327: # -------------------------------------------------------- Get user privileges
1.11      www      6328: 
                   6329: sub rolesinit {
1.1169    droeschl 6330:     my ($domain, $username) = @_;
                   6331:     my %userroles = ('user.login.time' => time);
                   6332:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6333: 
                   6334:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6335:     # also, blocking can be triggered by an activating timer
                   6336:     # it's saved in the user's %env.
                   6337:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6338:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6339:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6340:         %timerintchk, %timerintenv);
                   6341: 
1.1162    raeburn  6342:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6343:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6344:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6345:     }
1.1169    droeschl 6346: 
1.1162    raeburn  6347:     foreach my $key (keys(%timerinterval)) {
                   6348:         my ($cid,$rest) = split(/\0/,$key);
                   6349:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6350:     }
1.1169    droeschl 6351: 
1.11      www      6352:     my %allroles=();
1.1162    raeburn  6353:     my %allgroups=();
1.11      www      6354: 
1.1172.2.58  raeburn  6355:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6356:         my $role = $rolesdump{$area};
                   6357:         $area =~ s/\_\w\w$//;
                   6358: 
                   6359:         my ($trole, $tend, $tstart, $group_privs);
                   6360: 
                   6361:         if ($role =~ /^cr/) {
                   6362:         # Custom role, defined by a user 
                   6363:         # e.g., user.role.cr/msu/smith/mynewrole
                   6364:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6365:                 $trole = $1;
                   6366:                 ($tend, $tstart) = split('_', $2);
                   6367:             } else {
                   6368:                 $trole = $role;
                   6369:             }
                   6370:         } elsif ($role =~ m|^gr/|) {
                   6371:         # Role of member in a group, defined within a course/community
                   6372:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6373:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6374:             next if $tstart eq '-1';
                   6375:             ($trole, $group_privs) = split(/\//, $trole);
                   6376:             $group_privs = &unescape($group_privs);
                   6377:         } else {
                   6378:         # Just a normal role, defined in roles.tab
                   6379:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6380:         }
                   6381: 
                   6382:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6383:                  $username);
                   6384:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6385: 
                   6386:         # role expired or not available yet?
                   6387:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6388:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6389: 
                   6390:         next if $area eq '' or $trole eq '';
                   6391: 
                   6392:         my $spec = "$trole.$area";
                   6393:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6394: 
                   6395:         if ($trole =~ /^cr\//) {
                   6396:         # Custom role, defined by a user
                   6397:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6398:         } elsif ($trole eq 'gr') {
                   6399:         # Role of a member in a group, defined within a course/community
                   6400:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6401:             next;
                   6402:         } else {
                   6403:         # Normal role, defined in roles.tab
                   6404:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6405:         }
                   6406: 
                   6407:         my $cid = $tdomain.'_'.$trest;
                   6408:         unless ($firstaccchk{$cid}) {
                   6409:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6410:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6411:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6412:                         $coursetimerstarts{$cid}{$item}; 
                   6413:                 }
                   6414:             }
                   6415:             $firstaccchk{$cid} = 1;
                   6416:         }
                   6417:         unless ($timerintchk{$cid}) {
                   6418:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6419:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6420:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6421:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6422:                 }
1.12      www      6423:             }
1.1169    droeschl 6424:             $timerintchk{$cid} = 1;
1.191     harris41 6425:         }
1.11      www      6426:     }
1.1169    droeschl 6427: 
1.1172.2.91  raeburn  6428:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6429:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6430:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6431:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6432: 
1.1162    raeburn  6433:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6434: }
                   6435: 
1.567     raeburn  6436: sub set_arearole {
1.1172.2.19  raeburn  6437:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6438:     unless ($nolog) {
1.567     raeburn  6439: # log the associated role with the area
1.1172.2.19  raeburn  6440:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6441:     }
1.743     albertel 6442:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6443: }
                   6444: 
                   6445: sub custom_roleprivs {
                   6446:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6447:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6448:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6449:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6450:         my ($rdummy,$roledef)=
                   6451:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6452:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6453:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6454:             if (defined($syspriv)) {
1.1043    raeburn  6455:                 if ($trest =~ /^$match_community$/) {
                   6456:                     $syspriv =~ s/bre\&S//; 
                   6457:                 }
1.567     raeburn  6458:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6459:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6460:             }
                   6461:             if ($tdomain ne '') {
                   6462:                 if (defined($dompriv)) {
                   6463:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6464:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6465:                 }
                   6466:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6467:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6468:                         my $rolename = $1;
                   6469:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6470:                     }
1.567     raeburn  6471:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6472:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6473:                 }
                   6474:             }
                   6475:         }
                   6476:     }
                   6477: }
                   6478: 
1.1172.2.89  raeburn  6479: sub course_adhocrole_privs {
                   6480:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6481:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6482:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6483:         my (%currprivs,%storeprivs);
                   6484:         foreach my $item (split(/:/,$coursepriv)) {
                   6485:             my ($priv,$restrict) = split(/\&/,$item);
                   6486:             $currprivs{$priv} = $restrict;
                   6487:         }
                   6488:         my (%possadd,%possremove,%full);
                   6489:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6490:             my ($priv,$restrict)=split(/\&/,$item);
                   6491:             $full{$priv} = $restrict;
                   6492:         }
                   6493:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6494:              next if ($item eq '');
                   6495:              my ($rule,$rest) = split(/=/,$item);
                   6496:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6497:              foreach my $priv (split(/:/,$rest)) {
                   6498:                  if ($priv ne '') {
                   6499:                      if ($rule eq 'off') {
                   6500:                          $possremove{$priv} = 1;
                   6501:                      } else {
                   6502:                          $possadd{$priv} = 1;
                   6503:                      }
                   6504:                  }
                   6505:              }
                   6506:          }
                   6507:          foreach my $priv (sort(keys(%full))) {
                   6508:              if (exists($currprivs{$priv})) {
                   6509:                  unless (exists($possremove{$priv})) {
                   6510:                      $storeprivs{$priv} = $currprivs{$priv};
                   6511:                  }
                   6512:              } elsif (exists($possadd{$priv})) {
                   6513:                  $storeprivs{$priv} = $full{$priv};
                   6514:              }
                   6515:          }
                   6516:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6517:      }
                   6518:      return $coursepriv;
                   6519: }
                   6520: 
1.678     raeburn  6521: sub group_roleprivs {
                   6522:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6523:     my $access = 1;
                   6524:     my $now = time;
                   6525:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6526:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6527:     if ($access) {
1.811     albertel 6528:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6529:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6530:     }
                   6531: }
1.567     raeburn  6532: 
                   6533: sub standard_roleprivs {
                   6534:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6535:     if (defined($pr{$trole.':s'})) {
                   6536:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6537:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6538:     }
                   6539:     if ($tdomain ne '') {
                   6540:         if (defined($pr{$trole.':d'})) {
                   6541:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6542:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6543:         }
                   6544:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6545:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6546:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6547:         }
                   6548:     }
                   6549: }
                   6550: 
                   6551: sub set_userprivs {
1.1064    raeburn  6552:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6553:     my $author=0;
                   6554:     my $adv=0;
1.1172.2.91  raeburn  6555:     my $rar=0;
1.678     raeburn  6556:     my %grouproles = ();
                   6557:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6558:         my @groupkeys; 
1.1000    raeburn  6559:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6560:             push(@groupkeys,$role);
                   6561:         }
                   6562:         if (ref($groups_roles) eq 'HASH') {
                   6563:             foreach my $key (keys(%{$groups_roles})) {
                   6564:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6565:                     push(@groupkeys,$key);
                   6566:                 }
                   6567:             }
                   6568:         }
                   6569:         if (@groupkeys > 0) {
                   6570:             foreach my $role (@groupkeys) {
                   6571:                 my ($trole,$area,$sec,$extendedarea);
                   6572:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6573:                     $trole = $1;
                   6574:                     $area = $2;
                   6575:                     $sec = $3;
                   6576:                     $extendedarea = $area.$sec;
                   6577:                     if (exists($$allgroups{$area})) {
                   6578:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6579:                             my $spec = $trole.'.'.$extendedarea;
                   6580:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6581:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6582:                         }
1.678     raeburn  6583:                     }
                   6584:                 }
                   6585:             }
                   6586:         }
                   6587:     }
1.800     albertel 6588:     foreach my $group (keys(%grouproles)) {
                   6589:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6590:     }
1.800     albertel 6591:     foreach my $role (keys(%{$allroles})) {
                   6592:         my %thesepriv;
1.941     raeburn  6593:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6594:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6595:             if ($item ne '') {
                   6596:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6597:                 if ($restrictions eq '') {
                   6598:                     $thesepriv{$privilege}='F';
                   6599:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6600:                     $thesepriv{$privilege}.=$restrictions;
                   6601:                 }
                   6602:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6603:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6604:             }
                   6605:         }
                   6606:         my $thesestr='';
1.1104    raeburn  6607:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6608: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6609: 	}
                   6610:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6611:     }
1.1172.2.91  raeburn  6612:     return ($author,$adv,$rar);
1.567     raeburn  6613: }
                   6614: 
1.994     raeburn  6615: sub role_status {
1.1104    raeburn  6616:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6617:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6618:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6619:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6620:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6621:             $$where = '/'.$two;
1.994     raeburn  6622:             $$trolecode=$$role.'.'.$$where;
                   6623:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6624:             $$tstatus='is';
1.1104    raeburn  6625:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6626:                 $$tstatus='future';
1.1034    raeburn  6627:                 if ($$tstart<$now) {
                   6628:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6629:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6630:                             my (%allroles,%allgroups,$group_privs,
                   6631:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6632:                             my %userroles = (
                   6633:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6634:                             );
1.1064    raeburn  6635:                             @rolecodes = ('cm'); 
1.1002    raeburn  6636:                             my $spec=$$role.'.'.$$where;
                   6637:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6638:                             if ($$role =~ /^cr\//) {
                   6639:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6640:                                 push(@rolecodes,'cr');
1.1002    raeburn  6641:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6642:                                 push(@rolecodes,$$role);
1.1002    raeburn  6643:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6644:                                                     $env{'user.name'});
1.1064    raeburn  6645:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6646:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6647:                                 $group_privs = &unescape($group_privs);
                   6648:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6649:                                 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  6650:                                 &get_groups_roles($tdomain,$trest,
                   6651:                                                   \%course_roles,\@rolecodes,
                   6652:                                                   \%groups_roles);
1.1002    raeburn  6653:                             } else {
1.1064    raeburn  6654:                                 push(@rolecodes,$$role);
1.1002    raeburn  6655:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6656:                             }
1.1172.2.91  raeburn  6657:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6658:                                                                    \%groups_roles);
1.1064    raeburn  6659:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6660:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6661:                         }
                   6662:                     }
1.1034    raeburn  6663:                     $$tstatus = 'is';
1.1002    raeburn  6664:                 }
1.994     raeburn  6665:             }
                   6666:             if ($$tend) {
1.1104    raeburn  6667:                 if ($$tend<$update) {
1.994     raeburn  6668:                     $$tstatus='expired';
                   6669:                 } elsif ($$tend<$now) {
                   6670:                     $$tstatus='will_not';
                   6671:                 }
                   6672:             }
                   6673:         }
                   6674:     }
                   6675: }
                   6676: 
1.1104    raeburn  6677: sub get_groups_roles {
                   6678:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6679:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6680:                   (ref($rolecodes) eq 'ARRAY') && 
                   6681:                   (ref($groups_roles) eq 'HASH')); 
                   6682:     if (keys(%{$cdom_courseroles}) > 0) {
                   6683:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6684:         if ($cdom ne '' && $cnum ne '') {
                   6685:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6686:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6687:                     my $crsrole = $1;
                   6688:                     my $crssec = $2;
                   6689:                     if ($crsrole =~ /^cr/) {
                   6690:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6691:                             push(@{$rolecodes},'cr');
                   6692:                         }
                   6693:                     } else {
                   6694:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6695:                             push(@{$rolecodes},$crsrole);
                   6696:                         }
                   6697:                     }
                   6698:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6699:                     if ($crssec ne '') {
                   6700:                         $rolekey .= "/$crssec";
                   6701:                     }
                   6702:                     $rolekey .= './';
                   6703:                     $groups_roles->{$rolekey} = $rolecodes;
                   6704:                 }
                   6705:             }
                   6706:         }
                   6707:     }
                   6708:     return;
                   6709: }
                   6710: 
                   6711: sub delete_env_groupprivs {
                   6712:     my ($where,$courseroles,$possroles) = @_;
                   6713:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6714:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6715:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6716:         %{$courseroles->{$udom}} =
                   6717:             &get_my_roles('','','userroles',['active'],
                   6718:                           $possroles,[$udom],1);
                   6719:     }
                   6720:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6721:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6722:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6723:             my $area = '/'.$cdom.'/'.$cnum;
                   6724:             my $privkey = "user.priv.$crsrole.$area";
                   6725:             if ($crssec ne '') {
                   6726:                 $privkey .= '/'.$crssec;
                   6727:             }
                   6728:             $privkey .= ".$area/$group";
                   6729:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6730:         }
                   6731:     }
                   6732:     return;
                   6733: }
                   6734: 
1.994     raeburn  6735: sub check_adhoc_privs {
1.1172.2.86  raeburn  6736:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6737:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6738:     if ($sec) {
                   6739:         $cckey .= '/'.$sec;
                   6740:     }
1.1172.2.9  raeburn  6741:     my $setprivs;
1.994     raeburn  6742:     if ($env{$cckey}) {
                   6743:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6744:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6745:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6746:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6747:             $setprivs = 1;
1.994     raeburn  6748:         }
                   6749:     } else {
1.1172.2.87  raeburn  6750:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6751:         $setprivs = 1;
1.994     raeburn  6752:     }
1.1172.2.9  raeburn  6753:     return $setprivs;
1.994     raeburn  6754: }
                   6755: 
                   6756: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6757: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6758:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6759:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6760:     if ($sec ne '') {
                   6761:         $area .= '/'.$sec;
                   6762:     }
1.994     raeburn  6763:     my $spec = $role.'.'.$area;
                   6764:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6765:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6766:     my %rolehash = ();
1.1172.2.89  raeburn  6767:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6768:         my $rolename = $1;
1.1172.2.84  raeburn  6769:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6770:         my %domdef = &get_domain_defaults($dcdom);
                   6771:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6772:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6773:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6774:             }
                   6775:         }
1.1172.2.84  raeburn  6776:     } else {
                   6777:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6778:     }
1.1172.2.91  raeburn  6779:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6780:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6781:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6782:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6783:         &appenv( {'request.role'        => $spec,
                   6784:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6785:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6786:                  }
                   6787:                );
                   6788:         my $tadv=0;
                   6789:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6790:         &appenv({'request.role.adv'    => $tadv});
                   6791:     }
1.994     raeburn  6792: }
                   6793: 
1.12      www      6794: # --------------------------------------------------------------- get interface
                   6795: 
                   6796: sub get {
1.131     albertel 6797:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6798:    my $items='';
1.800     albertel 6799:    foreach my $item (@$storearr) {
                   6800:        $items.=&escape($item).'&';
1.191     harris41 6801:    }
1.12      www      6802:    $items=~s/\&$//;
1.620     albertel 6803:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6804:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6805:    my $uhome=&homeserver($uname,$udomain);
                   6806: 
1.133     albertel 6807:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6808:    my @pairs=split(/\&/,$rep);
1.273     albertel 6809:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6810:      return @pairs;
                   6811:    }
1.15      www      6812:    my %returnhash=();
1.42      www      6813:    my $i=0;
1.800     albertel 6814:    foreach my $item (@$storearr) {
                   6815:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6816:       $i++;
1.191     harris41 6817:    }
1.15      www      6818:    return %returnhash;
1.27      www      6819: }
                   6820: 
                   6821: # --------------------------------------------------------------- del interface
                   6822: 
                   6823: sub del {
1.133     albertel 6824:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6825:    my $items='';
1.800     albertel 6826:    foreach my $item (@$storearr) {
                   6827:        $items.=&escape($item).'&';
1.191     harris41 6828:    }
1.984     neumanie 6829: 
1.27      www      6830:    $items=~s/\&$//;
1.620     albertel 6831:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6832:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6833:    my $uhome=&homeserver($uname,$udomain);
                   6834:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6835: }
                   6836: 
                   6837: # -------------------------------------------------------------- dump interface
                   6838: 
1.1172.2.22  raeburn  6839: sub unserialize {
                   6840:     my ($rep, $escapedkeys) = @_;
                   6841: 
                   6842:     return {} if $rep =~ /^error/;
                   6843: 
                   6844:     my %returnhash=();
                   6845:     foreach my $item (split(/\&/,$rep)) {
                   6846:         my ($key, $value) = split(/=/, $item, 2);
                   6847:         $key = unescape($key) unless $escapedkeys;
                   6848:         next if $key =~ /^error: 2 /;
                   6849:         $returnhash{$key} = &thaw_unescape($value);
                   6850:     }
                   6851:     return \%returnhash;
                   6852: }
                   6853: 
                   6854: # see Lond::dump_with_regexp
                   6855: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6856: sub dump {
1.1172.2.22  raeburn  6857:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6858:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6859:     if (!$uname) { $uname=$env{'user.name'}; }
                   6860:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6861: 
1.1172.2.55  raeburn  6862:     if ($regexp) {
                   6863:         $regexp=&escape($regexp);
                   6864:     } else {
                   6865:         $regexp='.';
                   6866:     }
1.1172.2.22  raeburn  6867:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6868:         # user is hosted on this machine
1.1172.2.55  raeburn  6869:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6870:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6871:         return %{&unserialize($reply, $escapedkeys)};
                   6872:     }
1.1166    raeburn  6873:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6874:     my @pairs=split(/\&/,$rep);
                   6875:     my %returnhash=();
1.1098    foxr     6876:     if (!($rep =~ /^error/ )) {
                   6877: 	foreach my $item (@pairs) {
                   6878: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6879:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6880: 	    next if ($key =~ /^error: 2 /);
                   6881: 	    $returnhash{$key}=&thaw_unescape($value);
                   6882: 	}
1.755     albertel 6883:     }
                   6884:     return %returnhash;
1.407     www      6885: }
                   6886: 
1.1098    foxr     6887: 
1.717     albertel 6888: # --------------------------------------------------------- dumpstore interface
                   6889: 
                   6890: sub dumpstore {
                   6891:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6892:    # same as dump but keys must be escaped. They may contain colon separated
                   6893:    # lists of values that may themself contain colons (e.g. symbs).
                   6894:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6895: }
                   6896: 
1.407     www      6897: # -------------------------------------------------------------- keys interface
                   6898: 
                   6899: sub getkeys {
                   6900:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6901:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6902:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6903:    my $uhome=&homeserver($uname,$udomain);
                   6904:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6905:    my @keyarray=();
1.800     albertel 6906:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6907:       next if ($key =~ /^error: 2 /);
1.800     albertel 6908:       push(@keyarray,&unescape($key));
1.407     www      6909:    }
                   6910:    return @keyarray;
1.318     matthew  6911: }
                   6912: 
1.319     matthew  6913: # --------------------------------------------------------------- currentdump
                   6914: sub currentdump {
1.328     matthew  6915:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6916:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6917:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6918:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6919:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6920:    my $rep;
                   6921: 
                   6922:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6923:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6924:                    $courseid)));
                   6925:    } else {
                   6926:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6927:    }
                   6928: 
1.318     matthew  6929:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6930:    #
1.318     matthew  6931:    my %returnhash=();
1.319     matthew  6932:    #
1.1172.2.118.  .1(raebu 6933:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6934:        # an old lond will not know currentdump
                   6935:        # Do a dump and make it look like a currentdump
1.822     albertel 6936:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6937:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6938:        my %hash = @tmp;
                   6939:        @tmp=();
1.424     matthew  6940:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6941:    } else {
                   6942:        my @pairs=split(/\&/,$rep);
1.800     albertel 6943:        foreach my $pair (@pairs) {
                   6944:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6945:            my ($symb,$param) = split(/:/,$key);
                   6946:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6947:                                                         &thaw_unescape($value);
1.319     matthew  6948:        }
1.191     harris41 6949:    }
1.12      www      6950:    return %returnhash;
1.424     matthew  6951: }
                   6952: 
                   6953: sub convert_dump_to_currentdump{
                   6954:     my %hash = %{shift()};
                   6955:     my %returnhash;
                   6956:     # Code ripped from lond, essentially.  The only difference
                   6957:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6958:     # we might run in to problems with parameter names =~ /^v\./
                   6959:     while (my ($key,$value) = each(%hash)) {
                   6960:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6961: 	$symb  = &unescape($symb);
                   6962: 	$param = &unescape($param);
1.424     matthew  6963:         next if ($v eq 'version' || $symb eq 'keys');
                   6964:         next if (exists($returnhash{$symb}) &&
                   6965:                  exists($returnhash{$symb}->{$param}) &&
                   6966:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6967:         $returnhash{$symb}->{$param}=$value;
                   6968:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6969:     }
                   6970:     #
                   6971:     # Remove all of the keys in the hashes which keep track of
                   6972:     # the version of the parameter.
                   6973:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6974:         # use a foreach because we are going to delete from the hash.
                   6975:         foreach my $key (keys(%$param_hash)) {
                   6976:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6977:         }
                   6978:     }
                   6979:     return \%returnhash;
1.12      www      6980: }
                   6981: 
1.627     albertel 6982: # ------------------------------------------------------ critical inc interface
                   6983: 
                   6984: sub cinc {
                   6985:     return &inc(@_,'critical');
                   6986: }
                   6987: 
1.449     matthew  6988: # --------------------------------------------------------------- inc interface
                   6989: 
                   6990: sub inc {
1.627     albertel 6991:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6992:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6993:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6994:     my $uhome=&homeserver($uname,$udomain);
                   6995:     my $items='';
                   6996:     if (! ref($store)) {
                   6997:         # got a single value, so use that instead
                   6998:         $items = &escape($store).'=&';
                   6999:     } elsif (ref($store) eq 'SCALAR') {
                   7000:         $items = &escape($$store).'=&';        
                   7001:     } elsif (ref($store) eq 'ARRAY') {
                   7002:         $items = join('=&',map {&escape($_);} @{$store});
                   7003:     } elsif (ref($store) eq 'HASH') {
                   7004:         while (my($key,$value) = each(%{$store})) {
                   7005:             $items.= &escape($key).'='.&escape($value).'&';
                   7006:         }
                   7007:     }
                   7008:     $items=~s/\&$//;
1.627     albertel 7009:     if ($critical) {
                   7010: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7011:     } else {
                   7012: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7013:     }
1.449     matthew  7014: }
                   7015: 
1.12      www      7016: # --------------------------------------------------------------- put interface
                   7017: 
                   7018: sub put {
1.134     albertel 7019:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7020:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7021:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7022:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7023:    my $items='';
1.800     albertel 7024:    foreach my $item (keys(%$storehash)) {
                   7025:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7026:    }
1.12      www      7027:    $items=~s/\&$//;
1.134     albertel 7028:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7029: }
                   7030: 
1.631     albertel 7031: # ------------------------------------------------------------ newput interface
                   7032: 
                   7033: sub newput {
                   7034:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7035:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7036:    if (!$uname) { $uname=$env{'user.name'}; }
                   7037:    my $uhome=&homeserver($uname,$udomain);
                   7038:    my $items='';
                   7039:    foreach my $key (keys(%$storehash)) {
                   7040:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7041:    }
                   7042:    $items=~s/\&$//;
                   7043:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7044: }
                   7045: 
                   7046: # ---------------------------------------------------------  putstore interface
                   7047: 
1.524     raeburn  7048: sub putstore {
1.1172.2.59  raeburn  7049:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7050:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7051:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7052:    my $uhome=&homeserver($uname,$udomain);
                   7053:    my $items='';
1.715     albertel 7054:    foreach my $key (keys(%$storehash)) {
                   7055:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7056:    }
1.715     albertel 7057:    $items=~s/\&$//;
1.716     albertel 7058:    my $esc_symb=&escape($symb);
                   7059:    my $esc_v=&escape($version);
1.715     albertel 7060:    my $reply =
1.716     albertel 7061:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7062: 	      $uhome);
1.1172.2.59  raeburn  7063:    if (($tolog) && ($reply eq 'ok')) {
                   7064:        my $namevalue='';
                   7065:        foreach my $key (keys(%{$storehash})) {
                   7066:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7067:        }
                   7068:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7069:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7070:                      '&version='.$esc_v.
                   7071:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7072:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7073:    }
1.715     albertel 7074:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7075:        # gfall back to way things use to be done
1.715     albertel 7076:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7077: 			    $uname);
1.524     raeburn  7078:    }
1.715     albertel 7079:    return $reply;
                   7080: }
                   7081: 
                   7082: sub old_putstore {
1.716     albertel 7083:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7084:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7085:     if (!$uname) { $uname=$env{'user.name'}; }
                   7086:     my $uhome=&homeserver($uname,$udomain);
                   7087:     my %newstorehash;
1.800     albertel 7088:     foreach my $item (keys(%$storehash)) {
                   7089: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7090: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7091:     }
                   7092:     my $items='';
                   7093:     my %allitems = ();
1.800     albertel 7094:     foreach my $item (keys(%newstorehash)) {
                   7095: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7096: 	    my $key = $1.':keys:'.$2;
                   7097: 	    $allitems{$key} .= $3.':';
                   7098: 	}
1.800     albertel 7099: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7100:     }
1.800     albertel 7101:     foreach my $item (keys(%allitems)) {
                   7102: 	$allitems{$item} =~ s/\:$//;
                   7103: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7104:     }
                   7105:     $items=~s/\&$//;
                   7106:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7107: }
                   7108: 
1.47      www      7109: # ------------------------------------------------------ critical put interface
                   7110: 
                   7111: sub cput {
1.134     albertel 7112:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7113:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7114:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7115:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7116:    my $items='';
1.800     albertel 7117:    foreach my $item (keys(%$storehash)) {
                   7118:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7119:    }
1.47      www      7120:    $items=~s/\&$//;
1.134     albertel 7121:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7122: }
                   7123: 
                   7124: # -------------------------------------------------------------- eget interface
                   7125: 
                   7126: sub eget {
1.133     albertel 7127:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7128:    my $items='';
1.800     albertel 7129:    foreach my $item (@$storearr) {
                   7130:        $items.=&escape($item).'&';
1.191     harris41 7131:    }
1.12      www      7132:    $items=~s/\&$//;
1.620     albertel 7133:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7134:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7135:    my $uhome=&homeserver($uname,$udomain);
                   7136:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7137:    my @pairs=split(/\&/,$rep);
                   7138:    my %returnhash=();
1.42      www      7139:    my $i=0;
1.800     albertel 7140:    foreach my $item (@$storearr) {
                   7141:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7142:       $i++;
1.191     harris41 7143:    }
1.12      www      7144:    return %returnhash;
                   7145: }
                   7146: 
1.667     albertel 7147: # ------------------------------------------------------------ tmpput interface
                   7148: sub tmpput {
1.802     raeburn  7149:     my ($storehash,$server,$context)=@_;
1.667     albertel 7150:     my $items='';
1.800     albertel 7151:     foreach my $item (keys(%$storehash)) {
                   7152: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7153:     }
                   7154:     $items=~s/\&$//;
1.802     raeburn  7155:     if (defined($context)) {
                   7156:         $items .= ':'.&escape($context);
                   7157:     }
1.667     albertel 7158:     return &reply("tmpput:$items",$server);
                   7159: }
                   7160: 
                   7161: # ------------------------------------------------------------ tmpget interface
                   7162: sub tmpget {
1.688     albertel 7163:     my ($token,$server)=@_;
                   7164:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7165:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7166:     my %returnhash;
1.1172.2.85  raeburn  7167:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7168:         return %returnhash;
                   7169:     }
1.667     albertel 7170:     foreach my $item (split(/\&/,$rep)) {
                   7171: 	my ($key,$value)=split(/=/,$item);
                   7172: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7173:     }
                   7174:     return %returnhash;
                   7175: }
                   7176: 
1.1113    raeburn  7177: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7178: sub tmpdel {
                   7179:     my ($token,$server)=@_;
                   7180:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7181:     return &reply("tmpdel:$token",$server);
                   7182: }
                   7183: 
1.1172.2.13  raeburn  7184: # ------------------------------------------------------------ get_timebased_id
                   7185: 
                   7186: sub get_timebased_id {
                   7187:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7188:         $maxtries) = @_;
                   7189:     my ($newid,$error,$dellock);
                   7190:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7191:         return ('','ok','invalid call to get suffix');
                   7192:     }
                   7193: 
                   7194: # set defaults for any optional args for which values were not supplied
                   7195:     if ($who eq '') {
                   7196:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7197:     }
                   7198:     if (!$locktries) {
                   7199:         $locktries = 3;
                   7200:     }
                   7201:     if (!$maxtries) {
                   7202:         $maxtries = 10;
                   7203:     }
                   7204: 
                   7205:     if (($cdom eq '') || ($cnum eq '')) {
                   7206:         if ($env{'request.course.id'}) {
                   7207:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7208:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7209:         }
                   7210:         if (($cdom eq '') || ($cnum eq '')) {
                   7211:             return ('','ok','call to get suffix not in course context');
                   7212:         }
                   7213:     }
                   7214: 
                   7215: # construct locking item
                   7216:     my $lockhash = {
                   7217:                       $prefix."\0".'locked_'.$keyid => $who,
                   7218:                    };
                   7219:     my $tries = 0;
                   7220: 
                   7221: # attempt to get lock on nohist_$namespace file
                   7222:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7223:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7224:         $tries ++;
                   7225:         sleep 1;
                   7226:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7227:     }
                   7228: 
                   7229: # attempt to get unique identifier, based on current timestamp
                   7230:     if ($gotlock eq 'ok') {
                   7231:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7232:         my $id = time;
                   7233:         $newid = $id;
1.1172.2.56  raeburn  7234:         if ($idtype eq 'addcode') {
                   7235:             $newid .= &sixnum_code();
                   7236:         }
1.1172.2.13  raeburn  7237:         my $idtries = 0;
                   7238:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7239:             if ($idtype eq 'concat') {
                   7240:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7241:             } elsif ($idtype eq 'addcode') {
                   7242:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7243:             } else {
                   7244:                 $newid ++;
                   7245:             }
                   7246:             $idtries ++;
                   7247:         }
                   7248:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7249:             my %new_item =  (
                   7250:                               $prefix."\0".$newid => $who,
                   7251:                             );
                   7252:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7253:                                                  $cdom,$cnum);
                   7254:             if ($putresult ne 'ok') {
                   7255:                 undef($newid);
                   7256:                 $error = 'error saving new item: '.$putresult;
                   7257:             }
                   7258:         } else {
1.1172.2.56  raeburn  7259:              undef($newid);
1.1172.2.13  raeburn  7260:              $error = ('error: no unique suffix available for the new item ');
                   7261:         }
                   7262: #  remove lock
                   7263:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7264:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7265:     } else {
                   7266:         $error = "error: could not obtain lockfile\n";
                   7267:         $dellock = 'ok';
1.1172.2.58  raeburn  7268:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7269:             $dellock = 'nolock';
                   7270:         }
1.1172.2.13  raeburn  7271:     }
                   7272:     return ($newid,$dellock,$error);
                   7273: }
                   7274: 
1.1172.2.56  raeburn  7275: sub sixnum_code {
                   7276:     my $code;
                   7277:     for (0..6) {
                   7278:         $code .= int( rand(9) );
                   7279:     }
                   7280:     return $code;
                   7281: }
                   7282: 
1.765     albertel 7283: # -------------------------------------------------- portfolio access checking
                   7284: 
                   7285: sub portfolio_access {
1.1172.2.77  raeburn  7286:     my ($requrl,$clientip) = @_;
1.765     albertel 7287:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7288:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7289:     if ($result) {
                   7290:         my %setters;
                   7291:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7292:             my ($startblock,$endblock) =
                   7293:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7294:             if ($startblock && $endblock) {
                   7295:                 return 'B';
                   7296:             }
                   7297:         } else {
                   7298:             my ($startblock,$endblock) =
                   7299:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7300:             if ($startblock && $endblock) {
                   7301:                 return 'B';
                   7302:             }
                   7303:         }
                   7304:     }
1.765     albertel 7305:     if ($result eq 'ok') {
1.766     albertel 7306:        return 'F';
1.765     albertel 7307:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7308:        return 'A';
1.765     albertel 7309:     }
1.766     albertel 7310:     return '';
1.765     albertel 7311: }
                   7312: 
                   7313: sub get_portfolio_access {
1.1172.2.77  raeburn  7314:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7315: 
                   7316:     if (!ref($access_hash)) {
                   7317: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7318: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7319: 						   $file_name);
                   7320: 	$access_hash = $access_controls{$file_name};
                   7321:     }
                   7322: 
1.1172.2.77  raeburn  7323:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7324:     my $now = time;
                   7325:     if (ref($access_hash) eq 'HASH') {
                   7326:         foreach my $key (keys(%{$access_hash})) {
                   7327:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7328:             if ($start > $now) {
                   7329:                 next;
                   7330:             }
                   7331:             if ($end && $end<$now) {
                   7332:                 next;
                   7333:             }
                   7334:             if ($scope eq 'public') {
                   7335:                 $public = $key;
                   7336:                 last;
                   7337:             } elsif ($scope eq 'guest') {
                   7338:                 $guest = $key;
                   7339:             } elsif ($scope eq 'domains') {
                   7340:                 push(@domains,$key);
                   7341:             } elsif ($scope eq 'users') {
                   7342:                 push(@users,$key);
                   7343:             } elsif ($scope eq 'course') {
                   7344:                 push(@courses,$key);
                   7345:             } elsif ($scope eq 'group') {
                   7346:                 push(@groups,$key);
1.1172.2.77  raeburn  7347:             } elsif ($scope eq 'ip') {
                   7348:                 push(@ips,$key);
1.765     albertel 7349:             }
                   7350:         }
                   7351:         if ($public) {
                   7352:             return 'ok';
1.1172.2.77  raeburn  7353:         } elsif (@ips > 0) {
                   7354:             my $allowed;
                   7355:             foreach my $ipkey (@ips) {
                   7356:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7357:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7358:                         $allowed = 1;
                   7359:                         last;
                   7360:                     }
                   7361:                 }
                   7362:             }
                   7363:             if ($allowed) {
                   7364:                 return 'ok';
                   7365:             }
1.765     albertel 7366:         }
                   7367:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7368:             if ($guest) {
                   7369:                 return $guest;
                   7370:             }
                   7371:         } else {
                   7372:             if (@domains > 0) {
                   7373:                 foreach my $domkey (@domains) {
                   7374:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7375:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7376:                             return 'ok';
                   7377:                         }
                   7378:                     }
                   7379:                 }
                   7380:             }
                   7381:             if (@users > 0) {
                   7382:                 foreach my $userkey (@users) {
1.865     raeburn  7383:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7384:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7385:                             if (ref($item) eq 'HASH') {
                   7386:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7387:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7388:                                     return 'ok';
                   7389:                                 }
                   7390:                             }
                   7391:                         }
                   7392:                     } 
1.765     albertel 7393:                 }
                   7394:             }
                   7395:             my %roleshash;
                   7396:             my @courses_and_groups = @courses;
                   7397:             push(@courses_and_groups,@groups); 
                   7398:             if (@courses_and_groups > 0) {
                   7399:                 my (%allgroups,%allroles); 
                   7400:                 my ($start,$end,$role,$sec,$group);
                   7401:                 foreach my $envkey (%env) {
1.1060    raeburn  7402:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7403:                         my $cid = $2.'_'.$3; 
                   7404:                         if ($1 eq 'gr') {
                   7405:                             $group = $4;
                   7406:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7407:                         } else {
                   7408:                             if ($4 eq '') {
                   7409:                                 $sec = 'none';
                   7410:                             } else {
                   7411:                                 $sec = $4;
                   7412:                             }
                   7413:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7414:                         }
1.811     albertel 7415:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7416:                         my $cid = $2.'_'.$3;
                   7417:                         if ($4 eq '') {
                   7418:                             $sec = 'none';
                   7419:                         } else {
                   7420:                             $sec = $4;
                   7421:                         }
                   7422:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7423:                     }
                   7424:                 }
                   7425:                 if (keys(%allroles) == 0) {
                   7426:                     return;
                   7427:                 }
                   7428:                 foreach my $key (@courses_and_groups) {
                   7429:                     my %content = %{$$access_hash{$key}};
                   7430:                     my $cnum = $content{'number'};
                   7431:                     my $cdom = $content{'domain'};
                   7432:                     my $cid = $cdom.'_'.$cnum;
                   7433:                     if (!exists($allroles{$cid})) {
                   7434:                         next;
                   7435:                     }    
                   7436:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7437:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7438:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7439:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7440:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7441:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7442:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7443:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7444:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7445:                                         if (grep/^all$/,@sections) {
                   7446:                                             return 'ok';
                   7447:                                         } else {
                   7448:                                             if (grep/^$sec$/,@sections) {
                   7449:                                                 return 'ok';
                   7450:                                             }
                   7451:                                         }
                   7452:                                     }
                   7453:                                 }
                   7454:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7455:                                     if (grep/^none$/,@groups) {
                   7456:                                         return 'ok';
                   7457:                                     }
                   7458:                                 } else {
                   7459:                                     if (grep/^all$/,@groups) {
                   7460:                                         return 'ok';
                   7461:                                     } 
                   7462:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7463:                                         if (grep/^$group$/,@groups) {
                   7464:                                             return 'ok';
                   7465:                                         }
                   7466:                                     }
                   7467:                                 } 
                   7468:                             }
                   7469:                         }
                   7470:                     }
                   7471:                 }
                   7472:             }
                   7473:             if ($guest) {
                   7474:                 return $guest;
                   7475:             }
                   7476:         }
                   7477:     }
                   7478:     return;
                   7479: }
                   7480: 
                   7481: sub course_group_datechecker {
                   7482:     my ($dates,$now,$status) = @_;
                   7483:     my ($start,$end) = split(/\./,$dates);
                   7484:     if (!$start && !$end) {
                   7485:         return 'ok';
                   7486:     }
                   7487:     if (grep/^active$/,@{$status}) {
                   7488:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7489:             return 'ok';
                   7490:         }
                   7491:     }
                   7492:     if (grep/^previous$/,@{$status}) {
                   7493:         if ($end > $now ) {
                   7494:             return 'ok';
                   7495:         }
                   7496:     }
                   7497:     if (grep/^future$/,@{$status}) {
                   7498:         if ($start > $now) {
                   7499:             return 'ok';
                   7500:         }
                   7501:     }
                   7502:     return; 
                   7503: }
                   7504: 
                   7505: sub parse_portfolio_url {
                   7506:     my ($url) = @_;
                   7507: 
                   7508:     my ($type,$udom,$unum,$group,$file_name);
                   7509:     
1.823     albertel 7510:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7511: 	$type = 1;
                   7512:         $udom = $1;
                   7513:         $unum = $2;
                   7514:         $file_name = $3;
1.823     albertel 7515:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7516: 	$type = 2;
                   7517:         $udom = $1;
                   7518:         $unum = $2;
                   7519:         $group = $3;
                   7520:         $file_name = $3.'/'.$4;
                   7521:     }
                   7522:     if (wantarray) {
                   7523: 	return ($type,$udom,$unum,$file_name,$group);
                   7524:     }
                   7525:     return $type;
                   7526: }
                   7527: 
                   7528: sub is_portfolio_url {
                   7529:     my ($url) = @_;
                   7530:     return scalar(&parse_portfolio_url($url));
                   7531: }
                   7532: 
1.798     raeburn  7533: sub is_portfolio_file {
                   7534:     my ($file) = @_;
1.820     raeburn  7535:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7536:         return 1;
                   7537:     }
                   7538:     return;
                   7539: }
                   7540: 
1.976     raeburn  7541: sub usertools_access {
1.1084    raeburn  7542:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7543:     my ($access,%tools);
                   7544:     if ($context eq '') {
                   7545:         $context = 'tools';
                   7546:     }
                   7547:     if ($context eq 'requestcourses') {
                   7548:         %tools = (
                   7549:                       official   => 1,
                   7550:                       unofficial => 1,
1.1006    raeburn  7551:                       community  => 1,
1.1172.2.37  raeburn  7552:                       textbook   => 1,
1.985     raeburn  7553:                  );
1.1172.2.9  raeburn  7554:     } elsif ($context eq 'requestauthor') {
                   7555:         %tools = (
                   7556:                       requestauthor => 1,
                   7557:                  );
1.985     raeburn  7558:     } else {
                   7559:         %tools = (
                   7560:                       aboutme   => 1,
                   7561:                       blog      => 1,
1.1172.2.6  raeburn  7562:                       webdav    => 1,
1.985     raeburn  7563:                       portfolio => 1,
                   7564:                  );
                   7565:     }
1.976     raeburn  7566:     return if (!defined($tools{$tool}));
                   7567: 
1.1172.2.35  raeburn  7568:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7569:         $udom = $env{'user.domain'};
                   7570:         $uname = $env{'user.name'};
                   7571:     }
                   7572: 
1.978     raeburn  7573:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7574:         if ($action ne 'reload') {
1.985     raeburn  7575:             if ($context eq 'requestcourses') {
                   7576:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7577:             } elsif ($context eq 'requestauthor') {
                   7578:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7579:             } else {
                   7580:                 return $env{'environment.availabletools.'.$tool};
                   7581:             }
                   7582:         }
1.976     raeburn  7583:     }
                   7584: 
1.1172.2.9  raeburn  7585:     my ($toolstatus,$inststatus,$envkey);
                   7586:     if ($context eq 'requestauthor') {
                   7587:         $envkey = $context;
                   7588:     } else {
                   7589:         $envkey = $context.'.'.$tool;
                   7590:     }
1.976     raeburn  7591: 
1.985     raeburn  7592:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7593:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7594:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7595:         $inststatus = $env{'environment.inststatus'};
                   7596:     } else {
1.1084    raeburn  7597:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7598:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7599:             $inststatus = $userenvref->{'inststatus'};
                   7600:         } else {
1.1172.2.9  raeburn  7601:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7602:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7603:             $inststatus = $userenv{'inststatus'};
                   7604:         }
1.976     raeburn  7605:     }
                   7606: 
                   7607:     if ($toolstatus ne '') {
                   7608:         if ($toolstatus) {
                   7609:             $access = 1;
                   7610:         } else {
                   7611:             $access = 0;
                   7612:         }
                   7613:         return $access;
                   7614:     }
                   7615: 
1.1084    raeburn  7616:     my ($is_adv,%domdef);
                   7617:     if (ref($is_advref) eq 'HASH') {
                   7618:         $is_adv = $is_advref->{'is_adv'};
                   7619:     } else {
                   7620:         $is_adv = &is_advanced_user($udom,$uname);
                   7621:     }
                   7622:     if (ref($domdefref) eq 'HASH') {
                   7623:         %domdef = %{$domdefref};
                   7624:     } else {
                   7625:         %domdef = &get_domain_defaults($udom);
                   7626:     }
1.976     raeburn  7627:     if (ref($domdef{$tool}) eq 'HASH') {
                   7628:         if ($is_adv) {
                   7629:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7630:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7631:                     $access = 1;
                   7632:                 } else {
                   7633:                     $access = 0;
                   7634:                 }
                   7635:                 return $access;
                   7636:             }
                   7637:         }
                   7638:         if ($inststatus ne '') {
                   7639:             my ($hasaccess,$hasnoaccess);
                   7640:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7641:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7642:                     if ($domdef{$tool}{$affiliation}) {
                   7643:                         $hasaccess = 1;
                   7644:                     } else {
                   7645:                         $hasnoaccess = 1;
                   7646:                     }
                   7647:                 }
                   7648:             }
                   7649:             if ($hasaccess || $hasnoaccess) {
                   7650:                 if ($hasaccess) {
                   7651:                     $access = 1;
                   7652:                 } elsif ($hasnoaccess) {
                   7653:                     $access = 0; 
                   7654:                 }
                   7655:                 return $access;
                   7656:             }
                   7657:         } else {
                   7658:             if ($domdef{$tool}{'default'} ne '') {
                   7659:                 if ($domdef{$tool}{'default'}) {
                   7660:                     $access = 1;
                   7661:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7662:                     $access = 0;
                   7663:                 }
                   7664:                 return $access;
                   7665:             }
                   7666:         }
                   7667:     } else {
1.1172.2.6  raeburn  7668:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7669:             $access = 1;
                   7670:         } else {
                   7671:             $access = 0;
                   7672:         }
1.976     raeburn  7673:         return $access;
                   7674:     }
                   7675: }
                   7676: 
1.1050    raeburn  7677: sub is_course_owner {
                   7678:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7679:     if (($udom eq '') || ($uname eq '')) {
                   7680:         $udom = $env{'user.domain'};
                   7681:         $uname = $env{'user.name'};
                   7682:     }
                   7683:     unless (($udom eq '') || ($uname eq '')) {
                   7684:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7685:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7686:                 return 1;
                   7687:             } else {
                   7688:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7689:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7690:                     return 1;
                   7691:                 }
                   7692:             }
                   7693:         }
                   7694:     }
                   7695:     return;
                   7696: }
                   7697: 
1.976     raeburn  7698: sub is_advanced_user {
                   7699:     my ($udom,$uname) = @_;
1.1085    raeburn  7700:     if ($udom ne '' && $uname ne '') {
                   7701:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7702:             if (wantarray) {
                   7703:                 return ($env{'user.adv'},$env{'user.author'});
                   7704:             } else {
                   7705:                 return $env{'user.adv'};
                   7706:             }
1.1085    raeburn  7707:         }
                   7708:     }
1.976     raeburn  7709:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7710:     my %allroles;
1.1128    raeburn  7711:     my ($is_adv,$is_author);
1.976     raeburn  7712:     foreach my $role (keys(%roleshash)) {
                   7713:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7714:         my $area = '/'.$tdomain.'/'.$trest;
                   7715:         if ($sec ne '') {
                   7716:             $area .= '/'.$sec;
                   7717:         }
                   7718:         if (($area ne '') && ($trole ne '')) {
                   7719:             my $spec=$trole.'.'.$area;
                   7720:             if ($trole =~ /^cr\//) {
                   7721:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7722:             } elsif ($trole ne 'gr') {
                   7723:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7724:             }
1.1128    raeburn  7725:             if ($trole eq 'au') {
                   7726:                 $is_author = 1;
                   7727:             }
1.976     raeburn  7728:         }
                   7729:     }
                   7730:     foreach my $role (keys(%allroles)) {
                   7731:         last if ($is_adv);
                   7732:         foreach my $item (split(/:/,$allroles{$role})) {
                   7733:             if ($item ne '') {
                   7734:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7735:                 if ($privilege eq 'adv') {
                   7736:                     $is_adv = 1;
                   7737:                     last;
                   7738:                 }
                   7739:             }
                   7740:         }
                   7741:     }
1.1128    raeburn  7742:     if (wantarray) {
                   7743:         return ($is_adv,$is_author);
                   7744:     }
1.976     raeburn  7745:     return $is_adv;
                   7746: }
1.798     raeburn  7747: 
1.1035    raeburn  7748: sub check_can_request {
1.1036    raeburn  7749:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7750:     my $canreq = 0;
                   7751:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7752:     my @options = ('approval','validate','autolimit');
                   7753:     my $optregex = join('|',@options);
                   7754:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7755:         foreach my $type (@{$types}) {
                   7756:             if (&usertools_access($env{'user.name'},
                   7757:                                   $env{'user.domain'},
                   7758:                                   $type,undef,'requestcourses')) {
                   7759:                 $canreq ++;
1.1036    raeburn  7760:                 if (ref($request_domains) eq 'HASH') {
                   7761:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7762:                 }
1.1035    raeburn  7763:                 if ($dom eq $env{'user.domain'}) {
                   7764:                     $can_request->{$type} = 1;
                   7765:                 }
                   7766:             }
                   7767:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7768:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7769:                 if (@curr > 0) {
1.1036    raeburn  7770:                     foreach my $item (@curr) {
                   7771:                         if (ref($request_domains) eq 'HASH') {
                   7772:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7773:                             if ($otherdom ne '') {
                   7774:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7775:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7776:                                         push(@{$request_domains->{$type}},$otherdom);
                   7777:                                     }
                   7778:                                 } else {
                   7779:                                     push(@{$request_domains->{$type}},$otherdom);
                   7780:                                 }
                   7781:                             }
                   7782:                         }
                   7783:                     }
                   7784:                     unless($dom eq $env{'user.domain'}) {
                   7785:                         $canreq ++;
1.1035    raeburn  7786:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7787:                             $can_request->{$type} = 1;
                   7788:                         }
                   7789:                     }
                   7790:                 }
                   7791:             }
                   7792:         }
                   7793:     }
                   7794:     return $canreq;
                   7795: }
                   7796: 
1.341     www      7797: # ---------------------------------------------- Custom access rule evaluation
                   7798: 
                   7799: sub customaccess {
                   7800:     my ($priv,$uri)=@_;
1.807     albertel 7801:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7802:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7803:     $udom = &LONCAPA::clean_domain($udom);
                   7804:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7805:     my $access=0;
1.800     albertel 7806:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7807: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7808: 	if ($type eq 'user') {
                   7809: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7810: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7811: 		if ($tdom) {
                   7812: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7813: 		}
1.896     albertel 7814: 		if ($tuname) {
                   7815: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7816: 		}
                   7817: 		$access=($effect eq 'allow');
                   7818: 		last;
                   7819: 	    }
                   7820: 	} else {
                   7821: 	    if ($role) {
                   7822: 		if ($role ne $urole) { next; }
                   7823: 	    }
                   7824: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7825: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7826: 		if ($tdom) {
                   7827: 		    if ($tdom ne $udom) { next; }
                   7828: 		}
                   7829: 		if ($tcrs) {
                   7830: 		    if ($tcrs ne $ucrs) { next; }
                   7831: 		}
                   7832: 		if ($tsec) {
                   7833: 		    if ($tsec ne $usec) { next; }
                   7834: 		}
                   7835: 		$access=($effect eq 'allow');
                   7836: 		last;
                   7837: 	    }
                   7838: 	    if ($realm eq '' && $role eq '') {
                   7839: 		$access=($effect eq 'allow');
                   7840: 	    }
1.402     bowersj2 7841: 	}
1.341     www      7842:     }
                   7843:     return $access;
                   7844: }
                   7845: 
1.103     harris41 7846: # ------------------------------------------------- Check for a user privilege
1.12      www      7847: 
                   7848: sub allowed {
1.1172.2.118.  .8(raebu 7849:20):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7850:     my $ver_orguri=$uri;
1.439     www      7851:     $uri=&deversion($uri);
1.152     www      7852:     my $orguri=$uri;
1.52      www      7853:     $uri=&declutter($uri);
1.809     raeburn  7854: 
1.810     raeburn  7855:     if ($priv eq 'evb') {
                   7856: # Evade communication block restrictions for specified role in a course
                   7857:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7858:             return $1;
                   7859:         } else {
                   7860:             return;
                   7861:         }
                   7862:     }
                   7863: 
1.620     albertel 7864:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7865: # Free bre access to adm and meta resources
1.1172.2.118.  .1(raebu 7866:20):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7867: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7868: 	&& ($priv eq 'bre')) {
1.14      www      7869: 	return 'F';
1.159     www      7870:     }
                   7871: 
1.545     banghart 7872: # Free bre access to user's own portfolio contents
1.714     raeburn  7873:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7874:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7875: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7876:         my %setters;
                   7877:         my ($startblock,$endblock) = 
                   7878:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7879:         if ($startblock && $endblock) {
                   7880:             return 'B';
                   7881:         } else {
                   7882:             return 'F';
                   7883:         }
1.545     banghart 7884:     }
                   7885: 
1.762     raeburn  7886: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7887:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7888:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7889:         if (exists($env{'request.course.id'})) {
                   7890:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7891:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7892:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7893:                 my $courseprivid=$env{'request.course.id'};
                   7894:                 $courseprivid=~s/\_/\//;
                   7895:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7896:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7897:                     return $1; 
1.762     raeburn  7898:                 } else {
                   7899:                     if ($env{'request.course.sec'}) {
                   7900:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7901:                     }
                   7902:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7903:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7904:                         return $2;
                   7905:                     }
1.714     raeburn  7906:                 }
                   7907:             }
                   7908:         }
                   7909:     }
                   7910: 
1.159     www      7911: # Free bre to public access
                   7912: 
                   7913:     if ($priv eq 'bre') {
1.238     www      7914:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7915: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7916:            return 'F'; 
                   7917:         }
1.238     www      7918:         if ($copyright eq 'priv') {
                   7919:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7920: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7921: 		return '';
                   7922:             }
                   7923:         }
                   7924:         if ($copyright eq 'domain') {
                   7925:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7926: 	    unless (($env{'user.domain'} eq $1) ||
                   7927:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7928: 		return '';
                   7929:             }
1.262     matthew  7930:         }
1.620     albertel 7931:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7932:             # Library role, so allow browsing of resources in this domain.
                   7933:             return 'F';
1.238     www      7934:         }
1.341     www      7935:         if ($copyright eq 'custom') {
                   7936: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7937:         }
1.14      www      7938:     }
1.264     matthew  7939:     # Domain coordinator is trying to create a course
1.620     albertel 7940:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7941:         # uri is the requested domain in this case.
                   7942:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7943:         # a role of dc for the domain in question.
1.620     albertel 7944:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7945:     }
1.29      www      7946: 
1.52      www      7947:     my $thisallowed='';
                   7948:     my $statecond=0;
                   7949:     my $courseprivid='';
                   7950: 
1.1039    raeburn  7951:     my $ownaccess;
1.1043    raeburn  7952:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7953:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7954:         if ($uri eq '') {
                   7955:             $ownaccess = 1;
                   7956:         } else {
                   7957:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7958:                 my $udom = $env{'user.domain'};
                   7959:                 my $uname = $env{'user.name'};
                   7960:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7961:                     $ownaccess = 1;
1.1040    raeburn  7962:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7963:                     unless ($uri =~ m{\.\./}) {
                   7964:                         $ownaccess = 1;
                   7965:                     }
                   7966:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7967:                     my $now = time;
                   7968:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7969:                         my $adom = $1;
                   7970:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7971:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7972:                                 my ($start,$end) = split('.',$env{$key});
                   7973:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7974:                                     $ownaccess = 1;
                   7975:                                     last;
                   7976:                                 }
                   7977:                             }
                   7978:                         }
                   7979:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7980:                         my $adom = $1;
                   7981:                         my $aname = $2;
1.1042    raeburn  7982:                         foreach my $role ('ca','aa') { 
                   7983:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7984:                                 my ($start,$end) =
                   7985:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7986:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7987:                                     $ownaccess = 1;
                   7988:                                     last;
                   7989:                                 }
1.1039    raeburn  7990:                             }
                   7991:                         }
                   7992:                     }
                   7993:                 }
                   7994:             }
                   7995:         }
                   7996:     }
                   7997: 
1.52      www      7998: # Course
                   7999: 
1.620     albertel 8000:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8001:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8002:             $thisallowed.=$1;
                   8003:         }
1.52      www      8004:     }
1.29      www      8005: 
1.52      www      8006: # Domain
                   8007: 
1.620     albertel 8008:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8009:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8010:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8011:             $thisallowed.=$1;
                   8012:         }
1.12      www      8013:     }
1.52      www      8014: 
1.1141    raeburn  8015: # User who is not author or co-author might still be able to edit
                   8016: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8017:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8018:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8019:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8020:             $thisallowed.=$1;
                   8021:         }
                   8022:     }
                   8023: 
1.52      www      8024: # Course: uri itself is a course
1.66      www      8025:     my $courseuri=$uri;
                   8026:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8027:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8028: 
1.620     albertel 8029:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8030:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8031:         if ($priv eq 'mip') {
                   8032:             my $rem = $1;
                   8033:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8034:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8035:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8036:                 if ($cdom ne '') {
                   8037:                     my %passwdconf = &get_passwdconf($cdom);
                   8038:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8039:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8040:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8041:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8042:                                 unless (@inststatuses) {
                   8043:                                     @inststatuses = ('default');
                   8044:                                 }
                   8045:                                 foreach my $status (@inststatuses) {
                   8046:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8047:                                         $thisallowed.=$rem;
                   8048:                                     }
                   8049:                                 }
                   8050:                             }
                   8051:                         }
                   8052:                     }
                   8053:                 }
                   8054:             }
                   8055:         } else {
                   8056:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8057:                 $thisallowed.=$1;
                   8058:             }
1.1039    raeburn  8059:         }
1.12      www      8060:     }
1.29      www      8061: 
1.665     albertel 8062: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8063: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8064:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8065: 	$thisallowed='';
1.671     raeburn  8066:         my ($match)=&is_on_map($uri);
                   8067:         if ($match) {
                   8068:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8069:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8070:                 my $value = $1;
                   8071:                 if ($noblockcheck) {
                   8072:                     $thisallowed.=$value;
1.1162    raeburn  8073:                 } else {
1.1172.2.118.  .8(raebu 8074:20):                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8075:                     if (@blockers > 0) {
                   8076:                         $thisallowed = 'B';
                   8077:                     } else {
                   8078:                         $thisallowed.=$value;
                   8079:                     }
1.1162    raeburn  8080:                 }
1.671     raeburn  8081:             }
                   8082:         } else {
1.705     albertel 8083:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8084:             if ($refuri) {
                   8085:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8086:                     $thisallowed='F';
1.671     raeburn  8087:                 } else {
                   8088:                     $refuri=&declutter($refuri);
                   8089:                     my ($match) = &is_on_map($refuri);
                   8090:                     if ($match) {
1.1172.2.65  raeburn  8091:                         if ($noblockcheck) {
1.1162    raeburn  8092:                             $thisallowed='F';
1.1172.2.65  raeburn  8093:                         } else {
1.1172.2.118.  .8(raebu 8094:20):                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8095:                             if (@blockers > 0) {
                   8096:                                 $thisallowed = 'B';
                   8097:                             } else {
                   8098:                                 $thisallowed='F';
                   8099:                             }
1.1162    raeburn  8100:                         }
1.671     raeburn  8101:                     }
1.669     raeburn  8102:                 }
1.671     raeburn  8103:             }
                   8104:         }
1.314     www      8105:     }
1.492     albertel 8106: 
1.766     albertel 8107:     if ($priv eq 'bre'
                   8108: 	&& $thisallowed ne 'F' 
                   8109: 	&& $thisallowed ne '2'
                   8110: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8111: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8112:     }
1.1172.2.118.  .8(raebu 8113:20): 
1.52      www      8114: # Full access at system, domain or course-wide level? Exit.
1.29      www      8115:     if ($thisallowed=~/F/) {
                   8116: 	return 'F';
                   8117:     }
                   8118: 
1.52      www      8119: # If this is generating or modifying users, exit with special codes
1.29      www      8120: 
1.643     www      8121:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8122: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8123: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8124: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8125: 	    unless ($auname) { return $thisallowed; }
                   8126: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8127: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8128: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8129: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8130: 	}
1.52      www      8131: 	return $thisallowed;
                   8132:     }
                   8133: #
1.103     harris41 8134: # Gathered so far: system, domain and course wide privileges
1.52      www      8135: #
                   8136: # Course: See if uri or referer is an individual resource that is part of 
                   8137: # the course
                   8138: 
1.620     albertel 8139:     if ($env{'request.course.id'}) {
1.232     www      8140: 
1.1172.2.115  raeburn  8141: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8142: 
                   8143:         if ($priv eq 'mip') {
                   8144:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8145:                 return $thisallowed;
                   8146:             } else {
                   8147:                 return '';
                   8148:             }
                   8149:         }
                   8150: 
1.620     albertel 8151:        $courseprivid=$env{'request.course.id'};
                   8152:        if ($env{'request.course.sec'}) {
                   8153:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8154:        }
                   8155:        $courseprivid=~s/\_/\//;
                   8156:        my $checkreferer=1;
1.232     www      8157:        my ($match,$cond)=&is_on_map($uri);
                   8158:        if ($match) {
                   8159:            $statecond=$cond;
1.620     albertel 8160:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8161:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8162:                my $value = $1;
                   8163:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8164:                    if ($noblockcheck) {
1.1162    raeburn  8165:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8166:                    } else {
1.1172.2.118.  .8(raebu 8167:20):                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8168:                        if (@blockers > 0) {
                   8169:                            $thisallowed = 'B';
                   8170:                        } else {
                   8171:                            $thisallowed.=$value;
                   8172:                        }
1.1162    raeburn  8173:                    }
                   8174:                } else {
                   8175:                    $thisallowed.=$value;
                   8176:                }
1.52      www      8177:                $checkreferer=0;
                   8178:            }
1.29      www      8179:        }
1.1172.2.118.  .8(raebu 8180:20): 
1.148     www      8181:        if ($checkreferer) {
1.620     albertel 8182: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8183:             unless ($refuri) {
1.800     albertel 8184:                 foreach my $key (keys(%env)) {
                   8185: 		    if ($key=~/^httpref\..*\*/) {
                   8186: 			my $pattern=$key;
1.156     www      8187:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8188:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8189:                         $pattern=~s/\//\\\//g;
1.152     www      8190:                         if ($orguri=~/$pattern/) {
1.800     albertel 8191: 			    $refuri=$env{$key};
1.148     www      8192:                         }
                   8193:                     }
1.191     harris41 8194:                 }
1.148     www      8195:             }
1.232     www      8196: 
1.148     www      8197:          if ($refuri) { 
1.152     www      8198: 	  $refuri=&declutter($refuri);
1.232     www      8199:           my ($match,$cond)=&is_on_map($refuri);
                   8200:             if ($match) {
                   8201:               my $refstatecond=$cond;
1.620     albertel 8202:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8203:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8204:                   my $value = $1;
                   8205:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8206:                       if ($noblockcheck) {
1.1162    raeburn  8207:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8208:                       } else {
1.1172.2.118.  .8(raebu 8209:20):                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8210:                           if (@blockers > 0) {
                   8211:                               $thisallowed = 'B';
                   8212:                           } else {
                   8213:                               $thisallowed.=$value;
                   8214:                           }
1.1162    raeburn  8215:                       }
                   8216:                   } else {
                   8217:                       $thisallowed.=$value;
                   8218:                   }
1.53      www      8219:                   $uri=$refuri;
                   8220:                   $statecond=$refstatecond;
1.52      www      8221:               }
                   8222:           }
1.148     www      8223:         }
1.29      www      8224:        }
1.52      www      8225:    }
1.29      www      8226: 
1.52      www      8227: #
1.103     harris41 8228: # Gathered now: all privileges that could apply, and condition number
1.52      www      8229: # 
                   8230: #
                   8231: # Full or no access?
                   8232: #
1.29      www      8233: 
1.52      www      8234:     if ($thisallowed=~/F/) {
                   8235: 	return 'F';
                   8236:     }
1.29      www      8237: 
1.52      www      8238:     unless ($thisallowed) {
                   8239:         return '';
                   8240:     }
1.29      www      8241: 
1.52      www      8242: # Restrictions exist, deal with them
                   8243: #
                   8244: #   C:according to course preferences
                   8245: #   R:according to resource settings
                   8246: #   L:unless locked
                   8247: #   X:according to user session state
                   8248: #
                   8249: 
                   8250: # Possibly locked functionality, check all courses
1.54      www      8251: # Locks might take effect only after 10 minutes cache expiration for other
                   8252: # courses, and 2 minutes for current course
1.52      www      8253: 
                   8254:     my $envkey;
                   8255:     if ($thisallowed=~/L/) {
1.1000    raeburn  8256:         foreach $envkey (keys(%env)) {
1.54      www      8257:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8258:                my $courseid=$2;
                   8259:                my $roleid=$1.'.'.$2;
1.92      www      8260:                $courseid=~s/^\///;
1.54      www      8261:                my $expiretime=600;
1.620     albertel 8262:                if ($env{'request.role'} eq $roleid) {
1.54      www      8263: 		  $expiretime=120;
                   8264:                }
                   8265: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8266:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8267:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8268: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8269:                }
1.620     albertel 8270:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8271:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8272: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8273:                        &log($env{'user.domain'},$env{'user.name'},
                   8274:                             $env{'user.home'},
1.57      www      8275:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8276:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8277:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8278: 		       return '';
                   8279:                    }
                   8280:                }
1.620     albertel 8281:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8282:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8283: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8284:                        &log($env{'user.domain'},$env{'user.name'},
                   8285:                             $env{'user.home'},
1.57      www      8286:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8287:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8288:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8289: 		       return '';
                   8290:                    }
                   8291:                }
                   8292: 	   }
1.29      www      8293:        }
1.52      www      8294:     }
1.1172.2.118.  .8(raebu 8295:20): 
1.52      www      8296: #
                   8297: # Rest of the restrictions depend on selected course
                   8298: #
                   8299: 
1.620     albertel 8300:     unless ($env{'request.course.id'}) {
1.766     albertel 8301: 	if ($thisallowed eq 'A') {
                   8302: 	    return 'A';
1.814     raeburn  8303:         } elsif ($thisallowed eq 'B') {
                   8304:             return 'B';
1.766     albertel 8305: 	} else {
                   8306: 	    return '1';
                   8307: 	}
1.52      www      8308:     }
1.29      www      8309: 
1.52      www      8310: #
                   8311: # Now user is definitely in a course
                   8312: #
1.53      www      8313: 
                   8314: 
                   8315: # Course preferences
                   8316: 
                   8317:    if ($thisallowed=~/C/) {
1.620     albertel 8318:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8319:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8320:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8321: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8322: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8323: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8324: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8325: 			$env{'request.course.id'});
                   8326: 	   }
1.237     www      8327:            return '';
                   8328:        }
                   8329: 
1.620     albertel 8330:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8331: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8332: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8333: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8334: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8335: 			$env{'request.course.id'});
                   8336: 	   }
1.54      www      8337:            return '';
                   8338:        }
1.53      www      8339:    }
                   8340: 
                   8341: # Resource preferences
                   8342: 
                   8343:    if ($thisallowed=~/R/) {
1.620     albertel 8344:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8345:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8346: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8347: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8348: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8349: 	   }
                   8350: 	   return '';
1.54      www      8351:        }
1.53      www      8352:    }
1.30      www      8353: 
1.246     www      8354: # Restricted by state or randomout?
1.30      www      8355: 
1.52      www      8356:    if ($thisallowed=~/X/) {
1.620     albertel 8357:       if ($env{'acc.randomout'}) {
1.579     albertel 8358: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8359:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8360:             return ''; 
                   8361:          }
1.247     www      8362:       }
                   8363:       if (&condval($statecond)) {
1.52      www      8364: 	 return '2';
                   8365:       } else {
                   8366:          return '';
                   8367:       }
                   8368:    }
1.30      www      8369: 
1.766     albertel 8370:     if ($thisallowed eq 'A') {
                   8371: 	return 'A';
1.814     raeburn  8372:     } elsif ($thisallowed eq 'B') {
                   8373:         return 'B';
1.766     albertel 8374:     }
1.52      www      8375:    return 'F';
1.232     www      8376: }
1.1162    raeburn  8377: 
1.1172.2.13  raeburn  8378: # ------------------------------------------- Check construction space access
                   8379: 
                   8380: sub constructaccess {
                   8381:     my ($url,$setpriv)=@_;
                   8382: 
                   8383: # We do not allow editing of previous versions of files
                   8384:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8385: 
                   8386: # Get username and domain from URL
                   8387:     my ($ownername,$ownerdomain,$ownerhome);
                   8388: 
                   8389:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8390:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8391: 
                   8392: # The URL does not really point to any authorspace, forget it
                   8393:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8394: 
                   8395: # Now we need to see if the user has access to the authorspace of
                   8396: # $ownername at $ownerdomain
                   8397: 
                   8398:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8399: # Real author for this?
                   8400:        $ownerhome = $env{'user.home'};
                   8401:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8402:           return ($ownername,$ownerdomain,$ownerhome);
                   8403:        }
                   8404:     } else {
                   8405: # Co-author for this?
                   8406:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8407:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8408:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8409:             return ($ownername,$ownerdomain,$ownerhome);
                   8410:         }
                   8411:     }
                   8412: 
                   8413: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8414: # we might as well leave
                   8415:    unless ($setpriv) { return ''; }
                   8416: 
                   8417: # Backdoor access?
                   8418:     my $allowed=&allowed('eco',$ownerdomain);
                   8419: # Nope
                   8420:     unless ($allowed) { return ''; }
                   8421: # Looks like we may have access, but could be locked by the owner of the construction space
                   8422:     if ($allowed eq 'U') {
                   8423:         my %blocked=&get('environment',['domcoord.author'],
                   8424:                          $ownerdomain,$ownername);
                   8425: # Is blocked by owner
                   8426:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8427:     }
                   8428:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8429: # Grant temporary access
                   8430:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8431:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8432:         if (!$update) { $update = $then; }
                   8433:         my $refresh=$env{'user.refresh.time'};
                   8434:         if (!$refresh) { $refresh = $update; }
                   8435:         my $now = time;
                   8436:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8437:                            $now,'ca','constructaccess');
                   8438:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8439:         return($ownername,$ownerdomain,$ownerhome);
                   8440:     }
                   8441: # No business here
                   8442:     return '';
                   8443: }
                   8444: 
1.1172.2.66  raeburn  8445: # ----------------------------------------------------------- Content Blocking
                   8446: 
                   8447: {
                   8448: # Caches for faster Course Contents display where content blocking
                   8449: # is in operation (i.e., interval param set) for timed quiz.
                   8450: #
                   8451: # User for whom data are being temporarily cached.
                   8452: my $cacheduser='';
1.1172.2.118.  .8(raebu 8453:20): # Course for which data are being temporarily cached.
                   8454:20): my $cachedcid='';
1.1172.2.66  raeburn  8455: # Cached blockers for this user (a hash of blocking items).
                   8456: my %cachedblockers=();
                   8457: # When the data were last cached.
                   8458: my $cachedlast='';
                   8459: 
                   8460: sub load_all_blockers {
1.1172.2.118.  .9(raebu 8461:20):     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8462:     if (($uname ne '') && ($udom ne '')) {
                   8463:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.118.  .8(raebu 8464:20):             ($cachedcid eq $env{'request.course.id'}) &&
          .9(raebu 8465:20):             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8466:             return;
                   8467:         }
                   8468:     }
                   8469:     $cachedlast=time;
                   8470:     $cacheduser=$uname.':'.$udom;
1.1172.2.118.  .8(raebu 8471:20):     $cachedcid=$env{'request.course.id'};
          .9(raebu 8472:20):     %cachedblockers = &get_commblock_resources();
          .8(raebu 8473:20):     return;
1.1172.2.66  raeburn  8474: }
                   8475: 
1.1162    raeburn  8476: sub get_comm_blocks {
                   8477:     my ($cdom,$cnum) = @_;
                   8478:     if ($cdom eq '' || $cnum eq '') {
                   8479:         return unless ($env{'request.course.id'});
                   8480:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8481:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8482:     }
                   8483:     my %commblocks;
                   8484:     my $hashid=$cdom.'_'.$cnum;
                   8485:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8486:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8487:         %commblocks = %{$blocksref};
                   8488:     } else {
                   8489:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8490:         my $cachetime = 600;
                   8491:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8492:     }
                   8493:     return %commblocks;
                   8494: }
                   8495: 
1.1172.2.66  raeburn  8496: sub get_commblock_resources {
                   8497:     my ($blocks) = @_;
                   8498:     my %blockers = ();
                   8499:     return %blockers unless ($env{'request.course.id'});
                   8500:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8501:     my %commblocks;
                   8502:     if (ref($blocks) eq 'HASH') {
                   8503:         %commblocks = %{$blocks};
                   8504:     } else {
                   8505:         %commblocks = &get_comm_blocks();
                   8506:     }
1.1172.2.66  raeburn  8507:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8508:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8509:     return %blockers unless (ref($navmap));
                   8510:     my $now = time;
1.1162    raeburn  8511:     foreach my $block (keys(%commblocks)) {
                   8512:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8513:             my ($start,$end) = ($1,$2);
                   8514:             if ($start <= $now && $end >= $now) {
                   8515:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8516:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8517:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8518:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8519:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8520:                             }
                   8521:                         }
                   8522:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8523:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8524:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8525:                             }
                   8526:                         }
                   8527:                     }
                   8528:                 }
                   8529:             }
                   8530:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8531:             my $item = $1;
1.1163    raeburn  8532:             my @to_test;
1.1162    raeburn  8533:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8534:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8535:                     my @interval;
                   8536:                     my $type = 'map';
                   8537:                     if ($item eq 'course') {
                   8538:                         $type = 'course';
                   8539:                         @interval=&EXT("resource.0.interval");
                   8540:                     } else {
                   8541:                         if ($item =~ /___\d+___/) {
                   8542:                             $type = 'resource';
                   8543:                             @interval=&EXT("resource.0.interval",$item);
                   8544:                             if (ref($navmap)) {
                   8545:                                 my $res = $navmap->getBySymb($item);
                   8546:                                 push(@to_test,$res);
                   8547:                             }
1.1162    raeburn  8548:                         } else {
1.1172.2.66  raeburn  8549:                             my $mapsymb = &symbread($item,1);
                   8550:                             if ($mapsymb) {
                   8551:                                 if (ref($navmap)) {
                   8552:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.118.  .11(raeb 8553:-20):                                     if (ref($mapres)) {
                   8554:-20):                                         my $first = $mapres->map_start();
                   8555:-20):                                         my $finish = $mapres->map_finish();
                   8556:-20):                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8557:-20):                                         if (ref($it)) {
                   8558:-20):                                             my $res;
                   8559:-20):                                             while ($res = $it->next(undef,1)) {
                   8560:-20):                                                 next unless (ref($res));
                   8561:-20):                                                 my $symb = $res->symb();
                   8562:-20):                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8563:-20):                                                 @interval=&EXT("resource.0.interval",$symb);
                   8564:-20):                                                 if ($interval[1] eq 'map') {
                   8565:-20):                                                     if ($res->answerable()) {
                   8566:-20):                                                         push(@to_test,$res);
                   8567:-20):                                                         last;
                   8568:-20):                                                     }
                   8569:-20):                                                 }
1.1162    raeburn  8570:                                             }
                   8571:                                         }
                   8572:                                     }
                   8573:                                 }
                   8574:                             }
                   8575:                         }
1.1172.2.66  raeburn  8576:                     }
1.1172.2.118.  .1(raebu 8577:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8578:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8579:                         my $first_access;
                   8580:                         if ($type eq 'resource') {
                   8581:                             $first_access=&get_first_access($interval[1],$item);
                   8582:                         } elsif ($type eq 'map') {
                   8583:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8584:                         } else {
                   8585:                             $first_access=&get_first_access($interval[1]);
                   8586:                         }
                   8587:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8588:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8589:                             if ($timesup > $now) {
                   8590:                                 my $activeblock;
                   8591:                                 foreach my $res (@to_test) {
                   8592:                                     if ($res->answerable()) {
                   8593:                                         $activeblock = 1;
                   8594:                                         last;
                   8595:                                     }
                   8596:                                 }
                   8597:                                 if ($activeblock) {
                   8598:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8599:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8600:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8601:                                          }
                   8602:                                     }
                   8603:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8604:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8605:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8606:                                         }
1.1162    raeburn  8607:                                     }
                   8608:                                 }
                   8609:                             }
                   8610:                         }
                   8611:                     }
                   8612:                 }
                   8613:             }
                   8614:         }
                   8615:     }
1.1172.2.66  raeburn  8616:     return %blockers;
1.1162    raeburn  8617: }
                   8618: 
1.1172.2.66  raeburn  8619: sub has_comm_blocking {
1.1172.2.118.  .9(raebu 8620:20):     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8621:     my @blockers;
                   8622:     return unless ($env{'request.course.id'});
                   8623:     return unless ($priv eq 'bre');
                   8624:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8625:     return if ($env{'request.state'} eq 'construct');
1.1172.2.118.  .9(raebu 8626:20):     my %blockinfo;
                   8627:20):     if (ref($blocks) eq 'HASH') {
                   8628:20):         %blockinfo = &get_commblock_resources($blocks);
                   8629:20):     } else {
                   8630:20):         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8631:20):         %blockinfo = %cachedblockers;
                   8632:20):     }
                   8633:20):     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8634:     my (%possibles,@symbs);
                   8635:     if (!$symb) {
1.1172.2.118.  .9(raebu 8636:20):         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8637:     }
1.1172.2.66  raeburn  8638:     if ($symb) {
                   8639:         @symbs = ($symb);
                   8640:     } elsif (keys(%possibles)) {
                   8641:         @symbs = keys(%possibles);
                   8642:     }
                   8643:     my $noblock;
                   8644:     foreach my $symb (@symbs) {
                   8645:         last if ($noblock);
                   8646:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.118.  .9(raebu 8647:20):         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8648:             if ($block =~ /^firstaccess____(.+)$/) {
                   8649:                 my $item = $1;
1.1172.2.118.  .8(raebu 8650:20):                 unless ($blocked) {
                   8651:20):                     if (($item eq $map) || ($item eq $symb)) {
                   8652:20):                         $noblock = 1;
                   8653:20):                         last;
                   8654:20):                     }
1.1172.2.66  raeburn  8655:                 }
1.1162    raeburn  8656:             }
1.1172.2.118.  .9(raebu 8657:20):             if (ref($blockinfo{$block}) eq 'HASH') {
                   8658:20):                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8659:20):                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8660:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8661:                             push(@blockers,$block);
                   8662:                         }
                   8663:                     }
                   8664:                 }
1.1172.2.118.  .9(raebu 8665:20):                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8666:20):                     if ($blockinfo{$block}{'maps'}{$map}) {
          .8(raebu 8667:20):                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8668:20):                             push(@blockers,$block);
                   8669:20):                         }
1.1172.2.66  raeburn  8670:                     }
                   8671:                 }
1.1162    raeburn  8672:             }
                   8673:         }
                   8674:     }
1.1172.2.118.  .8(raebu 8675:20):     unless ($noblock) {
                   8676:20):         return @blockers;
                   8677:20):     }
                   8678:20):     return;
1.1172.2.66  raeburn  8679: }
1.1162    raeburn  8680: }
                   8681: 
1.1172.2.66  raeburn  8682: # -------------------------------- Deversion and split uri into path an filename
                   8683: 
1.1133    foxr     8684: #
1.1172.2.66  raeburn  8685: #   Removes the version from a URI and
1.1133    foxr     8686: #   splits it in to its filename and path to the filename.
                   8687: #   Seems like File::Basename could have done this more clearly.
                   8688: #   Parameters:
                   8689: #      $uri   - input URI
                   8690: #   Returns:
                   8691: #     Two element list consisting of 
                   8692: #     $pathname  - the URI up to and excluding the trailing /
                   8693: #     $filename  - The part of the URI following the last /
                   8694: #  NOTE:
                   8695: #    Another realization of this is simply:
                   8696: #    use File::Basename;
                   8697: #    ...
                   8698: #    $uri = shift;
                   8699: #    $filename = basename($uri);
                   8700: #    $path     = dirname($uri);
                   8701: #    return ($filename, $path);
                   8702: #
                   8703: #     The implementation below is probably faster however.
                   8704: #
1.710     albertel 8705: sub split_uri_for_cond {
                   8706:     my $uri=&deversion(&declutter(shift));
                   8707:     my @uriparts=split(/\//,$uri);
                   8708:     my $filename=pop(@uriparts);
                   8709:     my $pathname=join('/',@uriparts);
                   8710:     return ($pathname,$filename);
                   8711: }
1.232     www      8712: # --------------------------------------------------- Is a resource on the map?
                   8713: 
                   8714: sub is_on_map {
1.710     albertel 8715:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8716:     #Trying to find the conditional for the file
1.620     albertel 8717:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8718: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8719:     if ($match) {
1.289     bowersj2 8720: 	return (1,$1);
                   8721:     } else {
1.434     www      8722: 	return (0,0);
1.289     bowersj2 8723:     }
1.12      www      8724: }
                   8725: 
1.427     www      8726: # --------------------------------------------------------- Get symb from alias
                   8727: 
                   8728: sub get_symb_from_alias {
                   8729:     my $symb=shift;
                   8730:     my ($map,$resid,$url)=&decode_symb($symb);
                   8731: # Already is a symb
                   8732:     if ($url) { return $symb; }
                   8733: # Must be an alias
                   8734:     my $aliassymb='';
                   8735:     my %bighash;
1.620     albertel 8736:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8737:                             &GDBM_READER(),0640)) {
                   8738:         my $rid=$bighash{'mapalias_'.$symb};
                   8739: 	if ($rid) {
                   8740: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8741: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8742: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8743: 	}
                   8744:         untie %bighash;
                   8745:     }
                   8746:     return $aliassymb;
                   8747: }
                   8748: 
1.12      www      8749: # ----------------------------------------------------------------- Define Role
                   8750: 
                   8751: sub definerole {
                   8752:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8753:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8754:     foreach my $role (split(':',$sysrole)) {
                   8755: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8756:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8757:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8758: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8759:                return "refused:s:$crole&$cqual"; 
                   8760:             }
                   8761:         }
1.191     harris41 8762:     }
1.800     albertel 8763:     foreach my $role (split(':',$domrole)) {
                   8764: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8765:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8766:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8767: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8768:                return "refused:d:$crole&$cqual"; 
                   8769:             }
                   8770:         }
1.191     harris41 8771:     }
1.800     albertel 8772:     foreach my $role (split(':',$courole)) {
                   8773: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8774:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8775:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8776: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8777:                return "refused:c:$crole&$cqual"; 
                   8778:             }
                   8779:         }
1.191     harris41 8780:     }
1.1172.2.84  raeburn  8781:     my $uhome;
                   8782:     if (($uname ne '') && ($udom ne '')) {
                   8783:         $uhome = &homeserver($uname,$udom);
                   8784:         return $uhome if ($uhome eq 'no_host');
                   8785:     } else {
                   8786:         $uname = $env{'user.name'};
                   8787:         $udom = $env{'user.domain'};
                   8788:         $uhome = $env{'user.home'};
                   8789:     }
1.620     albertel 8790:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8791:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8792:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8793:     return reply($command,$uhome);
1.12      www      8794:   } else {
                   8795:     return 'refused';
                   8796:   }
1.105     harris41 8797: }
                   8798: 
                   8799: # ---------------- Make a metadata query against the network of library servers
                   8800: 
                   8801: sub metadata_query {
1.1172.2.33  raeburn  8802:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8803:     my %rhash;
1.845     albertel 8804:     my %libserv = &all_library();
1.244     matthew  8805:     my @server_list = (defined($server_array) ? @$server_array
                   8806:                                               : keys(%libserv) );
                   8807:     for my $server (@server_list) {
1.1172.2.33  raeburn  8808:         my $domains = '';
                   8809:         if (ref($domains_hash) eq 'HASH') {
                   8810:             $domains = $domains_hash->{$server};    
                   8811:         }
1.118     harris41 8812: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8813: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8814: 	    $rhash{$server}=$reply;
                   8815: 	}
                   8816: 	else {
                   8817: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8818: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8819: 			     $server);
                   8820: 	    $rhash{$server}=$reply;
                   8821: 	}
1.112     harris41 8822:     }
1.118     harris41 8823:     return \%rhash;
1.240     www      8824: }
                   8825: 
                   8826: # ----------------------------------------- Send log queries and wait for reply
                   8827: 
                   8828: sub log_query {
                   8829:     my ($uname,$udom,$query,%filters)=@_;
                   8830:     my $uhome=&homeserver($uname,$udom);
                   8831:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8832:     my $uhost=&hostname($uhome);
1.800     albertel 8833:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8834:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8835:                        $uhome);
1.479     albertel 8836:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8837:     return get_query_reply($queryid);
                   8838: }
                   8839: 
1.818     raeburn  8840: # -------------------------- Update MySQL table for portfolio file
                   8841: 
                   8842: sub update_portfolio_table {
1.821     raeburn  8843:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8844:     if ($group ne '') {
                   8845:         $file_name =~s /^\Q$group\E//;
                   8846:     }
1.818     raeburn  8847:     my $homeserver = &homeserver($uname,$udom);
                   8848:     my $queryid=
1.821     raeburn  8849:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8850:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8851:     my $reply = &get_query_reply($queryid);
                   8852:     return $reply;
                   8853: }
                   8854: 
1.899     raeburn  8855: # -------------------------- Update MySQL allusers table
                   8856: 
                   8857: sub update_allusers_table {
                   8858:     my ($uname,$udom,$names) = @_;
                   8859:     my $homeserver = &homeserver($uname,$udom);
                   8860:     my $queryid=
                   8861:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8862:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8863:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8864:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8865:                'generation='.&escape($names->{'generation'}).'%%'.
                   8866:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8867:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8868:     return;
1.899     raeburn  8869: }
                   8870: 
1.508     raeburn  8871: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8872: 
                   8873: sub fetch_enrollment_query {
1.511     raeburn  8874:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8875:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8876:     my $maxtries = 1;
1.508     raeburn  8877:     if ($context eq 'automated') {
                   8878:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8879:         $sleep = 2;
                   8880:         $loopmax = 100;
1.547     raeburn  8881:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8882:     } else {
                   8883:         $homeserver = &homeserver($cnum,$dom);
                   8884:     }
1.838     albertel 8885:     my $host=&hostname($homeserver);
1.506     raeburn  8886:     my $cmd = '';
1.1000    raeburn  8887:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8888:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8889:     }
                   8890:     $cmd =~ s/%%$//;
                   8891:     $cmd = &escape($cmd);
                   8892:     my $query = 'fetchenrollment';
1.620     albertel 8893:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8894:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8895:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8896:         return 'error: '.$queryid;
                   8897:     }
1.1172.2.93  raeburn  8898:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8899:     my $tries = 1;
                   8900:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8901:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8902:         $tries ++;
                   8903:     }
1.526     raeburn  8904:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8905:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8906:     } else {
1.901     albertel 8907:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8908:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8909:             foreach my $line (@responses) {
                   8910:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8911:                 $$replyref{$key} = $value;
                   8912:             }
                   8913:         } else {
1.1117    foxr     8914:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8915:             foreach my $line (@responses) {
                   8916:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8917:                 $$replyref{$key} = $value;
                   8918:                 if ($value > 0) {
1.800     albertel 8919:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8920:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8921:                         my $destname = $pathname.'/'.$filename;
                   8922:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8923:                         if ($xml_classlist =~ /^error/) {
                   8924:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8925:                         } else {
1.1172.2.96  raeburn  8926:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8927:                                 print FILE &unescape($xml_classlist);
                   8928:                                 close(FILE);
1.526     raeburn  8929:                             } else {
                   8930:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8931:                             }
                   8932:                         }
                   8933:                     }
                   8934:                 }
                   8935:             }
                   8936:         }
                   8937:         return 'ok';
                   8938:     }
                   8939:     return 'error';
                   8940: }
                   8941: 
1.242     www      8942: sub get_query_reply {
1.1172.2.79  raeburn  8943:     my ($queryid,$sleep,$loopmax) = @_;
                   8944:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8945:         $sleep = 0.2;
                   8946:     }
                   8947:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8948:         $loopmax = 100;
                   8949:     }
1.1117    foxr     8950:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8951:     my $reply='';
1.1172.2.79  raeburn  8952:     for (1..$loopmax) {
                   8953: 	sleep($sleep);
1.240     www      8954:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8955: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8956: 		$reply = join('',<$fh>);
                   8957: 		close($fh);
1.240     www      8958: 	   } else { return 'error: reply_file_error'; }
1.242     www      8959:            return &unescape($reply);
                   8960: 	}
1.240     www      8961:     }
1.242     www      8962:     return 'timeout:'.$queryid;
1.240     www      8963: }
                   8964: 
                   8965: sub courselog_query {
1.241     www      8966: #
                   8967: # possible filters:
                   8968: # url: url or symb
                   8969: # username
                   8970: # domain
                   8971: # action: view, submit, grade
                   8972: # start: timestamp
                   8973: # end: timestamp
                   8974: #
1.240     www      8975:     my (%filters)=@_;
1.620     albertel 8976:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8977:     if ($filters{'url'}) {
                   8978: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8979:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8980:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8981:     }
1.620     albertel 8982:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8983:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8984:     return &log_query($cname,$cdom,'courselog',%filters);
                   8985: }
                   8986: 
                   8987: sub userlog_query {
1.858     raeburn  8988: #
                   8989: # possible filters:
                   8990: # action: log check role
                   8991: # start: timestamp
                   8992: # end: timestamp
                   8993: #
1.240     www      8994:     my ($uname,$udom,%filters)=@_;
                   8995:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8996: }
                   8997: 
1.506     raeburn  8998: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8999: 
                   9000: sub auto_run {
1.508     raeburn  9001:     my ($cnum,$cdom) = @_;
1.876     raeburn  9002:     my $response = 0;
                   9003:     my $settings;
                   9004:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9005:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9006:         $settings = $domconfig{'autoenroll'};
                   9007:         if ($settings->{'run'} eq '1') {
                   9008:             $response = 1;
                   9009:         }
                   9010:     } else {
1.934     raeburn  9011:         my $homeserver;
                   9012:         if (&is_course($cdom,$cnum)) {
                   9013:             $homeserver = &homeserver($cnum,$cdom);
                   9014:         } else {
                   9015:             $homeserver = &domain($cdom,'primary');
                   9016:         }
                   9017:         if ($homeserver ne 'no_host') {
                   9018:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9019:         }
1.876     raeburn  9020:     }
1.506     raeburn  9021:     return $response;
                   9022: }
1.776     albertel 9023: 
1.506     raeburn  9024: sub auto_get_sections {
1.508     raeburn  9025:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9026:     my $homeserver;
                   9027:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9028:         $homeserver = &homeserver($cnum,$cdom);
                   9029:     }
                   9030:     if (!defined($homeserver)) { 
                   9031:         if ($cdom =~ /^$match_domain$/) {
                   9032:             $homeserver = &domain($cdom,'primary');
                   9033:         }
                   9034:     }
                   9035:     my @secs;
                   9036:     if (defined($homeserver)) {
                   9037:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9038:         unless ($response eq 'refused') {
                   9039:             @secs = split(/:/,$response);
                   9040:         }
1.506     raeburn  9041:     }
                   9042:     return @secs;
                   9043: }
1.776     albertel 9044: 
1.506     raeburn  9045: sub auto_new_course {
1.1099    raeburn  9046:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9047:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9048:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9049:     return $response;
                   9050: }
1.776     albertel 9051: 
1.506     raeburn  9052: sub auto_validate_courseID {
1.508     raeburn  9053:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9054:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9055:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9056:     return $response;
                   9057: }
1.776     albertel 9058: 
1.1007    raeburn  9059: sub auto_validate_instcode {
1.1020    raeburn  9060:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9061:     my ($homeserver,$response);
                   9062:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9063:         $homeserver = &homeserver($cnum,$cdom);
                   9064:     }
                   9065:     if (!defined($homeserver)) {
                   9066:         if ($cdom =~ /^$match_domain$/) {
                   9067:             $homeserver = &domain($cdom,'primary');
                   9068:         }
                   9069:     }
1.1065    raeburn  9070:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9071:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9072:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9073:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9074: }
                   9075: 
1.506     raeburn  9076: sub auto_create_password {
1.873     raeburn  9077:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9078:     my ($homeserver,$response);
1.506     raeburn  9079:     my $create_passwd = 0;
                   9080:     my $authchk = '';
1.873     raeburn  9081:     if ($udom =~ /^$match_domain$/) {
                   9082:         $homeserver = &domain($udom,'primary');
                   9083:     }
                   9084:     if ($homeserver eq '') {
                   9085:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9086:             $homeserver = &homeserver($cnum,$cdom);
                   9087:         }
                   9088:     }
                   9089:     if ($homeserver eq '') {
                   9090:         $authchk = 'nodomain';
1.506     raeburn  9091:     } else {
1.873     raeburn  9092:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9093:         if ($response eq 'refused') {
                   9094:             $authchk = 'refused';
                   9095:         } else {
1.901     albertel 9096:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9097:         }
1.506     raeburn  9098:     }
                   9099:     return ($authparam,$create_passwd,$authchk);
                   9100: }
                   9101: 
1.706     raeburn  9102: sub auto_photo_permission {
                   9103:     my ($cnum,$cdom,$students) = @_;
                   9104:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9105:     my ($outcome,$perm_reqd,$conditions) = 
                   9106: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9107:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9108: 	return (undef,undef);
                   9109:     }
1.706     raeburn  9110:     return ($outcome,$perm_reqd,$conditions);
                   9111: }
                   9112: 
                   9113: sub auto_checkphotos {
                   9114:     my ($uname,$udom,$pid) = @_;
                   9115:     my $homeserver = &homeserver($uname,$udom);
                   9116:     my ($result,$resulttype);
                   9117:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9118: 				   &escape($uname).':'.&escape($pid),
                   9119: 				   $homeserver));
1.709     albertel 9120:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9121: 	return (undef,undef);
                   9122:     }
1.706     raeburn  9123:     if ($outcome) {
                   9124:         ($result,$resulttype) = split(/:/,$outcome);
                   9125:     } 
                   9126:     return ($result,$resulttype);
                   9127: }
                   9128: 
                   9129: sub auto_photochoice {
                   9130:     my ($cnum,$cdom) = @_;
                   9131:     my $homeserver = &homeserver($cnum,$cdom);
                   9132:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9133: 						       &escape($cdom),
                   9134: 						       $homeserver)));
1.709     albertel 9135:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9136: 	return (undef,undef);
                   9137:     }
1.706     raeburn  9138:     return ($update,$comment);
                   9139: }
                   9140: 
                   9141: sub auto_photoupdate {
                   9142:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9143:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9144:     my $host=&hostname($homeserver);
1.706     raeburn  9145:     my $cmd = '';
                   9146:     my $maxtries = 1;
1.800     albertel 9147:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9148:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9149:     }
                   9150:     $cmd =~ s/%%$//;
                   9151:     $cmd = &escape($cmd);
                   9152:     my $query = 'institutionalphotos';
                   9153:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9154:     unless ($queryid=~/^\Q$host\E\_/) {
                   9155:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9156:         return 'error: '.$queryid;
                   9157:     }
                   9158:     my $reply = &get_query_reply($queryid);
                   9159:     my $tries = 1;
                   9160:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9161:         $reply = &get_query_reply($queryid);
                   9162:         $tries ++;
                   9163:     }
                   9164:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9165:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9166:     } else {
                   9167:         my @responses = split(/:/,$reply);
                   9168:         my $outcome = shift(@responses); 
                   9169:         foreach my $item (@responses) {
                   9170:             my ($key,$value) = split(/=/,$item);
                   9171:             $$photo{$key} = $value;
                   9172:         }
                   9173:         return $outcome;
                   9174:     }
                   9175:     return 'error';
                   9176: }
                   9177: 
1.521     raeburn  9178: sub auto_instcode_format {
1.793     albertel 9179:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9180: 	$cat_order) = @_;
1.521     raeburn  9181:     my $courses = '';
1.772     raeburn  9182:     my @homeservers;
1.521     raeburn  9183:     if ($caller eq 'global') {
1.841     albertel 9184: 	my %servers = &get_servers($codedom,'library');
                   9185: 	foreach my $tryserver (keys(%servers)) {
                   9186: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9187: 		push(@homeservers,$tryserver);
                   9188: 	    }
1.584     raeburn  9189:         }
1.1022    raeburn  9190:     } elsif ($caller eq 'requests') {
                   9191:         if ($codedom =~ /^$match_domain$/) {
                   9192:             my $chome = &domain($codedom,'primary');
                   9193:             unless ($chome eq 'no_host') {
                   9194:                 push(@homeservers,$chome);
                   9195:             }
                   9196:         }
1.521     raeburn  9197:     } else {
1.772     raeburn  9198:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9199:     }
1.793     albertel 9200:     foreach my $code (keys(%{$instcodes})) {
                   9201:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9202:     }
                   9203:     chop($courses);
1.772     raeburn  9204:     my $ok_response = 0;
                   9205:     my $response;
                   9206:     while (@homeservers > 0 && $ok_response == 0) {
                   9207:         my $server = shift(@homeservers); 
                   9208:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9209:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9210:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9211: 		split(/:/,$response);
1.772     raeburn  9212:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9213:             push(@{$codetitles},&str2array($codetitles_str));
                   9214:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9215:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9216:             $ok_response = 1;
                   9217:         }
                   9218:     }
                   9219:     if ($ok_response) {
1.521     raeburn  9220:         return 'ok';
1.772     raeburn  9221:     } else {
                   9222:         return $response;
1.521     raeburn  9223:     }
                   9224: }
                   9225: 
1.792     raeburn  9226: sub auto_instcode_defaults {
                   9227:     my ($domain,$returnhash,$code_order) = @_;
                   9228:     my @homeservers;
1.841     albertel 9229: 
                   9230:     my %servers = &get_servers($domain,'library');
                   9231:     foreach my $tryserver (keys(%servers)) {
                   9232: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9233: 	    push(@homeservers,$tryserver);
                   9234: 	}
1.792     raeburn  9235:     }
1.841     albertel 9236: 
1.792     raeburn  9237:     my $response;
1.841     albertel 9238:     foreach my $server (@homeservers) {
1.792     raeburn  9239:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9240:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9241: 	
                   9242: 	foreach my $pair (split(/\&/,$response)) {
                   9243: 	    my ($name,$value)=split(/\=/,$pair);
                   9244: 	    if ($name eq 'code_order') {
                   9245: 		@{$code_order} = split(/\&/,&unescape($value));
                   9246: 	    } else {
                   9247: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9248: 	    }
                   9249: 	}
                   9250: 	return 'ok';
1.792     raeburn  9251:     }
1.841     albertel 9252: 
                   9253:     return $response;
1.1003    raeburn  9254: }
                   9255: 
                   9256: sub auto_possible_instcodes {
1.1007    raeburn  9257:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9258:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9259:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9260:         return;
                   9261:     }
1.1003    raeburn  9262:     my (@homeservers,$uhome);
                   9263:     if (defined(&domain($domain,'primary'))) {
                   9264:         $uhome=&domain($domain,'primary');
                   9265:         push(@homeservers,&domain($domain,'primary'));
                   9266:     } else {
                   9267:         my %servers = &get_servers($domain,'library');
                   9268:         foreach my $tryserver (keys(%servers)) {
                   9269:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9270:                 push(@homeservers,$tryserver);
                   9271:             }
                   9272:         }
                   9273:     }
                   9274:     my $response;
                   9275:     foreach my $server (@homeservers) {
                   9276:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9277:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9278:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9279:             split(':',$response);
                   9280:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9281:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9282:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9283:             my ($name,$value)=split('=',$item);
                   9284:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9285:         }
                   9286:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9287:             my ($name,$value)=split('=',$item);
                   9288:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9289:         }
                   9290:         return 'ok';
                   9291:     }
                   9292:     return $response;
                   9293: }
1.792     raeburn  9294: 
1.1010    raeburn  9295: sub auto_courserequest_checks {
                   9296:     my ($dom) = @_;
1.1020    raeburn  9297:     my ($homeserver,%validations);
                   9298:     if ($dom =~ /^$match_domain$/) {
                   9299:         $homeserver = &domain($dom,'primary');
                   9300:     }
                   9301:     unless ($homeserver eq 'no_host') {
                   9302:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9303:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9304:             my @items = split(/&/,$response);
                   9305:             foreach my $item (@items) {
                   9306:                 my ($key,$value) = split('=',$item);
                   9307:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9308:             }
                   9309:         }
                   9310:     }
1.1010    raeburn  9311:     return %validations; 
                   9312: }
                   9313: 
1.1020    raeburn  9314: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9315:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9316:     my ($homeserver,$response);
                   9317:     if ($dom =~ /^$match_domain$/) {
                   9318:         $homeserver = &domain($dom,'primary');
                   9319:     }
1.1172.2.43  raeburn  9320:     unless ($homeserver eq 'no_host') {
                   9321:         my $customdata;
                   9322:         if (ref($custominfo) eq 'HASH') {
                   9323:             $customdata = &freeze_escape($custominfo);
                   9324:         }
1.1020    raeburn  9325:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9326:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9327:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9328:                                     $customdata,$homeserver));
1.1020    raeburn  9329:     }
                   9330:     return $response;
                   9331: }
                   9332: 
1.777     albertel 9333: sub auto_validate_class_sec {
1.918     raeburn  9334:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9335:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9336:     my $ownerlist;
                   9337:     if (ref($owners) eq 'ARRAY') {
                   9338:         $ownerlist = join(',',@{$owners});
                   9339:     } else {
                   9340:         $ownerlist = $owners;
                   9341:     }
1.773     raeburn  9342:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9343:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9344:     return $response;
                   9345: }
                   9346: 
1.1172.2.94  raeburn  9347: sub auto_validate_instclasses {
                   9348:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9349:     my ($homeserver,%validations);
                   9350:     $homeserver = &homeserver($cnum,$cdom);
                   9351:     unless ($homeserver eq 'no_host') {
                   9352:         my $ownerlist;
                   9353:         if (ref($owners) eq 'ARRAY') {
                   9354:             $ownerlist = join(',',@{$owners});
                   9355:         } else {
                   9356:             $ownerlist = $owners;
                   9357:         }
                   9358:         if (ref($classesref) eq 'HASH') {
                   9359:             my $classes = &freeze_escape($classesref);
                   9360:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9361:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9362:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9363:                 my @items = split(/&/,$response);
                   9364:                 foreach my $item (@items) {
                   9365:                     my ($key,$value) = split('=',$item);
                   9366:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9367:                 }
                   9368:             }
                   9369:         }
                   9370:     }
                   9371:     return %validations;
                   9372: }
                   9373: 
1.1172.2.38  raeburn  9374: sub auto_crsreq_update {
                   9375:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9376:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9377:     my ($homeserver,%crsreqresponse);
                   9378:     if ($cdom =~ /^$match_domain$/) {
                   9379:         $homeserver = &domain($cdom,'primary');
                   9380:     }
                   9381:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9382:         my $info;
                   9383:         if (ref($inbound) eq 'HASH') {
                   9384:             $info = &freeze_escape($inbound);
                   9385:         }
                   9386:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9387:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9388:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9389:                             &escape($title).':'.&escape($code).':'.
                   9390:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9391:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9392:             my @items = split(/&/,$response);
                   9393:             foreach my $item (@items) {
                   9394:                 my ($key,$value) = split('=',$item);
                   9395:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9396:             }
                   9397:         }
                   9398:     }
                   9399:     return \%crsreqresponse;
                   9400: }
                   9401: 
1.1172.2.78  raeburn  9402: sub auto_export_grades {
                   9403:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9404:     my ($homeserver,%exportresponse);
                   9405:     if ($cdom =~ /^$match_domain$/) {
                   9406:         $homeserver = &domain($cdom,'primary');
                   9407:     }
                   9408:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9409:         my $info;
                   9410:         if (ref($inforef) eq 'HASH') {
                   9411:             $info = &freeze_escape($inforef);
                   9412:         }
                   9413:         if (ref($gradesref) eq 'HASH') {
                   9414:             my $grades = &freeze_escape($gradesref);
                   9415:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9416:                                 $info.':'.$grades,$homeserver);
                   9417:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9418:                 my @items = split(/&/,$response);
                   9419:                 foreach my $item (@items) {
                   9420:                     my ($key,$value) = split('=',$item);
                   9421:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9422:                 }
                   9423:             }
                   9424:         }
                   9425:     }
                   9426:     return \%exportresponse;
                   9427: }
                   9428: 
1.1172.2.68  raeburn  9429: sub check_instcode_cloning {
                   9430:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9431:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9432:         return;
                   9433:     }
                   9434:     my $canclone;
                   9435:     if (@{$code_order} > 0) {
                   9436:         my $instcoderegexp ='^';
                   9437:         my @clonecodes = split(/\&/,$cloner);
                   9438:         foreach my $item (@{$code_order}) {
                   9439:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9440:                 foreach my $pair (@clonecodes) {
                   9441:                     my ($key,$val) = split(/\=/,$pair,2);
                   9442:                     $val = &unescape($val);
                   9443:                     if ($key eq $item) {
                   9444:                         $instcoderegexp .= '('.$val.')';
                   9445:                         last;
                   9446:                     }
                   9447:                 }
                   9448:             } else {
                   9449:                 $instcoderegexp .= $codedefaults->{$item};
                   9450:             }
                   9451:         }
                   9452:         $instcoderegexp .= '$';
                   9453:         my (@from,@to);
                   9454:         eval {
                   9455:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9456:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9457:         };
                   9458:         if ((@from > 0) && (@to > 0)) {
                   9459:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9460:             if (!@diffs) {
                   9461:                 $canclone = 1;
                   9462:             }
                   9463:         }
                   9464:     }
                   9465:     return $canclone;
                   9466: }
                   9467: 
                   9468: sub default_instcode_cloning {
                   9469:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9470:     my (%codedefaults,@code_order,$canclone);
                   9471:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9472:         %codedefaults = %{$codedefaultsref};
                   9473:         @code_order = @{$codeorderref};
                   9474:     } elsif ($clonedom) {
                   9475:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9476:     }
                   9477:     if (($domdefclone) && (@code_order)) {
                   9478:         my @clonecodes = split(/\+/,$domdefclone);
                   9479:         my $instcoderegexp ='^';
                   9480:         foreach my $item (@code_order) {
                   9481:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9482:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9483:             } else {
                   9484:                 $instcoderegexp .= $codedefaults{$item};
                   9485:             }
                   9486:         }
                   9487:         $instcoderegexp .= '$';
                   9488:         my (@from,@to);
                   9489:         eval {
                   9490:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9491:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9492:         };
                   9493:         if ((@from > 0) && (@to > 0)) {
                   9494:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9495:             if (!@diffs) {
                   9496:                 $canclone = 1;
                   9497:             }
                   9498:         }
                   9499:     }
                   9500:     return $canclone;
                   9501: }
                   9502: 
1.679     raeburn  9503: # ------------------------------------------------------- Course Group routines
                   9504: 
                   9505: sub get_coursegroups {
1.809     raeburn  9506:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9507:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9508: }
                   9509: 
1.679     raeburn  9510: sub modify_coursegroup {
                   9511:     my ($cdom,$cnum,$groupsettings) = @_;
                   9512:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9513: }
                   9514: 
1.809     raeburn  9515: sub toggle_coursegroup_status {
                   9516:     my ($cdom,$cnum,$group,$action) = @_;
                   9517:     my ($from_namespace,$to_namespace);
                   9518:     if ($action eq 'delete') {
                   9519:         $from_namespace = 'coursegroups';
                   9520:         $to_namespace = 'deleted_groups';
                   9521:     } else {
                   9522:         $from_namespace = 'deleted_groups';
                   9523:         $to_namespace = 'coursegroups';
                   9524:     }
                   9525:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9526:     if (my $tmp = &error(%curr_group)) {
                   9527:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9528:         return ('read error',$tmp);
                   9529:     } else {
                   9530:         my %savedsettings = %curr_group; 
1.809     raeburn  9531:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9532:         my $deloutcome;
                   9533:         if ($result eq 'ok') {
1.809     raeburn  9534:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9535:         } else {
                   9536:             return ('write error',$result);
                   9537:         }
                   9538:         if ($deloutcome eq 'ok') {
                   9539:             return 'ok';
                   9540:         } else {
                   9541:             return ('delete error',$deloutcome);
                   9542:         }
                   9543:     }
                   9544: }
                   9545: 
1.679     raeburn  9546: sub modify_group_roles {
1.957     raeburn  9547:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9548:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9549:     my $role = 'gr/'.&escape($userprivs);
                   9550:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9551:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9552:     if ($result eq 'ok') {
                   9553:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9554:     }
1.679     raeburn  9555:     return $result;
                   9556: }
                   9557: 
                   9558: sub modify_coursegroup_membership {
                   9559:     my ($cdom,$cnum,$membership) = @_;
                   9560:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9561:     return $result;
                   9562: }
                   9563: 
1.682     raeburn  9564: sub get_active_groups {
                   9565:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9566:     my $now = time;
                   9567:     my %groups = ();
                   9568:     foreach my $key (keys(%env)) {
1.811     albertel 9569:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9570:             my ($start,$end) = split(/\./,$env{$key});
                   9571:             if (($end!=0) && ($end<$now)) { next; }
                   9572:             if (($start!=0) && ($start>$now)) { next; }
                   9573:             if ($1 eq $cdom && $2 eq $cnum) {
                   9574:                 $groups{$3} = $env{$key} ;
                   9575:             }
                   9576:         }
                   9577:     }
                   9578:     return %groups;
                   9579: }
                   9580: 
1.683     raeburn  9581: sub get_group_membership {
                   9582:     my ($cdom,$cnum,$group) = @_;
                   9583:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9584: }
                   9585: 
                   9586: sub get_users_groups {
                   9587:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9588:     my @usersgroups;
1.683     raeburn  9589:     my $cachetime=1800;
                   9590: 
                   9591:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9592:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9593:     if (defined($cached)) {
1.734     albertel 9594:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9595:     } else {  
                   9596:         $grouplist = '';
1.816     raeburn  9597:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9598:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9599:         my $access_end = $env{'course.'.$courseid.
                   9600:                               '.default_enrollment_end_date'};
                   9601:         my $now = time;
                   9602:         foreach my $key (keys(%roleshash)) {
                   9603:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9604:                 my $group = $1;
                   9605:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9606:                     my $start = $2;
                   9607:                     my $end = $1;
                   9608:                     if ($start == -1) { next; } # deleted from group
                   9609:                     if (($start!=0) && ($start>$now)) { next; }
                   9610:                     if (($end!=0) && ($end<$now)) {
                   9611:                         if ($access_end && $access_end < $now) {
                   9612:                             if ($access_end - $end < 86400) {
                   9613:                                 push(@usersgroups,$group);
1.733     raeburn  9614:                             }
                   9615:                         }
1.817     raeburn  9616:                         next;
1.733     raeburn  9617:                     }
1.817     raeburn  9618:                     push(@usersgroups,$group);
1.683     raeburn  9619:                 }
                   9620:             }
                   9621:         }
1.817     raeburn  9622:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9623:         $grouplist = join(':',@usersgroups);
                   9624:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9625:     }
1.733     raeburn  9626:     return @usersgroups;
1.683     raeburn  9627: }
                   9628: 
                   9629: sub devalidate_getgroups_cache {
                   9630:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9631:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9632: 
1.683     raeburn  9633:     my $hashid="$udom:$uname:$courseid";
                   9634:     &devalidate_cache_new('getgroups',$hashid);
                   9635: }
                   9636: 
1.12      www      9637: # ------------------------------------------------------------------ Plain Text
                   9638: 
                   9639: sub plaintext {
1.988     raeburn  9640:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9641:     if ($short =~ m{^cr/}) {
1.758     albertel 9642: 	return (split('/',$short))[-1];
                   9643:     }
1.742     raeburn  9644:     if (!defined($cid)) {
                   9645:         $cid = $env{'request.course.id'};
                   9646:     }
                   9647:     my %rolenames = (
1.1008    raeburn  9648:                       Course    => 'std',
                   9649:                       Community => 'alt1',
1.742     raeburn  9650:                     );
1.1037    raeburn  9651:     if ($cid ne '') {
                   9652:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9653:             unless ($forcedefault) {
                   9654:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9655:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9656:                 return &Apache::lonlocal::mt($roletext);
                   9657:             }
                   9658:         }
                   9659:     }
                   9660:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9661:         (defined($rolenames{$type})) && 
                   9662:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9663:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9664:     } elsif ($cid ne '') {
                   9665:         my $crstype = $env{'course.'.$cid.'.type'};
                   9666:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9667:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9668:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9669:         }
1.742     raeburn  9670:     }
1.1037    raeburn  9671:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9672: }
                   9673: 
                   9674: # ----------------------------------------------------------------- Assign Role
                   9675: 
                   9676: sub assignrole {
1.957     raeburn  9677:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9678:         $context)=@_;
1.21      www      9679:     my $mrole;
                   9680:     if ($role =~ /^cr\//) {
1.393     www      9681:         my $cwosec=$url;
1.811     albertel 9682:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9683: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9684:            my $refused = 1;
                   9685:            if ($context eq 'requestcourses') {
                   9686:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9687:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9688:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9689:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9690:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9691:                            if ($crsenv{'internal.courseowner'} eq
                   9692:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9693:                                $refused = '';
                   9694:                            }
                   9695:                        }
                   9696:                    }
                   9697:                }
                   9698:            }
                   9699:            if ($refused) {
                   9700:                &logthis('Refused custom assignrole: '.
                   9701:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9702:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9703:                return 'refused';
                   9704:            }
1.104     www      9705:         }
1.21      www      9706:         $mrole='cr';
1.678     raeburn  9707:     } elsif ($role =~ /^gr\//) {
                   9708:         my $cwogrp=$url;
1.811     albertel 9709:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9710:         unless (&allowed('mdg',$cwogrp)) {
                   9711:             &logthis('Refused group assignrole: '.
                   9712:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9713:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9714:             return 'refused';
                   9715:         }
                   9716:         $mrole='gr';
1.21      www      9717:     } else {
1.82      www      9718:         my $cwosec=$url;
1.811     albertel 9719:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9720:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9721:             my $refused;
                   9722:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9723:                 if (!(&allowed('c'.$role,$url))) {
                   9724:                     $refused = 1;
                   9725:                 }
                   9726:             } else {
                   9727:                 $refused = 1;
                   9728:             }
1.947     raeburn  9729:             if ($refused) {
1.1045    raeburn  9730:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9731:                 if (!$selfenroll && $context eq 'course') {
                   9732:                     my %crsenv;
                   9733:                     if ($role eq 'cc' || $role eq 'co') {
                   9734:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9735:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9736:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9737:                                 if ($crsenv{'internal.courseowner'} eq 
                   9738:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9739:                                     $refused = '';
                   9740:                                 }
                   9741:                             }
                   9742:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9743:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9744:                                 if ($crsenv{'internal.courseowner'} eq 
                   9745:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9746:                                     $refused = '';
                   9747:                                 }
                   9748:                             }
                   9749:                         }
                   9750:                     }
                   9751:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9752:                     $refused = '';
1.1017    raeburn  9753:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9754:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9755:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9756:                         my $wrongcc;
                   9757:                         if ($cnum =~ /^$match_community$/) {
                   9758:                             $wrongcc = 1 if ($role eq 'cc');
                   9759:                         } else {
                   9760:                             $wrongcc = 1 if ($role eq 'co');
                   9761:                         }
                   9762:                         unless ($wrongcc) {
                   9763:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9764:                             if ($crsenv{'internal.courseowner'} eq 
                   9765:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9766:                                 $refused = '';
                   9767:                             }
1.1017    raeburn  9768:                         }
                   9769:                     }
1.1172.2.9  raeburn  9770:                 } elsif ($context eq 'requestauthor') {
                   9771:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9772:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9773:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9774:                             $refused = '';
                   9775:                         } else {
                   9776:                             my %domdefaults = &get_domain_defaults($udom);
                   9777:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9778:                                 my $checkbystatus;
                   9779:                                 if ($env{'user.adv'}) {
                   9780:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9781:                                     if ($disposition eq 'automatic') {
                   9782:                                         $refused = '';
                   9783:                                     } elsif ($disposition eq '') {
                   9784:                                         $checkbystatus = 1;
                   9785:                                     }
                   9786:                                 } else {
                   9787:                                     $checkbystatus = 1;
                   9788:                                 }
                   9789:                                 if ($checkbystatus) {
                   9790:                                     if ($env{'environment.inststatus'}) {
                   9791:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9792:                                         foreach my $type (@inststatuses) {
                   9793:                                             if (($type ne '') &&
                   9794:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9795:                                                 $refused = '';
                   9796:                                             }
                   9797:                                         }
                   9798:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9799:                                         $refused = '';
                   9800:                                     }
                   9801:                                 }
                   9802:                             }
                   9803:                         }
                   9804:                     }
1.1017    raeburn  9805:                 }
                   9806:                 if ($refused) {
1.947     raeburn  9807:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9808:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9809: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9810:                     return 'refused';
                   9811:                 }
1.932     raeburn  9812:             }
1.1131    raeburn  9813:         } elsif ($role eq 'au') {
                   9814:             if ($url ne '/'.$udom.'/') {
                   9815:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9816:                          ' to assign author role for '.$uname.':'.$udom.
                   9817:                          ' in domain: '.$url.' refused (wrong domain).');
                   9818:                 return 'refused';
                   9819:             }
1.104     www      9820:         }
1.21      www      9821:         $mrole=$role;
                   9822:     }
1.620     albertel 9823:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9824:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9825:     if ($end) { $command.='_'.$end; }
1.21      www      9826:     if ($start) {
                   9827: 	if ($end) { 
1.81      www      9828:            $command.='_'.$start; 
1.21      www      9829:         } else {
1.81      www      9830:            $command.='_0_'.$start;
1.21      www      9831:         }
                   9832:     }
1.739     raeburn  9833:     my $origstart = $start;
                   9834:     my $origend = $end;
1.957     raeburn  9835:     my $delflag;
1.357     www      9836: # actually delete
                   9837:     if ($deleteflag) {
1.373     www      9838: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9839: # modify command to delete the role
1.620     albertel 9840:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9841:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9842: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9843: # set start and finish to negative values for userrolelog
                   9844:            $start=-1;
                   9845:            $end=-1;
1.957     raeburn  9846:            $delflag = 1;
1.357     www      9847:         }
                   9848:     }
                   9849: # send command
1.349     www      9850:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9851: # log new user role if status is ok
1.349     www      9852:     if ($answer eq 'ok') {
1.663     raeburn  9853: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9854:         if (($role eq 'cc') || ($role eq 'in') ||
                   9855:             ($role eq 'ep') || ($role eq 'ad') ||
                   9856:             ($role eq 'ta') || ($role eq 'st') ||
                   9857:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9858:             ($role eq 'co')) {
1.1172.2.13  raeburn  9859: # for course roles, perform group memberships changes triggered by role change.
                   9860:             unless ($role =~ /^gr/) {
                   9861:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9862:                                                  $origstart,$selfenroll,$context);
                   9863:             }
1.1172.2.9  raeburn  9864:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9865:                            $selfenroll,$context);
                   9866:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9867:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9868:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9869:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9870:                            $context);
                   9871:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9872:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9873:                              $context);
                   9874:         }
1.1053    raeburn  9875:         if ($role eq 'cc') {
                   9876:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9877:         }
1.349     www      9878:     }
                   9879:     return $answer;
1.169     harris41 9880: }
                   9881: 
1.1053    raeburn  9882: sub autoupdate_coowners {
                   9883:     my ($url,$end,$start,$uname,$udom) = @_;
                   9884:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9885:     if (($cdom ne '') && ($cnum ne '')) {
                   9886:         my $now = time;
                   9887:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9888:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9889:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9890:             my $instcode = $coursehash{'internal.coursecode'};
                   9891:             if ($instcode ne '') {
1.1056    raeburn  9892:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9893:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9894:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9895:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9896:                         if ($result eq 'valid') {
                   9897:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9898:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9899:                                     push(@newcoowners,$coowner);
                   9900:                                 }
                   9901:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9902:                                     push(@newcoowners,$uname.':'.$udom);
                   9903:                                 }
                   9904:                                 @newcoowners = sort(@newcoowners);
                   9905:                             } else {
                   9906:                                 push(@newcoowners,$uname.':'.$udom);
                   9907:                             }
                   9908:                         } else {
                   9909:                             if ($coursehash{'internal.co-owners'}) {
                   9910:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9911:                                     unless ($coowner eq $uname.':'.$udom) {
                   9912:                                         push(@newcoowners,$coowner);
                   9913:                                     }
                   9914:                                 }
                   9915:                                 unless (@newcoowners > 0) {
                   9916:                                     $delcoowners = 1;
                   9917:                                     $coowners = '';
                   9918:                                 }
                   9919:                             }
                   9920:                         }
                   9921:                         if (@newcoowners || $delcoowners) {
                   9922:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9923:                                             $delcoowners,@newcoowners);
                   9924:                         }
                   9925:                     }
                   9926:                 }
                   9927:             }
                   9928:         }
                   9929:     }
                   9930: }
                   9931: 
                   9932: sub store_coowners {
                   9933:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9934:     my $cid = $cdom.'_'.$cnum;
                   9935:     my ($coowners,$delresult,$putresult);
                   9936:     if (@newcoowners) {
                   9937:         $coowners = join(',',@newcoowners);
                   9938:         my %coownershash = (
                   9939:                             'internal.co-owners' => $coowners,
                   9940:                            );
                   9941:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9942:         if ($putresult eq 'ok') {
                   9943:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9944:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9945:             }
                   9946:         }
                   9947:     }
                   9948:     if ($delcoowners) {
                   9949:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9950:         if ($delresult eq 'ok') {
                   9951:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9952:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9953:             }
                   9954:         }
                   9955:     }
                   9956:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9957:         my %crsinfo =
                   9958:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9959:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9960:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9961:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9962:         }
                   9963:     }
                   9964: }
                   9965: 
1.169     harris41 9966: # -------------------------------------------------- Modify user authentication
1.197     www      9967: # Overrides without validation
                   9968: 
1.169     harris41 9969: sub modifyuserauth {
                   9970:     my ($udom,$uname,$umode,$upass)=@_;
                   9971:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9972:     my $allowed;
                   9973:     if (&allowed('mau',$udom)) {
                   9974:         $allowed = 1;
                   9975:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9976:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9977:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9978:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9979:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9980:         if (($cdom ne '') && ($cnum ne '')) {
                   9981:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9982:             if ($is_owner) {
                   9983:                 $allowed = 1;
                   9984:             }
                   9985:         }
                   9986:     }
                   9987:     unless ($allowed) { return 'refused'; }
1.197     www      9988:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9989:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9990:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9991:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9992: 		     &escape($upass),$uhome);
1.620     albertel 9993:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9994:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9995:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9996:     &log($udom,,$uname,$uhome,
1.620     albertel 9997:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9998:                                      $env{'user.name'}.', '.$umode.
1.197     www      9999:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 10000:     unless ($reply eq 'ok') {
1.197     www      10001:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10002: 	return 'error: '.$reply;
                   10003:     }   
1.170     harris41 10004:     return 'ok';
1.80      www      10005: }
                   10006: 
1.81      www      10007: # --------------------------------------------------------------- Modify a user
1.80      www      10008: 
1.81      www      10009: sub modifyuser {
1.206     matthew  10010:     my ($udom,    $uname, $uid,
                   10011:         $umode,   $upass, $first,
                   10012:         $middle,  $last,  $gene,
1.1058    raeburn  10013:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10014:     $udom= &LONCAPA::clean_domain($udom);
                   10015:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10016:     my $showcandelete = 'none';
                   10017:     if (ref($candelete) eq 'ARRAY') {
                   10018:         if (@{$candelete} > 0) {
                   10019:             $showcandelete = join(', ',@{$candelete});
                   10020:         }
                   10021:     }
1.81      www      10022:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10023:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10024: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10025:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10026:                                      ' desiredhome not specified'). 
1.620     albertel 10027:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10028:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10029:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10030:     my $newuser;
                   10031:     if ($uhome eq 'no_host') {
                   10032:         $newuser = 1;
                   10033:     }
1.80      www      10034: # ----------------------------------------------------------------- Create User
1.406     albertel 10035:     if (($uhome eq 'no_host') && 
                   10036: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10037:         my $unhome='';
1.844     albertel 10038:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10039:             $unhome = $desiredhome;
1.620     albertel 10040: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10041: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10042:         } else { # load balancing routine for determining $unhome
1.81      www      10043:             my $loadm=10000000;
1.841     albertel 10044: 	    my %servers = &get_servers($udom,'library');
                   10045: 	    foreach my $tryserver (keys(%servers)) {
                   10046: 		my $answer=reply('load',$tryserver);
                   10047: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10048: 		    $loadm=$answer;
                   10049: 		    $unhome=$tryserver;
                   10050: 		}
1.80      www      10051: 	    }
                   10052:         }
                   10053:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10054: 	    return 'error: unable to find a home server for '.$uname.
                   10055:                    ' in domain '.$udom;
1.80      www      10056:         }
                   10057:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10058:                          &escape($upass),$unhome);
                   10059: 	unless ($reply eq 'ok') {
                   10060:             return 'error: '.$reply;
                   10061:         }   
1.230     stredwic 10062:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10063:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10064: 	    return 'error: unable verify users home machine.';
1.80      www      10065:         }
1.209     matthew  10066:     }   # End of creation of new user
1.80      www      10067: # ---------------------------------------------------------------------- Add ID
                   10068:     if ($uid) {
                   10069:        $uid=~tr/A-Z/a-z/;
                   10070:        my %uidhash=&idrget($udom,$uname);
1.196     www      10071:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10072:          && (!$forceid)) {
1.80      www      10073: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10074: 	      return 'error: user id "'.$uid.'" does not match '.
                   10075:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10076:           }
                   10077:        } else {
                   10078: 	  &idput($udom,($uname => $uid));
                   10079:        }
                   10080:     }
                   10081: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10082:     my @tmp=&get('environment',
1.899     raeburn  10083: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10084:                     'permanentemail','inststatus'],
1.134     albertel 10085: 		   $udom,$uname);
1.1075    raeburn  10086:     my (%names,%oldnames);
1.313     matthew  10087:     if ($tmp[0] =~ m/^error:.*/) { 
                   10088:         %names=(); 
                   10089:     } else {
                   10090:         %names = @tmp;
1.1075    raeburn  10091:         %oldnames = %names;
1.313     matthew  10092:     }
1.388     www      10093: #
1.1058    raeburn  10094: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10095: # of users did not contain them), do not overwrite existing values
                   10096: # unless field is in $candelete array ref.  
                   10097: #
                   10098: 
                   10099:     my @fields = ('firstname','middlename','lastname','generation',
                   10100:                   'permanentemail','id');
                   10101:     my %newvalues;
                   10102:     if (ref($candelete) eq 'ARRAY') {
                   10103:         foreach my $field (@fields) {
                   10104:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10105:                 if ($field eq 'firstname') {
                   10106:                     $names{$field} = $first;
                   10107:                 } elsif ($field eq 'middlename') {
                   10108:                     $names{$field} = $middle;
                   10109:                 } elsif ($field eq 'lastname') {
                   10110:                     $names{$field} = $last;
                   10111:                 } elsif ($field eq 'generation') { 
                   10112:                     $names{$field} = $gene;
                   10113:                 } elsif ($field eq 'permanentemail') {
                   10114:                     $names{$field} = $email;
                   10115:                 } elsif ($field eq 'id') {
                   10116:                     $names{$field}  = $uid;
                   10117:                 }
                   10118:             }
                   10119:         }
                   10120:     }
1.388     www      10121:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10122:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10123:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10124:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10125:     if ($email) {
                   10126:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10127:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10128:     }
1.899     raeburn  10129:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10130:     if (defined($inststatus)) {
                   10131:         $names{'inststatus'} = '';
                   10132:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10133:         if (ref($usertypes) eq 'HASH') {
                   10134:             my @okstatuses; 
                   10135:             foreach my $item (split(/:/,$inststatus)) {
                   10136:                 if (defined($usertypes->{$item})) {
                   10137:                     push(@okstatuses,$item);  
                   10138:                 }
                   10139:             }
                   10140:             if (@okstatuses) {
                   10141:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10142:             }
                   10143:         }
                   10144:     }
1.1075    raeburn  10145:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10146:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10147:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10148:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10149:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10150:     } else {
                   10151:         $logmsg .= ' during self creation';
                   10152:     }
1.1075    raeburn  10153:     my $changed;
                   10154:     if ($newuser) {
                   10155:         $changed = 1;
                   10156:     } else {
                   10157:         foreach my $field (@fields) {
                   10158:             if ($names{$field} ne $oldnames{$field}) {
                   10159:                 $changed = 1;
                   10160:                 last;
                   10161:             }
                   10162:         }
                   10163:     }
                   10164:     unless ($changed) {
                   10165:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10166:         &logthis($logmsg);
                   10167:         return 'ok';
                   10168:     }
                   10169:     my $reply = &put('environment', \%names, $udom,$uname);
                   10170:     if ($reply ne 'ok') { 
                   10171:         return 'error: '.$reply;
                   10172:     }
1.1087    raeburn  10173:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10174:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10175:     }
1.1075    raeburn  10176:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10177:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10178:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10179:     &logthis($logmsg);
1.134     albertel 10180:     return 'ok';
1.80      www      10181: }
                   10182: 
1.81      www      10183: # -------------------------------------------------------------- Modify student
1.80      www      10184: 
1.81      www      10185: sub modifystudent {
                   10186:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10187:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10188:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10189:     if (!$cid) {
1.620     albertel 10190: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10191: 	    return 'not_in_class';
                   10192: 	}
1.80      www      10193:     }
                   10194: # --------------------------------------------------------------- Make the user
1.81      www      10195:     my $reply=&modifyuser
1.209     matthew  10196: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10197:          $desiredhome,$email,$inststatus);
1.80      www      10198:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10199:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10200:     # student's environment
1.297     matthew  10201:     $uid = undef if (!$forceid);
1.455     albertel 10202:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10203: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10204:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10205:     return $reply;
                   10206: }
                   10207: 
                   10208: sub modify_student_enrollment {
1.1172.2.23  raeburn  10209:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10210:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10211:     my ($cdom,$cnum,$chome);
                   10212:     if (!$cid) {
1.620     albertel 10213: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10214: 	    return 'not_in_class';
                   10215: 	}
1.620     albertel 10216: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10217: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10218:     } else {
                   10219: 	($cdom,$cnum)=split(/_/,$cid);
                   10220:     }
1.620     albertel 10221:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10222:     if (!$chome) {
1.457     raeburn  10223: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10224:     }
1.455     albertel 10225:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10226:     # Make sure the user exists
1.81      www      10227:     my $uhome=&homeserver($uname,$udom);
                   10228:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10229: 	return 'error: no such user';
                   10230:     }
1.297     matthew  10231:     # Get student data if we were not given enough information
                   10232:     if (!defined($first)  || $first  eq '' || 
                   10233:         !defined($last)   || $last   eq '' || 
                   10234:         !defined($uid)    || $uid    eq '' || 
                   10235:         !defined($middle) || $middle eq '' || 
                   10236:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10237:         # They did not supply us with enough data to enroll the student, so
                   10238:         # we need to pick up more information.
1.297     matthew  10239:         my %tmp = &get('environment',
1.294     matthew  10240:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10241:                        ,$udom,$uname);
                   10242: 
1.800     albertel 10243:         #foreach my $key (keys(%tmp)) {
                   10244:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10245:         #}
1.294     matthew  10246:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10247:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10248:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10249:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10250:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10251:     }
1.556     albertel 10252:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10253:     my $user = "$uname:$udom";
                   10254:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10255:     my $reply=cput('classlist',
1.1148    raeburn  10256: 		   {$user => 
1.1172.2.76  raeburn  10257: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10258: 		   $cdom,$cnum);
1.1148    raeburn  10259:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10260:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10261:     } else { 
1.81      www      10262: 	return 'error: '.$reply;
                   10263:     }
1.297     matthew  10264:     # Add student role to user
1.83      www      10265:     my $uurl='/'.$cid;
1.81      www      10266:     $uurl=~s/\_/\//g;
                   10267:     if ($usec) {
                   10268: 	$uurl.='/'.$usec;
                   10269:     }
1.1148    raeburn  10270:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10271:                              $selfenroll,$context);
                   10272:     if ($result ne 'ok') {
                   10273:         if ($old_entry{$user} ne '') {
                   10274:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10275:         } else {
                   10276:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10277:         }
                   10278:     }
                   10279:     return $result; 
1.21      www      10280: }
                   10281: 
1.556     albertel 10282: sub format_name {
                   10283:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10284:     my $name;
                   10285:     if ($first ne 'lastname') {
                   10286: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10287:     } else {
                   10288: 	if ($lastname=~/\S/) {
                   10289: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10290: 	    $name=~s/\s+,/,/;
                   10291: 	} else {
                   10292: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10293: 	}
                   10294:     }
                   10295:     $name=~s/^\s+//;
                   10296:     $name=~s/\s+$//;
                   10297:     $name=~s/\s+/ /g;
                   10298:     return $name;
                   10299: }
                   10300: 
1.84      www      10301: # ------------------------------------------------- Write to course preferences
                   10302: 
                   10303: sub writecoursepref {
                   10304:     my ($courseid,%prefs)=@_;
                   10305:     $courseid=~s/^\///;
                   10306:     $courseid=~s/\_/\//g;
                   10307:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10308:     my $chome=homeserver($cnum,$cdomain);
                   10309:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10310: 	return 'error: no such course';
                   10311:     }
                   10312:     my $cstring='';
1.800     albertel 10313:     foreach my $pref (keys(%prefs)) {
                   10314: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10315:     }
1.84      www      10316:     $cstring=~s/\&$//;
                   10317:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10318: }
                   10319: 
                   10320: # ---------------------------------------------------------- Make/modify course
                   10321: 
                   10322: sub createcourse {
1.741     raeburn  10323:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118.  .6(raebu 10324:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10325:     $url=&declutter($url);
                   10326:     my $cid='';
1.1028    raeburn  10327:     if ($context eq 'requestcourses') {
                   10328:         my $can_create = 0;
                   10329:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10330:         if ($udom eq $ownerdom) {
1.1172.2.118.  .6(raebu 10331:20):             my $reload;
                   10332:20):             if (($callercontext eq 'auto') &&
                   10333:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10334:20):                 $reload = 'reload';
                   10335:20):             }
                   10336:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10337:                                   $context)) {
                   10338:                 $can_create = 1;
                   10339:             }
                   10340:         } else {
                   10341:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10342:                                            $category);
                   10343:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10344:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10345:                 if (@curr > 0) {
                   10346:                     my @options = qw(approval validate autolimit);
                   10347:                     my $optregex = join('|',@options);
                   10348:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10349:                         $can_create = 1;
                   10350:                     }
                   10351:                 }
                   10352:             }
                   10353:         }
                   10354:         if ($can_create) {
                   10355:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10356:                 unless (&allowed('ccc',$udom)) {
                   10357:                     return 'refused'; 
                   10358:                 }
1.1017    raeburn  10359:             }
                   10360:         } else {
                   10361:             return 'refused';
                   10362:         }
1.1028    raeburn  10363:     } elsif (!&allowed('ccc',$udom)) {
                   10364:         return 'refused';
1.84      www      10365:     }
1.1011    raeburn  10366: # --------------------------------------------------------------- Get Unique ID
                   10367:     my $uname;
                   10368:     if ($cnum =~ /^$match_courseid$/) {
                   10369:         my $chome=&homeserver($cnum,$udom,'true');
                   10370:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10371:             $uname = $cnum;
                   10372:         } else {
1.1038    raeburn  10373:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10374:         }
                   10375:     } else {
1.1038    raeburn  10376:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10377:     }
                   10378:     return $uname if ($uname =~ /^error/);
                   10379: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10380:     if (!defined($course_server)) {
                   10381:         if (defined(&domain($udom,'primary'))) {
                   10382:             $course_server = &domain($udom,'primary');
                   10383:         } else {
                   10384:             $course_server = $env{'user.home'}; 
                   10385:         }
                   10386:     }
                   10387:     my %host_servers =
                   10388:         &Apache::lonnet::get_servers($udom,'library');
                   10389:     unless ($host_servers{$course_server}) {
                   10390:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10391:     }
1.84      www      10392: # ------------------------------------------------------------- Make the course
                   10393:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10394:                       $course_server);
1.84      www      10395:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10396:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10397:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10398: 	return 'error: no such course';
                   10399:     }
1.271     www      10400: # ----------------------------------------------------------------- Course made
1.516     raeburn  10401: # log existence
1.1029    raeburn  10402:     my $now = time;
1.918     raeburn  10403:     my $newcourse = {
                   10404:                     $udom.'_'.$uname => {
1.921     raeburn  10405:                                      description => $description,
                   10406:                                      inst_code   => $inst_code,
                   10407:                                      owner       => $course_owner,
                   10408:                                      type        => $crstype,
1.1029    raeburn  10409:                                      creator     => $env{'user.name'}.':'.
                   10410:                                                     $env{'user.domain'},
                   10411:                                      created     => $now,
                   10412:                                      context     => $context,
1.918     raeburn  10413:                                                 },
                   10414:                     };
1.921     raeburn  10415:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10416: # set toplevel url
1.271     www      10417:     my $topurl=$url;
                   10418:     unless ($nonstandard) {
                   10419: # ------------------------------------------ For standard courses, make top url
                   10420:         my $mapurl=&clutter($url);
1.278     www      10421:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10422:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10423: <map>
                   10424: <resource id="1" type="start"></resource>
                   10425: <resource id="2" src="$mapurl"></resource>
                   10426: <resource id="3" type="finish"></resource>
                   10427: <link index="1" from="1" to="2"></link>
                   10428: <link index="2" from="2" to="3"></link>
                   10429: </map>
                   10430: ENDINITMAP
                   10431:         $topurl=&declutter(
1.638     albertel 10432:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10433:                           );
                   10434:     }
                   10435: # ----------------------------------------------------------- Write preferences
1.84      www      10436:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10437:                      ('description'              => $description,
                   10438:                       'url'                      => $topurl,
                   10439:                       'internal.creator'         => $env{'user.name'}.':'.
                   10440:                                                     $env{'user.domain'},
                   10441:                       'internal.created'         => $now,
                   10442:                       'internal.creationcontext' => $context)
                   10443:                     );
1.84      www      10444:     return '/'.$udom.'/'.$uname;
                   10445: }
                   10446: 
1.1011    raeburn  10447: # ------------------------------------------------------------------- Create ID
                   10448: sub generate_coursenum {
1.1038    raeburn  10449:     my ($udom,$crstype) = @_;
1.1011    raeburn  10450:     my $domdesc = &domain($udom);
                   10451:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10452:     my $first;
                   10453:     if ($crstype eq 'Community') {
                   10454:         $first = '0';
                   10455:     } else {
                   10456:         $first = int(1+rand(9)); 
                   10457:     } 
                   10458:     my $uname=$first.
1.1011    raeburn  10459:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10460:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10461:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10462: # ----------------------------------------------- Make sure that does not exist
                   10463:     my $uhome=&homeserver($uname,$udom,'true');
                   10464:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10465:         if ($crstype eq 'Community') {
                   10466:             $first = '0';
                   10467:         } else {
                   10468:             $first = int(1+rand(9));
                   10469:         }
                   10470:         $uname=$first.
1.1011    raeburn  10471:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10472:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10473:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10474:         $uhome=&homeserver($uname,$udom,'true');
                   10475:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10476:             return 'error: unable to generate unique course-ID';
                   10477:         }
                   10478:     }
                   10479:     return $uname;
                   10480: }
                   10481: 
1.813     albertel 10482: sub is_course {
1.1167    droeschl 10483:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10484:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10485:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10486:     my $uhome=&homeserver($cnum,$cdom);
                   10487:     my $iscourse;
                   10488:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10489:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10490:     } else {
                   10491:         my $hashid = $cdom.':'.$cnum;
                   10492:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10493:         unless (defined($cached)) {
                   10494:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10495:                                         $cnum,undef,undef,'.');
                   10496:             $iscourse = 0;
                   10497:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10498:                 $iscourse = 1;
                   10499:             }
                   10500:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10501:         }
                   10502:     }
                   10503:     return unless($iscourse);
1.1167    droeschl 10504:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10505: }
                   10506: 
1.1015    raeburn  10507: sub store_userdata {
                   10508:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10509:     my $result;
1.1016    raeburn  10510:     if ($datakey ne '') {
1.1013    raeburn  10511:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10512:             if ($udom eq '' || $uname eq '') {
                   10513:                 $udom = $env{'user.domain'};
                   10514:                 $uname = $env{'user.name'};
                   10515:             }
                   10516:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10517:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10518:                 $result = 'error: no_host';
                   10519:             } else {
                   10520:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10521:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10522: 
                   10523:                 my $namevalue='';
                   10524:                 foreach my $key (keys(%{$storehash})) {
                   10525:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10526:                 }
                   10527:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10528:                 unless ($namespace eq 'courserequests') {
                   10529:                     $datakey = &escape($datakey);
                   10530:                 }
1.1105    raeburn  10531:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10532:                                   $namevalue,$uhome);
1.1013    raeburn  10533:             }
                   10534:         } else {
                   10535:             $result = 'error: data to store was not a hash reference'; 
                   10536:         }
                   10537:     } else {
                   10538:         $result= 'error: invalid requestkey'; 
                   10539:     }
                   10540:     return $result;
                   10541: }
                   10542: 
1.21      www      10543: # ---------------------------------------------------------- Assign Custom Role
                   10544: 
                   10545: sub assigncustomrole {
1.957     raeburn  10546:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10547:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10548:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10549: }
                   10550: 
                   10551: # ----------------------------------------------------------------- Revoke Role
                   10552: 
                   10553: sub revokerole {
1.957     raeburn  10554:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10555:     my $now=time;
1.965     raeburn  10556:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10557: }
                   10558: 
                   10559: # ---------------------------------------------------------- Revoke Custom Role
                   10560: 
                   10561: sub revokecustomrole {
1.957     raeburn  10562:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10563:     my $now=time;
1.357     www      10564:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10565:            $deleteflag,$selfenroll,$context);
1.17      www      10566: }
                   10567: 
1.533     banghart 10568: # ------------------------------------------------------------ Disk usage
1.535     albertel 10569: sub diskusage {
1.955     raeburn  10570:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10571:     $directorypath =~ s/\/$//;
                   10572:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10573:                        .&escape($getpropath).':'.&escape($uname).':'
                   10574:                        .&escape($udom),homeserver($uname,$udom));
                   10575:     if ($listing eq 'unknown_cmd') {
                   10576:         if ($getpropath) {
                   10577:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10578:         }
                   10579:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10580:     }
1.514     albertel 10581:     return $listing;
1.512     banghart 10582: }
                   10583: 
1.566     banghart 10584: sub is_locked {
1.1096    raeburn  10585:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10586:     my @check;
                   10587:     my $is_locked;
1.1093    raeburn  10588:     push (@check,$file_name);
1.613     albertel 10589:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10590: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10591:     my ($tmp)=keys(%locked);
                   10592:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10593:     
1.566     banghart 10594:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10595:         $is_locked = 'false';
                   10596:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10597:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10598:                $is_locked = 'true';
1.1096    raeburn  10599:                if (ref($which) eq 'ARRAY') {
                   10600:                    push(@{$which},$entry);
                   10601:                } else {
                   10602:                    last;
                   10603:                }
1.745     raeburn  10604:            }
                   10605:        }
1.566     banghart 10606:     } else {
                   10607:         $is_locked = 'false';
                   10608:     }
1.1093    raeburn  10609:     return $is_locked;
1.566     banghart 10610: }
                   10611: 
1.759     albertel 10612: sub declutter_portfile {
                   10613:     my ($file) = @_;
1.833     albertel 10614:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10615:     return $file;
                   10616: }
                   10617: 
1.559     banghart 10618: # ------------------------------------------------------------- Mark as Read Only
                   10619: 
                   10620: sub mark_as_readonly {
                   10621:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10622:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10623:     my ($tmp)=keys(%current_permissions);
                   10624:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10625:     foreach my $file (@{$files}) {
1.759     albertel 10626: 	$file = &declutter_portfile($file);
1.561     banghart 10627:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10628:     }
1.613     albertel 10629:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10630:     return;
                   10631: }
                   10632: 
1.572     banghart 10633: # ------------------------------------------------------------Save Selected Files
                   10634: 
                   10635: sub save_selected_files {
                   10636:     my ($user, $path, @files) = @_;
                   10637:     my $filename = $user."savedfiles";
1.573     banghart 10638:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10639:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10640:     foreach my $file (@files) {
1.620     albertel 10641:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10642:     }
                   10643:     foreach my $file (@other_files) {
1.574     banghart 10644:         print (OUT $file."\n");
1.572     banghart 10645:     }
1.574     banghart 10646:     close (OUT);
1.572     banghart 10647:     return 'ok';
                   10648: }
                   10649: 
1.574     banghart 10650: sub clear_selected_files {
                   10651:     my ($user) = @_;
                   10652:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10653:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10654:     print (OUT undef);
                   10655:     close (OUT);
                   10656:     return ("ok");    
                   10657: }
                   10658: 
1.572     banghart 10659: sub files_in_path {
                   10660:     my ($user, $path) = @_;
                   10661:     my $filename = $user."savedfiles";
                   10662:     my %return_files;
1.1172.2.96  raeburn  10663:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10664:     while (my $line_in = <IN>) {
1.574     banghart 10665:         chomp ($line_in);
                   10666:         my @paths_and_file = split (m!/!, $line_in);
                   10667:         my $file_part = pop (@paths_and_file);
                   10668:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10669:         $path_part.='/';
                   10670:         my $path_and_file = $path_part.$file_part;
                   10671:         if ($path_part eq $path) {
                   10672:             $return_files{$file_part}= 'selected';
                   10673:         }
                   10674:     }
1.574     banghart 10675:     close (IN);
                   10676:     return (\%return_files);
1.572     banghart 10677: }
                   10678: 
                   10679: # called in portfolio select mode, to show files selected NOT in current directory
                   10680: sub files_not_in_path {
                   10681:     my ($user, $path) = @_;
                   10682:     my $filename = $user."savedfiles";
                   10683:     my @return_files;
                   10684:     my $path_part;
1.1172.2.96  raeburn  10685:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10686:     while (my $line = <IN>) {
1.572     banghart 10687:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10688:         my @paths_and_file = split(m|/|, $line);
                   10689:         my $file_part = pop(@paths_and_file);
                   10690:         chomp($file_part);
                   10691:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10692:         $path_part .= '/';
                   10693:         my $path_and_file = $path_part.$file_part;
                   10694:         if ($path_part ne $path) {
1.800     albertel 10695:             push(@return_files, ($path_and_file));
1.572     banghart 10696:         }
                   10697:     }
1.800     albertel 10698:     close(OUT);
1.574     banghart 10699:     return (@return_files);
1.572     banghart 10700: }
                   10701: 
1.745     raeburn  10702: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10703: 
1.745     raeburn  10704: sub get_portfile_permissions {
                   10705:     my ($domain,$user) = @_;
1.613     albertel 10706:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10707:     my ($tmp)=keys(%current_permissions);
                   10708:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10709:     return \%current_permissions;
                   10710: }
                   10711: 
                   10712: #---------------------------------------------Get portfolio file access controls
                   10713: 
1.749     raeburn  10714: sub get_access_controls {
1.745     raeburn  10715:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10716:     my %access;
                   10717:     my $real_file = $file;
                   10718:     $file =~ s/\.meta$//;
1.745     raeburn  10719:     if (defined($file)) {
1.749     raeburn  10720:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10721:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10722:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10723:             }
                   10724:         }
1.745     raeburn  10725:     } else {
1.749     raeburn  10726:         foreach my $key (keys(%{$current_permissions})) {
                   10727:             if ($key =~ /\0accesscontrol$/) {
                   10728:                 if (defined($group)) {
                   10729:                     if ($key !~ m-^\Q$group\E/-) {
                   10730:                         next;
                   10731:                     }
                   10732:                 }
                   10733:                 my ($fullpath) = split(/\0/,$key);
                   10734:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10735:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10736:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10737:                     }
                   10738:                 }
                   10739:             }
                   10740:         }
                   10741:     }
                   10742:     return %access;
                   10743: }
                   10744: 
                   10745: sub modify_access_controls {
                   10746:     my ($file_name,$changes,$domain,$user)=@_;
                   10747:     my ($outcome,$deloutcome);
                   10748:     my %store_permissions;
                   10749:     my %new_values;
                   10750:     my %new_control;
                   10751:     my %translation;
                   10752:     my @deletions = ();
                   10753:     my $now = time;
                   10754:     if (exists($$changes{'activate'})) {
                   10755:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10756:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10757:             my $numnew = scalar(@newitems);
                   10758:             for (my $i=0; $i<$numnew; $i++) {
                   10759:                 my $newkey = $newitems[$i];
                   10760:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10761:                 if ($newkey =~ /^\d+:/) { 
                   10762:                     $newkey =~ s/^(\d+)/$newid/;
                   10763:                     $translation{$1} = $newid;
                   10764:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10765:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10766:                     $translation{$1} = $newid;
                   10767:                 }
1.749     raeburn  10768:                 $new_values{$file_name."\0".$newkey} = 
                   10769:                                           $$changes{'activate'}{$newitems[$i]};
                   10770:                 $new_control{$newkey} = $now;
                   10771:             }
                   10772:         }
                   10773:     }
                   10774:     my %todelete;
                   10775:     my %changed_items;
                   10776:     foreach my $action ('delete','update') {
                   10777:         if (exists($$changes{$action})) {
                   10778:             if (ref($$changes{$action}) eq 'HASH') {
                   10779:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10780:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10781:                     if ($action eq 'delete') { 
                   10782:                         $todelete{$itemnum} = 1;
                   10783:                     } else {
                   10784:                         $changed_items{$itemnum} = $key;
                   10785:                     }
                   10786:                 }
1.745     raeburn  10787:             }
                   10788:         }
1.749     raeburn  10789:     }
                   10790:     # get lock on access controls for file.
                   10791:     my $lockhash = {
                   10792:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10793:                                                        ':'.$env{'user.domain'},
                   10794:                    }; 
                   10795:     my $tries = 0;
                   10796:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10797:    
1.1172.2.79  raeburn  10798:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10799:         $tries ++;
1.1172.2.79  raeburn  10800:         sleep(0.1);
1.749     raeburn  10801:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10802:     }
                   10803:     if ($gotlock eq 'ok') {
                   10804:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10805:         my ($tmp)=keys(%curr_permissions);
                   10806:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10807:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10808:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10809:             if (ref($curr_controls) eq 'HASH') {
                   10810:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10811:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10812:                     if (defined($todelete{$itemnum})) {
                   10813:                         push(@deletions,$file_name."\0".$control_item);
                   10814:                     } else {
                   10815:                         if (defined($changed_items{$itemnum})) {
                   10816:                             $new_control{$changed_items{$itemnum}} = $now;
                   10817:                             push(@deletions,$file_name."\0".$control_item);
                   10818:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10819:                         } else {
                   10820:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10821:                         }
                   10822:                     }
1.745     raeburn  10823:                 }
                   10824:             }
                   10825:         }
1.970     raeburn  10826:         my ($group);
                   10827:         if (&is_course($domain,$user)) {
                   10828:             ($group,my $file) = split(/\//,$file_name,2);
                   10829:         }
1.749     raeburn  10830:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10831:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10832:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10833:         #  remove lock
                   10834:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10835:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10836:         my $sqlresult =
1.970     raeburn  10837:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10838:                                     $group);
1.749     raeburn  10839:     } else {
                   10840:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10841:     }
1.749     raeburn  10842:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10843: }
                   10844: 
1.827     raeburn  10845: sub make_public_indefinitely {
                   10846:     my ($requrl) = @_;
                   10847:     my $now = time;
                   10848:     my $action = 'activate';
                   10849:     my $aclnum = 0;
                   10850:     if (&is_portfolio_url($requrl)) {
                   10851:         my (undef,$udom,$unum,$file_name,$group) =
                   10852:             &parse_portfolio_url($requrl);
                   10853:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10854:         my %access_controls = &get_access_controls($current_perms,
                   10855:                                                    $group,$file_name);
                   10856:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10857:             my ($num,$scope,$end,$start) = 
                   10858:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10859:             if ($scope eq 'public') {
                   10860:                 if ($start <= $now && $end == 0) {
                   10861:                     $action = 'none';
                   10862:                 } else {
                   10863:                     $action = 'update';
                   10864:                     $aclnum = $num;
                   10865:                 }
                   10866:                 last;
                   10867:             }
                   10868:         }
                   10869:         if ($action eq 'none') {
                   10870:              return 'ok';
                   10871:         } else {
                   10872:             my %changes;
                   10873:             my $newend = 0;
                   10874:             my $newstart = $now;
                   10875:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10876:             $changes{$action}{$newkey} = {
                   10877:                 type => 'public',
                   10878:                 time => {
                   10879:                     start => $newstart,
                   10880:                     end   => $newend,
                   10881:                 },
                   10882:             };
                   10883:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10884:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10885:             return $outcome;
                   10886:         }
                   10887:     } else {
                   10888:         return 'invalid';
                   10889:     }
                   10890: }
                   10891: 
1.745     raeburn  10892: #------------------------------------------------------Get Marked as Read Only
                   10893: 
                   10894: sub get_marked_as_readonly {
                   10895:     my ($domain,$user,$what,$group) = @_;
                   10896:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10897:     my @readonly_files;
1.629     banghart 10898:     my $cmp1=$what;
                   10899:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10900:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10901:         if (defined($group)) {
                   10902:             if ($file_name !~ m-^\Q$group\E/-) {
                   10903:                 next;
                   10904:             }
                   10905:         }
1.561     banghart 10906:         if (ref($value) eq "ARRAY"){
                   10907:             foreach my $stored_what (@{$value}) {
1.629     banghart 10908:                 my $cmp2=$stored_what;
1.759     albertel 10909:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10910:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10911:                 }
1.629     banghart 10912:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10913:                     push(@readonly_files, $file_name);
1.745     raeburn  10914:                     last;
1.563     banghart 10915:                 } elsif (!defined($what)) {
                   10916:                     push(@readonly_files, $file_name);
1.745     raeburn  10917:                     last;
1.561     banghart 10918:                 }
                   10919:             }
1.745     raeburn  10920:         }
1.561     banghart 10921:     }
                   10922:     return @readonly_files;
                   10923: }
1.577     banghart 10924: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10925: 
1.577     banghart 10926: sub get_marked_as_readonly_hash {
1.745     raeburn  10927:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10928:     my %readonly_files;
1.745     raeburn  10929:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10930:         if (defined($group)) {
                   10931:             if ($file_name !~ m-^\Q$group\E/-) {
                   10932:                 next;
                   10933:             }
                   10934:         }
1.577     banghart 10935:         if (ref($value) eq "ARRAY"){
                   10936:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10937:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10938:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10939:                         if ($lock_descriptor eq 'graded') {
                   10940:                             $readonly_files{$file_name} = 'graded';
                   10941:                         } elsif ($lock_descriptor eq 'handback') {
                   10942:                             $readonly_files{$file_name} = 'handback';
                   10943:                         } else {
                   10944:                             if (!exists($readonly_files{$file_name})) {
                   10945:                                 $readonly_files{$file_name} = 'locked';
                   10946:                             }
                   10947:                         }
1.745     raeburn  10948:                     }
1.750     banghart 10949:                 } 
1.577     banghart 10950:             }
                   10951:         } 
                   10952:     }
                   10953:     return %readonly_files;
                   10954: }
1.559     banghart 10955: # ------------------------------------------------------------ Unmark as Read Only
                   10956: 
                   10957: sub unmark_as_readonly {
1.629     banghart 10958:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10959:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10960:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10961:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10962:     my $symb_crs = $what;
                   10963:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10964:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10965:     my ($tmp)=keys(%current_permissions);
                   10966:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10967:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10968:     foreach my $file (@readonly_files) {
1.759     albertel 10969: 	my $clean_file = &declutter_portfile($file);
                   10970: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10971: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10972:         my @new_locks;
                   10973:         my @del_keys;
                   10974:         if (ref($current_locks) eq "ARRAY"){
                   10975:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10976:                 my $compare=$locker;
1.749     raeburn  10977:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10978:                     $compare=join('',@{$locker});
1.746     raeburn  10979:                     if ($compare ne $symb_crs) {
                   10980:                         push(@new_locks, $locker);
                   10981:                     }
1.563     banghart 10982:                 }
                   10983:             }
1.650     albertel 10984:             if (scalar(@new_locks) > 0) {
1.563     banghart 10985:                 $current_permissions{$file} = \@new_locks;
                   10986:             } else {
                   10987:                 push(@del_keys, $file);
1.613     albertel 10988:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10989:                 delete($current_permissions{$file});
1.563     banghart 10990:             }
                   10991:         }
1.561     banghart 10992:     }
1.613     albertel 10993:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10994:     return;
                   10995: }
1.512     banghart 10996: 
1.17      www      10997: # ------------------------------------------------------------ Directory lister
                   10998: 
                   10999: sub dirlist {
1.955     raeburn  11000:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11001:     $uri=~s/^\///;
                   11002:     $uri=~s/\/$//;
1.253     stredwic 11003:     my ($udom, $uname);
1.955     raeburn  11004:     if ($getuserdir) {
1.253     stredwic 11005:         $udom = $userdomain;
                   11006:         $uname = $username;
1.955     raeburn  11007:     } else {
                   11008:         (undef,$udom,$uname)=split(/\//,$uri);
                   11009:         if(defined($userdomain)) {
                   11010:             $udom = $userdomain;
                   11011:         }
                   11012:         if(defined($username)) {
                   11013:             $uname = $username;
                   11014:         }
1.253     stredwic 11015:     }
1.955     raeburn  11016:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11017: 
1.955     raeburn  11018:     $dirRoot = $perlvar{'lonDocRoot'};
                   11019:     if (defined($getpropath)) {
                   11020:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11021:         $dirRoot =~ s/\/$//;
1.955     raeburn  11022:     } elsif (defined($getuserdir)) {
                   11023:         my $subdir=$uname.'__';
                   11024:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11025:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11026:                    ."/$udom/$subdir/$uname";
                   11027:     } elsif (defined($alternateRoot)) {
                   11028:         $dirRoot = $alternateRoot;
1.751     banghart 11029:     }
1.253     stredwic 11030: 
                   11031:     if($udom) {
                   11032:         if($uname) {
1.1135    raeburn  11033:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11034:             if ($uhome eq 'no_host') {
                   11035:                 return ([],'no_host');
                   11036:             }
1.955     raeburn  11037:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11038:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11039:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11040:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11041:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11042:             } else {
                   11043:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11044:             }
1.605     matthew  11045:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11046:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11047:                 @listing_results = split(/:/,$listing);
                   11048:             } else {
                   11049:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11050:             }
1.1135    raeburn  11051:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11052:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11053:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11054:                 return ([],$listing);
                   11055:             } else {
                   11056:                 return (\@listing_results);
1.1135    raeburn  11057:             }
1.955     raeburn  11058:         } elsif(!$alternateRoot) {
1.1136    raeburn  11059:             my (%allusers,%listerror);
1.841     albertel 11060: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11061:  	    foreach my $tryserver (keys(%servers)) {
                   11062:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11063:                                   &escape($udom),$tryserver);
                   11064:                 if ($listing eq 'unknown_cmd') {
                   11065: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11066: 				      $udom, $tryserver);
                   11067:                 } else {
                   11068:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11069:                 }
1.841     albertel 11070: 		if ($listing eq 'unknown_cmd') {
                   11071: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11072: 				      $udom, $tryserver);
                   11073: 		    @listing_results = split(/:/,$listing);
                   11074: 		} else {
                   11075: 		    @listing_results =
                   11076: 			map { &unescape($_); } split(/:/,$listing);
                   11077: 		}
1.1136    raeburn  11078:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11079:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11080:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11081:                     $listerror{$tryserver} = $listing;
                   11082:                 } else {
1.841     albertel 11083: 		    foreach my $line (@listing_results) {
                   11084: 			my ($entry) = split(/&/,$line,2);
                   11085: 			$allusers{$entry} = 1;
                   11086: 		    }
                   11087: 		}
1.253     stredwic 11088:             }
1.1136    raeburn  11089:             my @alluserslist=();
1.800     albertel 11090:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11091:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11092:             }
1.1172.2.80  raeburn  11093:             if (!%listerror) {
                   11094:                 # no errors
                   11095:                 return (\@alluserslist);
                   11096:             } elsif (scalar(keys(%servers)) == 1) {
                   11097:                 # one library server, one error
                   11098:                 my ($key) = keys(%listerror);
                   11099:                 return (\@alluserslist, $listerror{$key});
                   11100:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11101:                 # con_lost indicates that we might miss data from at least one
                   11102:                 # library server
                   11103:                 return (\@alluserslist, 'con_lost');
                   11104:             } else {
                   11105:                 # multiple library servers and no con_lost -> data should be
                   11106:                 # complete.
                   11107:                 return (\@alluserslist);
                   11108:             }
                   11109: 
1.253     stredwic 11110:         } else {
1.1136    raeburn  11111:             return ([],'missing username');
1.253     stredwic 11112:         }
1.955     raeburn  11113:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11114:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11115:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11116:         return (\@all_domains);
1.955     raeburn  11117:     } else {
1.1136    raeburn  11118:         return ([],'missing domain');
1.275     stredwic 11119:     }
                   11120: }
                   11121: 
                   11122: # --------------------------------------------- GetFileTimestamp
                   11123: # This function utilizes dirlist and returns the date stamp for
                   11124: # when it was last modified.  It will also return an error of -1
                   11125: # if an error occurs
                   11126: 
                   11127: sub GetFileTimestamp {
1.955     raeburn  11128:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11129:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11130:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11131:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11132:                                     undef,$getuserdir);
                   11133:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11134:         return -1;
                   11135:     }
                   11136:     if (ref($fileref) eq 'ARRAY') {
                   11137:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11138:         # @stats contains first the filename, then the stat output
                   11139:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11140:     } else {
                   11141:         return -1;
1.253     stredwic 11142:     }
1.26      www      11143: }
                   11144: 
1.712     albertel 11145: sub stat_file {
                   11146:     my ($uri) = @_;
1.787     albertel 11147:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11148: 
1.955     raeburn  11149:     my ($udom,$uname,$file);
1.712     albertel 11150:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11151: 	($udom,$uname,$file) =
1.811     albertel 11152: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11153: 	$file = 'userfiles/'.$file;
                   11154:     }
                   11155:     if ($uri =~ m-^/res/-) {
                   11156: 	($udom,$uname) = 
1.807     albertel 11157: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11158: 	$file = $uri;
                   11159:     }
                   11160: 
                   11161:     if (!$udom || !$uname || !$file) {
                   11162: 	# unable to handle the uri
                   11163: 	return ();
                   11164:     }
1.956     raeburn  11165:     my $getpropath;
                   11166:     if ($file =~ /^userfiles\//) {
                   11167:         $getpropath = 1;
                   11168:     }
1.1136    raeburn  11169:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11170:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11171:         return ();
                   11172:     } else {
                   11173:         if (ref($listref) eq 'ARRAY') {
                   11174:             my @stats = split('&',$listref->[0]);
                   11175: 	    shift(@stats); #filename is first
                   11176: 	    return @stats;
                   11177:         }
1.712     albertel 11178:     }
                   11179:     return ();
                   11180: }
                   11181: 
1.26      www      11182: # -------------------------------------------------------- Value of a Condition
                   11183: 
1.713     albertel 11184: # gets the value of a specific preevaluated condition
                   11185: #    stored in the string  $env{user.state.<cid>}
                   11186: # or looks up a condition reference in the bighash and if if hasn't
                   11187: # already been evaluated recurses into docondval to get the value of
                   11188: # the condition, then memoizing it to 
                   11189: #   $env{user.state.<cid>.<condition>}
1.40      www      11190: sub directcondval {
                   11191:     my $number=shift;
1.620     albertel 11192:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11193: 	&Apache::lonuserstate::evalstate();
                   11194:     }
1.713     albertel 11195:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11196: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11197:     } elsif ($number =~ /^_/) {
                   11198: 	my $sub_condition;
                   11199: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11200: 		&GDBM_READER(),0640)) {
                   11201: 	    $sub_condition=$bighash{'conditions'.$number};
                   11202: 	    untie(%bighash);
                   11203: 	}
                   11204: 	my $value = &docondval($sub_condition);
1.949     raeburn  11205: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11206: 	return $value;
                   11207:     }
1.620     albertel 11208:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11209:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11210:     } else {
                   11211:        return 2;
                   11212:     }
                   11213: }
                   11214: 
1.713     albertel 11215: # get the collection of conditions for this resource
1.26      www      11216: sub condval {
                   11217:     my $condidx=shift;
1.54      www      11218:     my $allpathcond='';
1.713     albertel 11219:     foreach my $cond (split(/\|/,$condidx)) {
                   11220: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11221: 	    $allpathcond.=
                   11222: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11223: 	}
1.191     harris41 11224:     }
1.54      www      11225:     $allpathcond=~s/\|$//;
1.713     albertel 11226:     return &docondval($allpathcond);
                   11227: }
                   11228: 
                   11229: #evaluates an expression of conditions
                   11230: sub docondval {
                   11231:     my ($allpathcond) = @_;
                   11232:     my $result=0;
                   11233:     if ($env{'request.course.id'}
                   11234: 	&& defined($allpathcond)) {
                   11235: 	my $operand='|';
                   11236: 	my @stack;
                   11237: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11238: 	    if ($chunk eq '(') {
                   11239: 		push @stack,($operand,$result);
                   11240: 	    } elsif ($chunk eq ')') {
                   11241: 		my $before=pop @stack;
                   11242: 		if (pop @stack eq '&') {
                   11243: 		    $result=$result>$before?$before:$result;
                   11244: 		} else {
                   11245: 		    $result=$result>$before?$result:$before;
                   11246: 		}
                   11247: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11248: 		$operand=$chunk;
                   11249: 	    } else {
                   11250: 		my $new=directcondval($chunk);
                   11251: 		if ($operand eq '&') {
                   11252: 		    $result=$result>$new?$new:$result;
                   11253: 		} else {
                   11254: 		    $result=$result>$new?$result:$new;
                   11255: 		}
                   11256: 	    }
                   11257: 	}
1.26      www      11258:     }
                   11259:     return $result;
1.421     albertel 11260: }
                   11261: 
                   11262: # ---------------------------------------------------- Devalidate courseresdata
                   11263: 
                   11264: sub devalidatecourseresdata {
                   11265:     my ($coursenum,$coursedomain)=@_;
                   11266:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11267:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11268: }
                   11269: 
1.763     www      11270: 
1.200     www      11271: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11272: #
                   11273: #  Parameters:
                   11274: #      $coursenum    - Number of the course.
                   11275: #      $coursedomain - Domain at which the course was created.
                   11276: #  Returns:
                   11277: #     A hash of the course parameters along (I think) with timestamps
                   11278: #     and version info.
1.877     foxr     11279: 
1.624     albertel 11280: sub get_courseresdata {
                   11281:     my ($coursenum,$coursedomain)=@_;
1.200     www      11282:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11283:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11284:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11285:     my %dumpreply;
1.417     albertel 11286:     unless (defined($cached)) {
1.624     albertel 11287: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11288: 	$result=\%dumpreply;
1.251     albertel 11289: 	my ($tmp) = keys(%dumpreply);
                   11290: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11291: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11292: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11293: 	    return $tmp;
1.416     albertel 11294: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11295: 	    $result=undef;
1.599     albertel 11296: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11297: 	}
                   11298:     }
1.624     albertel 11299:     return $result;
                   11300: }
                   11301: 
1.633     albertel 11302: sub devalidateuserresdata {
                   11303:     my ($uname,$udom)=@_;
                   11304:     my $hashid="$udom:$uname";
                   11305:     &devalidate_cache_new('userres',$hashid);
                   11306: }
                   11307: 
1.624     albertel 11308: sub get_userresdata {
                   11309:     my ($uname,$udom)=@_;
                   11310:     #most student don\'t have any data set, check if there is some data
                   11311:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11312: 
                   11313:     my $hashid="$udom:$uname";
                   11314:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11315:     if (!defined($cached)) {
                   11316: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11317: 	$result=\%resourcedata;
                   11318: 	&do_cache_new('userres',$hashid,$result,600);
                   11319:     }
                   11320:     my ($tmp)=keys(%$result);
                   11321:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11322: 	return $result;
                   11323:     }
                   11324:     #error 2 occurs when the .db doesn't exist
                   11325:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11326:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11327: 	    &logthis("<font color=\"blue\">WARNING:".
                   11328: 		     " Trying to get resource data for ".
                   11329: 		     $uname." at ".$udom.": ".
                   11330: 		     $tmp."</font>");
                   11331:         }
1.624     albertel 11332:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11333: 	#&EXT_cache_set($udom,$uname);
                   11334: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11335: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11336:     }
                   11337:     return $tmp;
                   11338: }
1.879     foxr     11339: #----------------------------------------------- resdata - return resource data
                   11340: #  Purpose:
                   11341: #    Return resource data for either users or for a course.
                   11342: #  Parameters:
                   11343: #     $name      - Course/user name.
                   11344: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11345:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11346: #     @which     - Array of names of resources desired.
                   11347: #  Returns:
                   11348: #     The value of the first reasource in @which that is found in the
                   11349: #     resource hash.
                   11350: #  Exceptional Conditions:
                   11351: #     If the $type passed in is not valid (not the string 'course' or 
                   11352: #     'user', an undefined  reference is returned.
                   11353: #     If none of the resources are found, an undef is returned
1.624     albertel 11354: sub resdata {
                   11355:     my ($name,$domain,$type,@which)=@_;
                   11356:     my $result;
                   11357:     if ($type eq 'course') {
                   11358: 	$result=&get_courseresdata($name,$domain);
                   11359:     } elsif ($type eq 'user') {
                   11360: 	$result=&get_userresdata($name,$domain);
                   11361:     }
                   11362:     if (!ref($result)) { return $result; }    
1.251     albertel 11363:     foreach my $item (@which) {
1.1172.2.118.  .8(raebu 11364:20): 	if (defined($result->{$item->[0]})) {
                   11365:20): 	    return [$result->{$item->[0]},$item->[1]];
          .1(raebu 11366:20):         }
1.250     albertel 11367:     }
1.291     albertel 11368:     return undef;
1.200     www      11369: }
                   11370: 
1.1172.2.118.  .10(raeb 11371:-20): sub get_domain_lti {
                   11372:-20):     my ($cdom,$context) = @_;
                   11373:-20):     my ($name,%lti);
                   11374:-20):     if ($context eq 'consumer') {
                   11375:-20):         $name = 'ltitools';
                   11376:-20):     } elsif ($context eq 'provider') {
                   11377:-20):         $name = 'lti';
                   11378:-20):     } else {
                   11379:-20):         return %lti;
                   11380:-20):     }
                   11381:-20):     my ($result,$cached)=&is_cached_new($name,$cdom);
          .1(raebu 11382:20):     if (defined($cached)) {
                   11383:20):         if (ref($result) eq 'HASH') {
          .10(raeb 11384:-20):             %lti = %{$result};
          .1(raebu 11385:20):         }
                   11386:20):     } else {
          .10(raeb 11387:-20):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11388:-20):         if (ref($domconfig{$name}) eq 'HASH') {
                   11389:-20):             %lti = %{$domconfig{$name}};
                   11390:-20):             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11391:-20):             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11392:-20):                 foreach my $id (keys(%lti)) {
                   11393:-20):                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
          .1(raebu 11394:20):                         foreach my $item ('key','secret') {
          .10(raeb 11395:-20):                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
          .1(raebu 11396:20):                         }
                   11397:20):                     }
                   11398:20):                 }
                   11399:20):             }
                   11400:20):         }
                   11401:20):         my $cachetime = 24*60*60;
          .10(raeb 11402:-20):         &do_cache_new($name,$cdom,\%lti,$cachetime);
          .1(raebu 11403:20):     }
          .10(raeb 11404:-20):     return %lti;
          .1(raebu 11405:20): }
                   11406:20): 
1.1172.2.31  raeburn  11407: sub get_numsuppfiles {
                   11408:     my ($cnum,$cdom,$ignorecache)=@_;
                   11409:     my $hashid=$cnum.':'.$cdom;
                   11410:     my ($suppcount,$cached);
                   11411:     unless ($ignorecache) {
                   11412:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11413:     }
                   11414:     unless (defined($cached)) {
                   11415:         my $chome=&homeserver($cnum,$cdom);
                   11416:         unless ($chome eq 'no_host') {
                   11417:             ($suppcount,my $errors) = (0,0);
                   11418:             my $suppmap = 'supplemental.sequence';
                   11419:             ($suppcount,$errors) =
                   11420:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11421:         }
                   11422:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11423:     }
                   11424:     return $suppcount;
                   11425: }
                   11426: 
1.379     matthew  11427: #
                   11428: # EXT resource caching routines
                   11429: #
                   11430: 
                   11431: sub clear_EXT_cache_status {
1.383     albertel 11432:     &delenv('cache.EXT.');
1.379     matthew  11433: }
                   11434: 
                   11435: sub EXT_cache_status {
                   11436:     my ($target_domain,$target_user) = @_;
1.383     albertel 11437:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11438:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11439:         # We know already the user has no data
                   11440:         return 1;
                   11441:     } else {
                   11442:         return 0;
                   11443:     }
                   11444: }
                   11445: 
                   11446: sub EXT_cache_set {
                   11447:     my ($target_domain,$target_user) = @_;
1.383     albertel 11448:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11449:     #&appenv({$cachename => time});
1.379     matthew  11450: }
                   11451: 
1.28      www      11452: # --------------------------------------------------------- Value of a Variable
1.58      www      11453: sub EXT {
1.715     albertel 11454: 
1.1172.2.28  raeburn  11455:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11456:     unless ($varname) { return ''; }
1.218     albertel 11457:     #get real user name/domain, courseid and symb
                   11458:     my $courseid;
1.359     albertel 11459:     my $publicuser;
1.427     www      11460:     if ($symbparm) {
                   11461: 	$symbparm=&get_symb_from_alias($symbparm);
                   11462:     }
1.218     albertel 11463:     if (!($uname && $udom)) {
1.790     albertel 11464:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11465:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11466:     } else {
1.620     albertel 11467: 	$courseid=$env{'request.course.id'};
1.218     albertel 11468:     }
1.48      www      11469:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11470:     my $rest;
1.320     albertel 11471:     if (defined($therest[0])) {
1.48      www      11472:        $rest=join('.',@therest);
                   11473:     } else {
                   11474:        $rest='';
                   11475:     }
1.320     albertel 11476: 
1.57      www      11477:     my $qualifierrest=$qualifier;
                   11478:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11479:     my $spacequalifierrest=$space;
                   11480:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11481:     if ($realm eq 'user') {
1.48      www      11482: # --------------------------------------------------------------- user.resource
                   11483: 	if ($space eq 'resource') {
1.651     albertel 11484: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11485: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11486: 		 &&
1.744     albertel 11487: 		 ($symbparm eq &symbread()) ) {	
                   11488: 		# if we are in the middle of processing the resource the
                   11489: 		# get the value we are planning on committing
                   11490:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11491:                     return $Apache::lonhomework::results{$qualifierrest};
                   11492:                 } else {
                   11493:                     return $Apache::lonhomework::history{$qualifierrest};
                   11494:                 }
1.335     albertel 11495: 	    } else {
1.359     albertel 11496: 		my %restored;
1.620     albertel 11497: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11498: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11499: 		} else {
                   11500: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11501: 		}
1.335     albertel 11502: 		return $restored{$qualifierrest};
                   11503: 	    }
1.48      www      11504: # ----------------------------------------------------------------- user.access
                   11505:         } elsif ($space eq 'access') {
1.218     albertel 11506: 	    # FIXME - not supporting calls for a specific user
1.48      www      11507:             return &allowed($qualifier,$rest);
                   11508: # ------------------------------------------ user.preferences, user.environment
                   11509:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11510: 	    if (($uname eq $env{'user.name'}) &&
                   11511: 		($udom eq $env{'user.domain'})) {
                   11512: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11513: 	    } else {
1.359     albertel 11514: 		my %returnhash;
                   11515: 		if (!$publicuser) {
                   11516: 		    %returnhash=&userenvironment($udom,$uname,
                   11517: 						 $qualifierrest);
                   11518: 		}
1.218     albertel 11519: 		return $returnhash{$qualifierrest};
                   11520: 	    }
1.48      www      11521: # ----------------------------------------------------------------- user.course
                   11522:         } elsif ($space eq 'course') {
1.218     albertel 11523: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11524:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11525: # ------------------------------------------------------------------- user.role
                   11526:         } elsif ($space eq 'role') {
1.218     albertel 11527: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11528:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11529:             if ($qualifier eq 'value') {
                   11530: 		return $role;
                   11531:             } elsif ($qualifier eq 'extent') {
                   11532:                 return $where;
                   11533:             }
                   11534: # ----------------------------------------------------------------- user.domain
                   11535:         } elsif ($space eq 'domain') {
1.218     albertel 11536:             return $udom;
1.48      www      11537: # ------------------------------------------------------------------- user.name
                   11538:         } elsif ($space eq 'name') {
1.218     albertel 11539:             return $uname;
1.48      www      11540: # ---------------------------------------------------- Any other user namespace
1.29      www      11541:         } else {
1.359     albertel 11542: 	    my %reply;
                   11543: 	    if (!$publicuser) {
                   11544: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11545: 	    }
                   11546: 	    return $reply{$qualifierrest};
1.48      www      11547:         }
1.236     www      11548:     } elsif ($realm eq 'query') {
                   11549: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11550:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11551: 						[$spacequalifierrest]);
1.620     albertel 11552: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11553:    } elsif ($realm eq 'request') {
1.48      www      11554: # ------------------------------------------------------------- request.browser
                   11555:         if ($space eq 'browser') {
1.1145    bisitz   11556:             return $env{'browser.'.$qualifier};
1.57      www      11557: # ------------------------------------------------------------ request.filename
                   11558:         } else {
1.620     albertel 11559:             return $env{'request.'.$spacequalifierrest};
1.29      www      11560:         }
1.28      www      11561:     } elsif ($realm eq 'course') {
1.48      www      11562: # ---------------------------------------------------------- course.description
1.620     albertel 11563:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11564:     } elsif ($realm eq 'resource') {
1.165     www      11565: 
1.620     albertel 11566: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11567: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11568: 	}
1.693     albertel 11569: 
1.1172.2.30  raeburn  11570:         if ($qualifier eq '') {
                   11571: 	    if ($space eq 'title') {
                   11572: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11573: 	        return &gettitle($symbparm);
                   11574: 	    }
1.693     albertel 11575: 	
1.1172.2.30  raeburn  11576: 	    if ($space eq 'map') {
                   11577: 	        my ($map) = &decode_symb($symbparm);
                   11578: 	        return &symbread($map);
                   11579: 	    }
                   11580:             if ($space eq 'maptitle') {
                   11581:                 my ($map) = &decode_symb($symbparm);
                   11582:                 return &gettitle($map);
                   11583:             }
                   11584: 	    if ($space eq 'filename') {
                   11585: 	        if ($symbparm) {
                   11586: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11587: 	        }
                   11588: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11589: 	    }
1.1172.2.30  raeburn  11590: 
                   11591:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11592:                 if ($space eq 'visibleparts') {
                   11593:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11594:                     my $item;
                   11595:                     if (ref($navmap)) {
                   11596:                         my $res = $navmap->getBySymb($symbparm);
                   11597:                         my $parts = $res->parts();
                   11598:                         if (ref($parts) eq 'ARRAY') {
                   11599:                             $item = join(',',@{$parts});
                   11600:                         }
                   11601:                         undef($navmap);
                   11602:                     }
                   11603:                     return $item;
                   11604:                 }
                   11605:             }
                   11606:         }
1.693     albertel 11607: 
                   11608: 	my ($section, $group, @groups);
1.593     albertel 11609: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11610:         if (($courseid eq '') && ($cid)) {
                   11611:             $courseid = $cid;
                   11612:         }
                   11613: 	if (($symbparm && $courseid) && 
                   11614: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11615: 
1.218     albertel 11616: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11617: 
1.60      www      11618: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11619: 	    my $symbp=$symbparm;
1.735     albertel 11620: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11621: 
                   11622: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11623: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11624: 
1.620     albertel 11625: 	    if (($env{'user.name'} eq $uname) &&
                   11626: 		($env{'user.domain'} eq $udom)) {
                   11627: 		$section=$env{'request.course.sec'};
1.733     raeburn  11628:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11629:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11630: 	    } else {
1.539     albertel 11631: 		if (! defined($usection)) {
1.551     albertel 11632: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11633: 		} else {
                   11634: 		    $section = $usection;
                   11635: 		}
1.733     raeburn  11636:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11637: 	    }
                   11638: 
                   11639: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11640: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11641: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11642: 
1.593     albertel 11643: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11644: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11645: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11646: 
1.60      www      11647: # ----------------------------------------------------------- first, check user
1.624     albertel 11648: 
                   11649: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11650: 				       ([$courselevelr,'resource'],
                   11651: 					[$courselevelm,'map'     ],
                   11652: 					[$courselevel, 'course'  ]));
1.931     albertel 11653: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11654: 
1.594     albertel 11655: # ------------------------------------------------ second, check some of course
1.684     raeburn  11656:             my $coursereply;
1.691     raeburn  11657:             if (@groups > 0) {
                   11658:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11659:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11660:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11661:             }
1.96      www      11662: 
1.684     raeburn  11663: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11664: 				  $env{'course.'.$courseid.'.domain'},
                   11665: 				  'course',
                   11666: 				  ([$seclevelr,   'resource'],
                   11667: 				   [$seclevelm,   'map'     ],
                   11668: 				   [$seclevel,    'course'  ],
                   11669: 				   [$courselevelr,'resource']));
                   11670: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11671: 
1.60      www      11672: # ------------------------------------------------------ third, check map parms
1.218     albertel 11673: 	    my %parmhash=();
                   11674: 	    my $thisparm='';
                   11675: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11676: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11677: 		    &GDBM_READER(),0640)) {
1.218     albertel 11678: 		$thisparm=$parmhash{$symbparm};
                   11679: 		untie(%parmhash);
                   11680: 	    }
1.927     albertel 11681: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11682: 	}
1.594     albertel 11683: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11684: 
1.218     albertel 11685: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11686: 	my $filename;
                   11687: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11688: 	if ($symbparm) {
1.409     www      11689: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11690: 	} else {
1.620     albertel 11691: 	    $filename=$env{'request.filename'};
1.282     albertel 11692: 	}
                   11693: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11694: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11695: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11696: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11697: 
1.927     albertel 11698: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11699: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11700: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11701: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11702: 				     $env{'course.'.$courseid.'.domain'},
                   11703: 				     'course',
1.927     albertel 11704: 				     ([$courselevelm,'map'   ],
                   11705: 				      [$courselevel, 'course']));
                   11706: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11707: 	}
1.145     www      11708: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11709: 	unless ($space eq '0') {
1.336     albertel 11710: 	    my @parts=split(/_/,$space);
                   11711: 	    my $id=pop(@parts);
                   11712: 	    my $part=join('_',@parts);
                   11713: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11714: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11715: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11716: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11717: 	}
1.395     albertel 11718: 	if ($recurse) { return undef; }
                   11719: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11720: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11721: # ---------------------------------------------------- Any other user namespace
                   11722:     } elsif ($realm eq 'environment') {
                   11723: # ----------------------------------------------------------------- environment
1.620     albertel 11724: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11725: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11726: 	} else {
1.770     albertel 11727: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11728: 		return '';
                   11729: 	    }
1.219     albertel 11730: 	    my %returnhash=&userenvironment($udom,$uname,
                   11731: 					    $spacequalifierrest);
                   11732: 	    return $returnhash{$spacequalifierrest};
                   11733: 	}
1.28      www      11734:     } elsif ($realm eq 'system') {
1.48      www      11735: # ----------------------------------------------------------------- system.time
                   11736: 	if ($space eq 'time') {
                   11737: 	    return time;
                   11738:         }
1.696     albertel 11739:     } elsif ($realm eq 'server') {
                   11740: # ----------------------------------------------------------------- system.time
                   11741: 	if ($space eq 'name') {
                   11742: 	    return $ENV{'SERVER_NAME'};
                   11743:         }
1.28      www      11744:     }
1.48      www      11745:     return '';
1.61      www      11746: }
                   11747: 
1.927     albertel 11748: sub get_reply {
                   11749:     my ($reply_value) = @_;
1.940     raeburn  11750:     if (ref($reply_value) eq 'ARRAY') {
                   11751:         if (wantarray) {
                   11752: 	    return @$reply_value;
                   11753:         }
                   11754:         return $reply_value->[0];
                   11755:     } else {
                   11756:         return $reply_value;
1.927     albertel 11757:     }
                   11758: }
                   11759: 
1.691     raeburn  11760: sub check_group_parms {
                   11761:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11762:     my @groupitems = ();
                   11763:     my $resultitem;
1.927     albertel 11764:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11765:     foreach my $group (@{$groups}) {
                   11766:         foreach my $level (@levels) {
1.927     albertel 11767:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11768:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11769:         }
                   11770:     }
                   11771:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11772:                             $env{'course.'.$courseid.'.domain'},
                   11773:                                      'course',@groupitems);
                   11774:     return $coursereply;
                   11775: }
                   11776: 
                   11777: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11778:     my ($courseid,@groups) = @_;
                   11779:     @groups = sort(@groups);
1.691     raeburn  11780:     return @groups;
                   11781: }
                   11782: 
1.395     albertel 11783: sub packages_tab_default {
                   11784:     my ($uri,$varname)=@_;
                   11785:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11786: 
                   11787:     my (@extension,@specifics,$do_default);
                   11788:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11789: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11790: 	if ($pack_type eq 'default') {
                   11791: 	    $do_default=1;
                   11792: 	} elsif ($pack_type eq 'extension') {
                   11793: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11794: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11795: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11796: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11797: 	}
                   11798:     }
                   11799:     # first look for a package that matches the requested part id
                   11800:     foreach my $package (@specifics) {
                   11801: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11802: 	next if ($pack_part ne $part);
                   11803: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11804: 	    return $packagetab{"$pack_type&$name&default"};
                   11805: 	}
                   11806:     }
                   11807:     # look for any possible matching non extension_ package
                   11808:     foreach my $package (@specifics) {
                   11809: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11810: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11811: 	    return $packagetab{"$pack_type&$name&default"};
                   11812: 	}
1.585     albertel 11813: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11814: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11815: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11816: 	}
                   11817:     }
1.738     albertel 11818:     # look for any posible extension_ match
                   11819:     foreach my $package (@extension) {
                   11820: 	my ($package,$pack_type)=@{$package};
                   11821: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11822: 	    return $packagetab{"$pack_type&$name&default"};
                   11823: 	}
                   11824: 	if (defined($packagetab{$package."&$name&default"})) {
                   11825: 	    return $packagetab{$package."&$name&default"};
                   11826: 	}
                   11827:     }
                   11828:     # look for a global default setting
                   11829:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11830: 	return $packagetab{"default&$name&default"};
                   11831:     }
1.395     albertel 11832:     return undef;
                   11833: }
                   11834: 
1.334     albertel 11835: sub add_prefix_and_part {
                   11836:     my ($prefix,$part)=@_;
                   11837:     my $keyroot;
                   11838:     if (defined($prefix) && $prefix !~ /^__/) {
                   11839: 	# prefix that has a part already
                   11840: 	$keyroot=$prefix;
                   11841:     } elsif (defined($prefix)) {
                   11842: 	# prefix that is missing a part
                   11843: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11844:     } else {
                   11845: 	# no prefix at all
                   11846: 	if (defined($part)) { $keyroot='_'.$part; }
                   11847:     }
                   11848:     return $keyroot;
                   11849: }
                   11850: 
1.71      www      11851: # ---------------------------------------------------------------- Get metadata
                   11852: 
1.599     albertel 11853: my %metaentry;
1.1070    www      11854: my %importedpartids;
1.1172.2.99  raeburn  11855: my %importedrespids;
1.71      www      11856: sub metadata {
1.176     www      11857:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11858:     $uri=&declutter($uri);
1.288     albertel 11859:     # if it is a non metadata possible uri return quickly
1.529     albertel 11860:     if (($uri eq '') || 
                   11861: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11862:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11863:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11864: 	return undef;
                   11865:     }
1.1172.2.49  raeburn  11866:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11867: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11868: 	return undef;
1.288     albertel 11869:     }
1.73      www      11870:     my $filename=$uri;
                   11871:     $uri=~s/\.meta$//;
1.172     www      11872: #
                   11873: # Is the metadata already cached?
1.177     www      11874: # Look at timestamp of caching
1.172     www      11875: # Everything is cached by the main uri, libraries are never directly cached
                   11876: #
1.428     albertel 11877:     if (!defined($liburi)) {
1.599     albertel 11878: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11879: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11880:     }
                   11881:     {
1.1069    www      11882: # Imported parts would go here
1.1172.2.99  raeburn  11883:         my @origfiletagids=();
1.1069    www      11884:         my $importedparts=0;
1.1172.2.99  raeburn  11885: 
                   11886: # Imported responseids would go here
                   11887:         my $importedresponses=0;
1.172     www      11888: #
                   11889: # Is this a recursive call for a library?
                   11890: #
1.599     albertel 11891: #	if (! exists($metacache{$uri})) {
                   11892: #	    $metacache{$uri}={};
                   11893: #	}
1.924     albertel 11894: 	my $cachetime = 60*60;
1.171     www      11895:         if ($liburi) {
                   11896: 	    $liburi=&declutter($liburi);
                   11897:             $filename=$liburi;
1.401     bowersj2 11898:         } else {
1.599     albertel 11899: 	    &devalidate_cache_new('meta',$uri);
                   11900: 	    undef(%metaentry);
1.401     bowersj2 11901: 	}
1.140     www      11902:         my %metathesekeys=();
1.73      www      11903:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11904: 	my $metastring;
1.1140    www      11905: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11906: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11907: 	    $metastring = 
1.929     albertel 11908: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11909: 					  ('grade_target' => 'meta'));
                   11910: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11911: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11912:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11913: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11914: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11915: 	    $metastring=&getfile($file);
1.489     albertel 11916: 	}
1.208     albertel 11917:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11918:         my $token;
1.140     www      11919:         undef %metathesekeys;
1.71      www      11920:         while ($token=$parser->get_token) {
1.339     albertel 11921: 	    if ($token->[0] eq 'S') {
                   11922: 		if (defined($token->[2]->{'package'})) {
1.172     www      11923: #
                   11924: # This is a package - get package info
                   11925: #
1.339     albertel 11926: 		    my $package=$token->[2]->{'package'};
                   11927: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11928: 		    if (defined($token->[2]->{'id'})) { 
                   11929: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11930: 		    }
1.599     albertel 11931: 		    if ($metaentry{':packages'}) {
                   11932: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11933: 		    } else {
1.599     albertel 11934: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11935: 		    }
1.736     albertel 11936: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11937: 			my $part=$keyroot;
                   11938: 			$part=~s/^\_//;
1.736     albertel 11939: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11940: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11941: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11942: 			    # ignore package.tab specified default values
                   11943:                             # here &package_tab_default() will fetch those
                   11944: 			    if ($subp eq 'default') { next; }
1.736     albertel 11945: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11946: 			    my $unikey;
                   11947: 			    if ($pack =~ /_0$/) {
                   11948: 				$unikey='parameter_0_'.$name;
                   11949: 				$part=0;
                   11950: 			    } else {
                   11951: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11952: 			    }
1.339     albertel 11953: 			    if ($subp eq 'display') {
                   11954: 				$value.=' [Part: '.$part.']';
                   11955: 			    }
1.599     albertel 11956: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11957: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11958: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11959: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11960: 			    }
1.599     albertel 11961: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11962: 				$metaentry{':'.$unikey}=
                   11963: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11964: 			    }
1.339     albertel 11965: 			}
                   11966: 		    }
                   11967: 		} else {
1.172     www      11968: #
                   11969: # This is not a package - some other kind of start tag
1.339     albertel 11970: #
                   11971: 		    my $entry=$token->[1];
1.1068    www      11972: 		    my $unikey='';
1.175     www      11973: 
1.339     albertel 11974: 		    if ($entry eq 'import') {
1.175     www      11975: #
                   11976: # Importing a library here
1.339     albertel 11977: #
1.1067    www      11978:                         my $location=$parser->get_text('/import');
                   11979:                         my $dir=$filename;
                   11980:                         $dir=~s|[^/]*$||;
                   11981:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11982: 
                   11983:                         my $importid=$token->[2]->{'id'};
1.1068    www      11984:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11985: #
                   11986: # Check metadata for imported file to
                   11987: # see if it contained response items
                   11988: #
                   11989:                         my %currmetaentry = %metaentry;
                   11990:                         my $libresponseorder = &metadata($location,'responseorder');
                   11991:                         my $origfile;
                   11992:                         if ($libresponseorder ne '') {
                   11993:                             if ($#origfiletagids<0) {
                   11994:                                 undef(%importedrespids);
                   11995:                                 undef(%importedpartids);
                   11996:                             }
                   11997:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11998:                             if (@{$importedrespids{$importid}} > 0) {
                   11999:                                 $importedresponses = 1;
                   12000: # We need to get the original file and the imported file to get the response order correct
                   12001: # Load and inspect original file
                   12002:                                 if ($#origfiletagids<0) {
                   12003:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12004:                                     $origfile=&getfile($origfilelocation);
                   12005:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12006:                                 }
                   12007:                             }
                   12008:                         }
                   12009: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12010: # hash populated for imported library file
                   12011:                         %metaentry = %currmetaentry;
                   12012:                         undef(%currmetaentry);
1.1068    www      12013:                         if ($importmode eq 'problem') {
1.1069    www      12014: # Import as problem/response
1.1068    www      12015:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12016:                         } elsif ($importmode eq 'part') {
                   12017: # Import as part(s)
1.1069    www      12018:                            $importedparts=1;
                   12019: # We need to get the original file and the imported file to get the part order correct
                   12020: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12021: # Load and inspect original file if we didn't do that already
                   12022:                            if ($#origfiletagids<0) {
                   12023:                                undef(%importedrespids);
                   12024:                                undef(%importedpartids);
                   12025:                                if ($origfile eq '') {
                   12026:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12027:                                    $origfile=&getfile($origfilelocation);
                   12028:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12029:                                }
1.1070    www      12030:                            }
                   12031: 
1.1069    www      12032: # Load and inspect imported file
                   12033:                            my $impfile=&getfile($location);
                   12034:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12035:                            if ($#impfilepartids>=0) {
                   12036: # This problem had parts
1.1070    www      12037:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12038:                            } else {
                   12039: # Importing by turning a single problem into a problem part
                   12040: # It gets the import-tags ID as part-ID
                   12041:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12042:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12043:                            }
1.1068    www      12044:                         } else {
                   12045: # Normal import
                   12046:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12047:                            if (defined($token->[2]->{'id'})) {
                   12048:                               $unikey.='_'.$token->[2]->{'id'};
                   12049:                            }
1.1067    www      12050:                         }
                   12051: 
1.339     albertel 12052: 			if ($depthcount<20) {
1.736     albertel 12053: 			    my $metadata = 
                   12054: 				&metadata($uri,'keys', $location,$unikey,
                   12055: 					  $depthcount+1);
                   12056: 			    foreach my $meta (split(',',$metadata)) {
                   12057: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12058: 				$metathesekeys{$meta}=1;
1.339     albertel 12059: 			    }
1.1068    www      12060: 			
                   12061:                         }
1.1067    www      12062: 		    } else {
                   12063: #
                   12064: # Not importing, some other kind of non-package, non-library start tag
                   12065: # 
                   12066:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12067:                         if (defined($token->[2]->{'id'})) {
                   12068:                             $unikey.='_'.$token->[2]->{'id'};
                   12069:                         }
1.339     albertel 12070: 			if (defined($token->[2]->{'name'})) { 
                   12071: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12072: 			}
                   12073: 			$metathesekeys{$unikey}=1;
1.736     albertel 12074: 			foreach my $param (@{$token->[3]}) {
                   12075: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12076: 				$token->[2]->{$param};
1.339     albertel 12077: 			}
                   12078: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12079: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12080: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12081: 		 # only ws inside the tag, and not in default, so use default
                   12082: 		 # as value
1.599     albertel 12083: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12084: 			} elsif ( $internaltext =~ /\S/ ) {
                   12085: 		  # something interesting inside the tag
                   12086: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12087: 			} else {
1.908     albertel 12088: 		  # no interesting values, don't set a default
1.339     albertel 12089: 			}
1.172     www      12090: # end of not-a-package not-a-library import
1.339     albertel 12091: 		    }
1.172     www      12092: # end of not-a-package start tag
1.339     albertel 12093: 		}
1.172     www      12094: # the next is the end of "start tag"
1.339     albertel 12095: 	    }
                   12096: 	}
1.483     albertel 12097: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12098: 	$extension = lc($extension);
                   12099: 	if ($extension eq 'htm') { $extension='html'; }
                   12100: 
1.737     albertel 12101: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12102: 	    #no specific packages #how's our extension
                   12103: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12104: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12105: 					 \%metathesekeys);
                   12106: 	}
1.883     albertel 12107: 
                   12108: 	if (!exists($metaentry{':packages'})
                   12109: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12110: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12111: 		#no specific packages well let's get default then
                   12112: 		if ($key!~/^default&/) { next; }
1.488     albertel 12113: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12114: 					     \%metathesekeys);
                   12115: 	    }
                   12116: 	}
1.338     www      12117: # are there custom rights to evaluate
1.599     albertel 12118: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12119: 
1.338     www      12120:     #
                   12121:     # Importing a rights file here
1.339     albertel 12122:     #
                   12123: 	    unless ($depthcount) {
1.599     albertel 12124: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12125: 		my $dir=$filename;
                   12126: 		$dir=~s|[^/]*$||;
                   12127: 		$location=&filelocation($dir,$location);
1.736     albertel 12128: 		my $rights_metadata =
                   12129: 		    &metadata($uri,'keys',$location,'_rights',
                   12130: 			      $depthcount+1);
                   12131: 		foreach my $rights (split(',',$rights_metadata)) {
                   12132: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12133: 		    $metathesekeys{$rights}=1;
1.339     albertel 12134: 		}
                   12135: 	    }
                   12136: 	}
1.737     albertel 12137: 	# uniqifiy package listing
                   12138: 	my %seen;
                   12139: 	my @uniq_packages =
                   12140: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12141: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12142: 
1.1172.2.99  raeburn  12143:         if (($importedresponses) || ($importedparts)) {
                   12144:             if ($importedparts) {
1.1070    www      12145: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12146:                 $metaentry{':partorder'}='';
                   12147:                 $metathesekeys{'partorder'}=1;
                   12148:             }
                   12149:             if ($importedresponses) {
                   12150: # We had imported responses and need to rebuild responseorder
                   12151:                 $metaentry{':responseorder'}='';
                   12152:                 $metathesekeys{'responseorder'}=1;
                   12153:             }
                   12154:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12155:                 my $origid = $origfiletagids[$index+1];
                   12156:                 if ($origfiletagids[$index] eq 'part') {
                   12157: # Original part, part of the problem
                   12158:                     if ($importedparts) {
                   12159:                         $metaentry{':partorder'}.=','.$origid;
                   12160:                     }
                   12161:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12162:                     if ($importedparts) {
                   12163: # We have imported parts at this position
                   12164:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12165:                     }
                   12166:                     if ($importedresponses) {
                   12167: # We have imported responses at this position
                   12168:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12169:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12170:                         }
                   12171:                     }
                   12172:                 } else {
                   12173: # Original response item, part of the problem
                   12174:                     if ($importedresponses) {
                   12175:                         $metaentry{':responseorder'}.=','.$origid;
                   12176:                     }
                   12177:                 }
                   12178:             }
                   12179:             if ($importedparts) {
                   12180:                 $metaentry{':partorder'}=~s/^\,//;
                   12181:             }
                   12182:             if ($importedresponses) {
                   12183:                 $metaentry{':responseorder'}=~s/^\,//;
                   12184:             }
1.1070    www      12185:         }
                   12186: 
1.737     albertel 12187: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12188: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12189: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12190: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12191: # this is the end of "was not already recently cached
1.71      www      12192:     }
1.599     albertel 12193:     return $metaentry{':'.$what};
1.261     albertel 12194: }
                   12195: 
1.488     albertel 12196: sub metadata_create_package_def {
1.483     albertel 12197:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12198:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12199:     if ($subp eq 'default') { next; }
                   12200:     
1.599     albertel 12201:     if (defined($metaentry{':packages'})) {
                   12202: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12203:     } else {
1.599     albertel 12204: 	$metaentry{':packages'}=$package;
1.483     albertel 12205:     }
                   12206:     my $value=$packagetab{$key};
                   12207:     my $unikey;
                   12208:     $unikey='parameter_0_'.$name;
1.599     albertel 12209:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12210:     $$metathesekeys{$unikey}=1;
1.599     albertel 12211:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12212: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12213:     }
1.599     albertel 12214:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12215: 	$metaentry{':'.$unikey}=
                   12216: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12217:     }
                   12218: }
                   12219: 
1.261     albertel 12220: sub metadata_generate_part0 {
                   12221:     my ($metadata,$metacache,$uri) = @_;
                   12222:     my %allnames;
1.737     albertel 12223:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12224: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12225: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12226: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12227: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12228: 	    $allnames{$name}=$part;
                   12229: 	  }
                   12230: 	}
                   12231:     }
                   12232:     foreach my $name (keys(%allnames)) {
                   12233:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12234:       my $key=":parameter_0_$name";
1.261     albertel 12235:       $$metacache{"$key.part"}='0';
                   12236:       $$metacache{"$key.name"}=$name;
1.428     albertel 12237:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12238: 					   $allnames{$name}.'_'.$name.
                   12239: 					   '.type'};
1.428     albertel 12240:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12241: 			     '.display'};
1.644     www      12242:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12243:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12244:       $$metacache{"$key.display"}=$olddis;
                   12245:     }
1.71      www      12246: }
                   12247: 
1.764     albertel 12248: # ------------------------------------------------------ Devalidate title cache
                   12249: 
                   12250: sub devalidate_title_cache {
                   12251:     my ($url)=@_;
                   12252:     if (!$env{'request.course.id'}) { return; }
                   12253:     my $symb=&symbread($url);
                   12254:     if (!$symb) { return; }
                   12255:     my $key=$env{'request.course.id'}."\0".$symb;
                   12256:     &devalidate_cache_new('title',$key);
                   12257: }
                   12258: 
1.1014    droeschl 12259: # ------------------------------------------------- Get the title of a course
                   12260: 
                   12261: sub current_course_title {
                   12262:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12263: }
1.301     www      12264: # ------------------------------------------------- Get the title of a resource
                   12265: 
                   12266: sub gettitle {
                   12267:     my $urlsymb=shift;
                   12268:     my $symb=&symbread($urlsymb);
1.534     albertel 12269:     if ($symb) {
1.620     albertel 12270: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12271: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12272: 	if (defined($cached)) { 
                   12273: 	    return $result;
                   12274: 	}
1.534     albertel 12275: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12276: 	my $title='';
1.907     albertel 12277: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12278: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12279: 	} else {
                   12280: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12281: 		    &GDBM_READER(),0640)) {
                   12282: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12283: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12284: 		untie(%bighash);
                   12285: 	    }
1.534     albertel 12286: 	}
                   12287: 	$title=~s/\&colon\;/\:/gs;
                   12288: 	if ($title) {
1.1159    www      12289: # Remember both $symb and $title for dynamic metadata
                   12290:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12291:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12292: # Cache this title and then return it
1.599     albertel 12293: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12294: 	}
                   12295: 	$urlsymb=$url;
                   12296:     }
                   12297:     my $title=&metadata($urlsymb,'title');
                   12298:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12299:     return $title;
1.301     www      12300: }
1.613     albertel 12301: 
1.614     albertel 12302: sub get_slot {
                   12303:     my ($which,$cnum,$cdom)=@_;
                   12304:     if (!$cnum || !$cdom) {
1.790     albertel 12305: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12306: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12307: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12308:     }
1.703     albertel 12309:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12310:     my %slotinfo;
                   12311:     if (exists($remembered{$key})) {
                   12312: 	$slotinfo{$which} = $remembered{$key};
                   12313:     } else {
                   12314: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12315: 	&Apache::lonhomework::showhash(%slotinfo);
                   12316: 	my ($tmp)=keys(%slotinfo);
                   12317: 	if ($tmp=~/^error:/) { return (); }
                   12318: 	$remembered{$key} = $slotinfo{$which};
                   12319:     }
1.616     albertel 12320:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12321: 	return %{$slotinfo{$which}};
                   12322:     }
                   12323:     return $slotinfo{$which};
1.614     albertel 12324: }
1.1150    raeburn  12325: 
                   12326: sub get_reservable_slots {
                   12327:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12328:     my $now = time;
                   12329:     my $reservable_info;
                   12330:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12331:     if (exists($remembered{$key})) {
                   12332:         $reservable_info = $remembered{$key};
                   12333:     } else {
                   12334:         my %resv;
                   12335:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12336:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12337:         $reservable_info = \%resv;
                   12338:         $remembered{$key} = $reservable_info;
                   12339:     }
                   12340:     return $reservable_info;
                   12341: }
                   12342: 
                   12343: sub get_course_slots {
                   12344:     my ($cnum,$cdom) = @_;
                   12345:     my $hashid=$cnum.':'.$cdom;
                   12346:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12347:     if (defined($cached)) {
                   12348:         if (ref($result) eq 'HASH') {
                   12349:             return %{$result};
                   12350:         }
                   12351:     } else {
                   12352:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12353:         my ($tmp) = keys(%slots);
                   12354:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12355:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12356:             return %slots;
                   12357:         }
                   12358:     }
                   12359:     return;
                   12360: }
                   12361: 
                   12362: sub devalidate_slots_cache {
                   12363:     my ($cnum,$cdom)=@_;
                   12364:     my $hashid=$cnum.':'.$cdom;
                   12365:     &devalidate_cache_new('allslots',$hashid);
                   12366: }
                   12367: 
1.1172.2.8  raeburn  12368: sub get_coursechange {
                   12369:     my ($cdom,$cnum) = @_;
                   12370:     if ($cdom eq '' || $cnum eq '') {
                   12371:         return unless ($env{'request.course.id'});
                   12372:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12373:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12374:     }
                   12375:     my $hashid=$cdom.'_'.$cnum;
                   12376:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12377:     if ((defined($cached)) && ($change ne '')) {
                   12378:         return $change;
                   12379:     } else {
                   12380:         my %crshash;
                   12381:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12382:         if ($crshash{'internal.contentchange'} eq '') {
                   12383:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12384:             if ($change eq '') {
                   12385:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12386:                 $change = $crshash{'internal.created'};
                   12387:             }
                   12388:         } else {
                   12389:             $change = $crshash{'internal.contentchange'};
                   12390:         }
                   12391:         my $cachetime = 600;
                   12392:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12393:     }
                   12394:     return $change;
                   12395: }
                   12396: 
                   12397: sub devalidate_coursechange_cache {
                   12398:     my ($cnum,$cdom)=@_;
                   12399:     my $hashid=$cnum.':'.$cdom;
                   12400:     &devalidate_cache_new('crschange',$hashid);
                   12401: }
                   12402: 
1.31      www      12403: # ------------------------------------------------- Update symbolic store links
                   12404: 
                   12405: sub symblist {
                   12406:     my ($mapname,%newhash)=@_;
1.438     www      12407:     $mapname=&deversion(&declutter($mapname));
1.31      www      12408:     my %hash;
1.620     albertel 12409:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12410:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12411:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12412: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12413: 		next if ($url eq 'last_known'
                   12414: 			 && $env{'form.no_update_last_known'});
                   12415: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12416: 						    $newhash{$url}->[1],
                   12417: 						    $newhash{$url}->[0]);
1.191     harris41 12418:             }
1.31      www      12419:             if (untie(%hash)) {
                   12420: 		return 'ok';
                   12421:             }
                   12422:         }
                   12423:     }
                   12424:     return 'error';
1.212     www      12425: }
                   12426: 
                   12427: # --------------------------------------------------------------- Verify a symb
                   12428: 
                   12429: sub symbverify {
1.1172.2.11  raeburn  12430:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12431:     my $thisfn=$thisurl;
1.439     www      12432:     $thisfn=&declutter($thisfn);
1.215     www      12433: # direct jump to resource in page or to a sequence - will construct own symbs
                   12434:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12435: # check URL part
1.409     www      12436:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12437: 
1.431     www      12438:     unless ($url eq $thisfn) { return 0; }
1.213     www      12439: 
1.216     www      12440:     $symb=&symbclean($symb);
1.510     www      12441:     $thisurl=&deversion($thisurl);
1.439     www      12442:     $thisfn=&deversion($thisfn);
1.213     www      12443: 
                   12444:     my %bighash;
                   12445:     my $okay=0;
1.431     www      12446: 
1.620     albertel 12447:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12448:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12449:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12450:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12451:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12452:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12453:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12454:             }
                   12455:         }
                   12456:         my $ids;
1.1172.2.118.  .5(raebu 12457:20):         if ($map =~ m{^uploaded/.+\.page$}) {
                   12458:20):             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12459:         } else {
                   12460:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12461:         }
1.1102    raeburn  12462:         unless ($ids) {
1.1172.2.13  raeburn  12463:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12464:             $ids=$bighash{$idkey};
1.216     www      12465:         }
                   12466:         if ($ids) {
                   12467: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12468:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12469:                 $symb =~ s/\?.+$//;
                   12470:             }
1.800     albertel 12471: 	    foreach my $id (split(/\,/,$ids)) {
                   12472: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12473:                if (
                   12474:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12475:    eq $symb) {
1.1172.2.11  raeburn  12476:                    if (ref($encstate)) {
                   12477:                        $$encstate = $bighash{'encrypted_'.$id};
                   12478:                    }
1.1172.2.13  raeburn  12479:                    if (($env{'request.role.adv'}) ||
                   12480:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12481:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12482:                        $okay=1;
                   12483:                        last;
                   12484:                    }
                   12485:                }
                   12486:            }
1.216     www      12487:         }
1.213     www      12488: 	untie(%bighash);
                   12489:     }
                   12490:     return $okay;
1.31      www      12491: }
                   12492: 
1.210     www      12493: # --------------------------------------------------------------- Clean-up symb
                   12494: 
                   12495: sub symbclean {
                   12496:     my $symb=shift;
1.568     albertel 12497:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12498: # remove version from map
                   12499:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12500: 
1.210     www      12501: # remove version from URL
                   12502:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12503: 
1.507     www      12504: # remove wrapper
                   12505: 
1.510     www      12506:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12507:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12508:     return $symb;
1.409     www      12509: }
                   12510: 
                   12511: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12512: 
                   12513: sub encode_symb {
                   12514:     my ($map,$resid,$url)=@_;
                   12515:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12516: }
1.409     www      12517: 
                   12518: sub decode_symb {
1.568     albertel 12519:     my $symb=shift;
                   12520:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12521:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12522:     return (&fixversion($map),$resid,&fixversion($url));
                   12523: }
                   12524: 
                   12525: sub fixversion {
                   12526:     my $fn=shift;
1.609     banghart 12527:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12528:     my %bighash;
                   12529:     my $uri=&clutter($fn);
1.620     albertel 12530:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12531: # is this cached?
1.599     albertel 12532:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12533:     if (defined($cached)) { return $result; }
                   12534: # unfortunately not cached, or expired
1.620     albertel 12535:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12536: 	    &GDBM_READER(),0640)) {
                   12537:  	if ($bighash{'version_'.$uri}) {
                   12538:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12539:  	    unless (($version eq 'mostrecent') || 
                   12540: 		    ($version==&getversion($uri))) {
1.440     www      12541:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12542:  	    }
                   12543:  	}
                   12544:  	untie %bighash;
1.413     www      12545:     }
1.599     albertel 12546:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12547: }
                   12548: 
                   12549: sub deversion {
                   12550:     my $url=shift;
                   12551:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12552:     return $url;
1.210     www      12553: }
                   12554: 
1.31      www      12555: # ------------------------------------------------------ Return symb list entry
                   12556: 
                   12557: sub symbread {
1.1172.2.118.  .8(raebu 12558:20):     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
          .9(raebu 12559:20):         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12560:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.118.  .9(raebu 12561:20):     if (defined($env{$cache_str})) {
          .8(raebu 12562:20):         unless (ref($possibles) eq 'HASH') {
                   12563:20):             if ($ignorecachednull) {
                   12564:20):                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12565:20):             } else {
                   12566:20):                 return $env{$cache_str};
                   12567:20):             }
1.1172.2.66  raeburn  12568:         }
                   12569:     }
1.242     www      12570: # no filename provided? try from environment
1.1172.2.54  raeburn  12571:     unless ($thisfn) {
1.620     albertel 12572:         if ($env{'request.symb'}) {
1.1172.2.118.  .9(raebu 12573:20):             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12574:         }
                   12575:         $thisfn=$env{'request.filename'};
1.44      www      12576:     }
1.569     albertel 12577:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12578: # is that filename actually a symb? Verify, clean, and return
                   12579:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12580: 	if (&symbverify($thisfn,$1)) {
1.1172.2.118.  .9(raebu 12581:20): 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12582: 	}
1.242     www      12583:     }
1.44      www      12584:     $thisfn=declutter($thisfn);
1.31      www      12585:     my %hash;
1.37      www      12586:     my %bighash;
                   12587:     my $syval='';
1.620     albertel 12588:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12589:         my $targetfn = $thisfn;
1.609     banghart 12590:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12591:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12592:         }
1.687     albertel 12593: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12594: 	    $targetfn=$1;
                   12595: 	}
1.1172.2.118.  .9(raebu 12596:20):         unless ($ignoresymbdb) {
          .8(raebu 12597:20):             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12598:20):                           &GDBM_READER(),0640)) {
                   12599:20): 	        $syval=$hash{$targetfn};
                   12600:20):                 untie(%hash);
                   12601:20):             }
          .9(raebu 12602:20):             if ($syval && $checkforblock) {
                   12603:20):                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
          .8(raebu 12604:20):                 if (@blockers) {
                   12605:20):                     $syval='';
                   12606:20):                 }
                   12607:20):             }
1.37      www      12608:         }
                   12609: # ---------------------------------------------------------- There was an entry
                   12610:         if ($syval) {
1.601     albertel 12611: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12612: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12613: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12614: 		    #return $env{$cache_str}='';
1.601     albertel 12615: 		#}    
                   12616: 		#$syval.=$1;
                   12617: 	    #}
1.37      www      12618:         } else {
                   12619: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12620:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12621:                             &GDBM_READER(),0640)) {
1.37      www      12622: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12623:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12624:               unless ($ids) { 
                   12625:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12626:               }
                   12627:               unless ($ids) {
                   12628: # alias?
                   12629: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12630:               }
1.37      www      12631:               if ($ids) {
                   12632: # ------------------------------------------------------------------- Has ID(s)
                   12633:                  my @possibilities=split(/\,/,$ids);
1.39      www      12634:                  if ($#possibilities==0) {
                   12635: # ----------------------------------------------- There is only one possibility
1.37      www      12636: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12637: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12638: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12639:                      if (ref($possibles) eq 'HASH') {
1.1172.2.118.  .8(raebu 12640:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12641:20):                              $possibles->{$syval} = 1;
                   12642:20):                          }
1.1172.2.66  raeburn  12643:                      }
                   12644:                      if ($checkforblock) {
1.1172.2.118.  .8(raebu 12645:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12646:20):                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
                   12647:20):                              if (@blockers) {
                   12648:20):                                  $syval = '';
                   12649:20):                                  untie(%bighash);
                   12650:20):                                  return $env{$cache_str}='';
                   12651:20):                              }
1.1172.2.66  raeburn  12652:                          }
                   12653:                      }
                   12654:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12655: # ------------------------------------------ There is more than one possibility
                   12656:                      my $realpossible=0;
1.800     albertel 12657:                      foreach my $id (@possibilities) {
                   12658: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12659:                          my $canaccess;
                   12660:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12661:                              $canaccess = 1;
                   12662:                          } else {
                   12663:                              $canaccess = &allowed('bre',$file);
                   12664:                          }
                   12665:                          if ($canaccess) {
                   12666:          		     my ($mapid,$resid)=split(/\./,$id);
                   12667:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12668:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12669:                                                              $resid,$thisfn);
1.1172.2.118.  .8(raebu 12670:20):                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
                   12671:20):                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12672:                                  if ($checkforblock) {
1.1172.2.118.  .8(raebu 12673:20):                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
                   12674:20):                                      if (@blockers > 0) {
                   12675:20):                                          $syval = '';
                   12676:20):                                      } else {
1.1172.2.66  raeburn  12677:                                          $syval = $poss_syval;
                   12678:                                          $realpossible++;
                   12679:                                      }
                   12680:                                  } else {
                   12681:                                      $syval = $poss_syval;
                   12682:                                      $realpossible++;
                   12683:                                  }
1.1172.2.118.  .8(raebu 12684:20):                                  if ($syval) {
                   12685:20):                                      if (ref($possibles) eq 'HASH') {
                   12686:20):                                          $possibles->{$syval} = 1;
                   12687:20):                                      }
                   12688:20):                                  }
1.1172.2.66  raeburn  12689:                              }
1.39      www      12690: 			 }
1.191     harris41 12691:                      }
1.39      www      12692: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12693:                  } else {
                   12694:                      $syval='';
1.37      www      12695:                  }
                   12696: 	      }
1.1172.2.66  raeburn  12697:               untie(%bighash);
1.481     raeburn  12698:            }
1.31      www      12699:         }
1.62      www      12700:         if ($syval) {
1.1172.2.118.  .9(raebu 12701:20): 	    return $env{$cache_str}=$syval;
1.62      www      12702:         }
1.31      www      12703:     }
1.949     raeburn  12704:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12705:     return $env{$cache_str}='';
1.31      www      12706: }
                   12707: 
                   12708: # ---------------------------------------------------------- Return random seed
                   12709: 
1.32      www      12710: sub numval {
                   12711:     my $txt=shift;
                   12712:     $txt=~tr/A-J/0-9/;
                   12713:     $txt=~tr/a-j/0-9/;
                   12714:     $txt=~tr/K-T/0-9/;
                   12715:     $txt=~tr/k-t/0-9/;
                   12716:     $txt=~tr/U-Z/0-5/;
                   12717:     $txt=~tr/u-z/0-5/;
                   12718:     $txt=~s/\D//g;
1.564     albertel 12719:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12720:     return int($txt);
1.368     albertel 12721: }
                   12722: 
1.484     albertel 12723: sub numval2 {
                   12724:     my $txt=shift;
                   12725:     $txt=~tr/A-J/0-9/;
                   12726:     $txt=~tr/a-j/0-9/;
                   12727:     $txt=~tr/K-T/0-9/;
                   12728:     $txt=~tr/k-t/0-9/;
                   12729:     $txt=~tr/U-Z/0-5/;
                   12730:     $txt=~tr/u-z/0-5/;
                   12731:     $txt=~s/\D//g;
                   12732:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12733:     my $total;
                   12734:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12735:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12736:     return int($total);
                   12737: }
                   12738: 
1.575     albertel 12739: sub numval3 {
                   12740:     use integer;
                   12741:     my $txt=shift;
                   12742:     $txt=~tr/A-J/0-9/;
                   12743:     $txt=~tr/a-j/0-9/;
                   12744:     $txt=~tr/K-T/0-9/;
                   12745:     $txt=~tr/k-t/0-9/;
                   12746:     $txt=~tr/U-Z/0-5/;
                   12747:     $txt=~tr/u-z/0-5/;
                   12748:     $txt=~s/\D//g;
                   12749:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12750:     my $total;
                   12751:     foreach my $val (@txts) { $total+=$val; }
                   12752:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12753:     return $total;
                   12754: }
                   12755: 
1.675     albertel 12756: sub digest {
                   12757:     my ($data)=@_;
                   12758:     my $digest=&Digest::MD5::md5($data);
                   12759:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12760:     my ($e,$f);
                   12761:     {
                   12762:         use integer;
                   12763:         $e=($a+$b);
                   12764:         $f=($c+$d);
                   12765:         if ($_64bit) {
                   12766:             $e=(($e<<32)>>32);
                   12767:             $f=(($f<<32)>>32);
                   12768:         }
                   12769:     }
                   12770:     if (wantarray) {
                   12771: 	return ($e,$f);
                   12772:     } else {
                   12773: 	my $g;
                   12774: 	{
                   12775: 	    use integer;
                   12776: 	    $g=($e+$f);
                   12777: 	    if ($_64bit) {
                   12778: 		$g=(($g<<32)>>32);
                   12779: 	    }
                   12780: 	}
                   12781: 	return $g;
                   12782:     }
                   12783: }
                   12784: 
1.368     albertel 12785: sub latest_rnd_algorithm_id {
1.675     albertel 12786:     return '64bit5';
1.366     albertel 12787: }
1.32      www      12788: 
1.503     albertel 12789: sub get_rand_alg {
                   12790:     my ($courseid)=@_;
1.790     albertel 12791:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12792:     if ($courseid) {
1.620     albertel 12793: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12794:     }
                   12795:     return &latest_rnd_algorithm_id();
                   12796: }
                   12797: 
1.562     albertel 12798: sub validCODE {
                   12799:     my ($CODE)=@_;
                   12800:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12801:     return 0;
                   12802: }
                   12803: 
1.491     albertel 12804: sub getCODE {
1.620     albertel 12805:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12806:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12807: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12808: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12809: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12810:     }
                   12811:     return undef;
                   12812: }
1.1133    foxr     12813: #
                   12814: #  Determines the random seed for a specific context:
                   12815: #
                   12816: # parameters:
                   12817: #   symb      - in course context the symb for the seed.
                   12818: #   course_id - The course id of the form domain_coursenum.
                   12819: #   domain    - Domain for the user.
                   12820: #   course    - Course for the user.
                   12821: #   cenv      - environment of the course.
                   12822: #
                   12823: # NOTE:
                   12824: #   All parameters are picked out of the environment if missing
                   12825: #   or not defined.
                   12826: #   If a symb cannot be determined the current time is used instead.
                   12827: #
                   12828: #  For a given well defined symb, courside, domain, username,
                   12829: #  and course environment, the seed is reproducible.
                   12830: #
1.31      www      12831: sub rndseed {
1.1133    foxr     12832:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12833:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12834:     if (!defined($symb)) {
1.366     albertel 12835: 	unless ($symb=$wsymb) { return time; }
                   12836:     }
1.1146    foxr     12837:     if (!defined $courseid) { 
                   12838: 	$courseid=$wcourseid; 
                   12839:     }
                   12840:     if (!defined $domain) { $domain=$wdomain; }
                   12841:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12842: 
                   12843:     my $which;
                   12844:     if (defined($cenv->{'rndseed'})) {
                   12845: 	$which = $cenv->{'rndseed'};
                   12846:     } else {
                   12847: 	$which =&get_rand_alg($courseid);
                   12848:     }
1.491     albertel 12849:     if (defined(&getCODE())) {
1.675     albertel 12850: 	if ($which eq '64bit5') {
                   12851: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12852: 	} elsif ($which eq '64bit4') {
1.575     albertel 12853: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12854: 	} else {
                   12855: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12856: 	}
1.675     albertel 12857:     } elsif ($which eq '64bit5') {
                   12858: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12859:     } elsif ($which eq '64bit4') {
                   12860: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12861:     } elsif ($which eq '64bit3') {
                   12862: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12863:     } elsif ($which eq '64bit2') {
                   12864: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12865:     } elsif ($which eq '64bit') {
                   12866: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12867:     }
                   12868:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12869: }
                   12870: 
                   12871: sub rndseed_32bit {
                   12872:     my ($symb,$courseid,$domain,$username)=@_;
                   12873:     {
                   12874: 	use integer;
                   12875: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12876: 	my $symbseed=numval($symb) << 22;
                   12877: 	my $namechck=unpack("%32C*",$username) << 17;
                   12878: 	my $nameseed=numval($username) << 12;
                   12879: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12880: 	my $courseseed=unpack("%32C*",$courseid);
                   12881: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12882: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12883: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12884: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12885: 	return $num;
                   12886:     }
                   12887: }
                   12888: 
                   12889: sub rndseed_64bit {
                   12890:     my ($symb,$courseid,$domain,$username)=@_;
                   12891:     {
                   12892: 	use integer;
                   12893: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12894: 	my $symbseed=numval($symb) << 10;
                   12895: 	my $namechck=unpack("%32S*",$username);
                   12896: 	
                   12897: 	my $nameseed=numval($username) << 21;
                   12898: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12899: 	my $courseseed=unpack("%32S*",$courseid);
                   12900: 	
                   12901: 	my $num1=$symbchck+$symbseed+$namechck;
                   12902: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12903: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12904: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12905: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12906: 	return "$num1,$num2";
1.155     albertel 12907:     }
1.366     albertel 12908: }
                   12909: 
1.443     albertel 12910: sub rndseed_64bit2 {
                   12911:     my ($symb,$courseid,$domain,$username)=@_;
                   12912:     {
                   12913: 	use integer;
                   12914: 	# strings need to be an even # of cahracters long, it it is odd the
                   12915:         # last characters gets thrown away
                   12916: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12917: 	my $symbseed=numval($symb) << 10;
                   12918: 	my $namechck=unpack("%32S*",$username.' ');
                   12919: 	
                   12920: 	my $nameseed=numval($username) << 21;
1.501     albertel 12921: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12922: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12923: 	
                   12924: 	my $num1=$symbchck+$symbseed+$namechck;
                   12925: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12926: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12927: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12928: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12929: 	return "$num1,$num2";
                   12930:     }
                   12931: }
                   12932: 
                   12933: sub rndseed_64bit3 {
                   12934:     my ($symb,$courseid,$domain,$username)=@_;
                   12935:     {
                   12936: 	use integer;
                   12937: 	# strings need to be an even # of cahracters long, it it is odd the
                   12938:         # last characters gets thrown away
                   12939: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12940: 	my $symbseed=numval2($symb) << 10;
                   12941: 	my $namechck=unpack("%32S*",$username.' ');
                   12942: 	
                   12943: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12944: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12945: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12946: 	
                   12947: 	my $num1=$symbchck+$symbseed+$namechck;
                   12948: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12949: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12950: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12951: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12952: 	
1.503     albertel 12953: 	return "$num1:$num2";
1.443     albertel 12954:     }
                   12955: }
                   12956: 
1.575     albertel 12957: sub rndseed_64bit4 {
                   12958:     my ($symb,$courseid,$domain,$username)=@_;
                   12959:     {
                   12960: 	use integer;
                   12961: 	# strings need to be an even # of cahracters long, it it is odd the
                   12962:         # last characters gets thrown away
                   12963: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12964: 	my $symbseed=numval3($symb) << 10;
                   12965: 	my $namechck=unpack("%32S*",$username.' ');
                   12966: 	
                   12967: 	my $nameseed=numval3($username) << 21;
                   12968: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12969: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12970: 	
                   12971: 	my $num1=$symbchck+$symbseed+$namechck;
                   12972: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12973: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12974: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12975: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12976: 	
1.575     albertel 12977: 	return "$num1:$num2";
                   12978:     }
                   12979: }
                   12980: 
1.675     albertel 12981: sub rndseed_64bit5 {
                   12982:     my ($symb,$courseid,$domain,$username)=@_;
                   12983:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12984:     return "$num1:$num2";
                   12985: }
                   12986: 
1.366     albertel 12987: sub rndseed_CODE_64bit {
                   12988:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12989:     {
1.366     albertel 12990: 	use integer;
1.443     albertel 12991: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12992: 	my $symbseed=numval2($symb);
1.491     albertel 12993: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12994: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12995: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12996: 	my $num1=$symbseed+$CODEchck;
                   12997: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12998: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12999: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13000: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13001: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13002: 	return "$num1:$num2";
1.366     albertel 13003:     }
                   13004: }
                   13005: 
1.575     albertel 13006: sub rndseed_CODE_64bit4 {
                   13007:     my ($symb,$courseid,$domain,$username)=@_;
                   13008:     {
                   13009: 	use integer;
                   13010: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13011: 	my $symbseed=numval3($symb);
                   13012: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13013: 	my $CODEseed=numval3(&getCODE());
                   13014: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13015: 	my $num1=$symbseed+$CODEchck;
                   13016: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13017: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13018: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13019: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13020: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13021: 	return "$num1:$num2";
                   13022:     }
                   13023: }
                   13024: 
1.675     albertel 13025: sub rndseed_CODE_64bit5 {
                   13026:     my ($symb,$courseid,$domain,$username)=@_;
                   13027:     my $code = &getCODE();
                   13028:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13029:     return "$num1:$num2";
                   13030: }
                   13031: 
1.366     albertel 13032: sub setup_random_from_rndseed {
                   13033:     my ($rndseed)=@_;
1.503     albertel 13034:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13035: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13036:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13037:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13038:         } else {
                   13039:             &Math::Random::random_set_seed($num1,$num2);
                   13040:         }
1.366     albertel 13041:     } else {
                   13042: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13043:     }
1.36      albertel 13044: }
                   13045: 
1.474     albertel 13046: sub latest_receipt_algorithm_id {
1.835     albertel 13047:     return 'receipt3';
1.474     albertel 13048: }
                   13049: 
1.480     www      13050: sub recunique {
                   13051:     my $fucourseid=shift;
                   13052:     my $unique;
1.835     albertel 13053:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13054: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13055: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13056:     } else {
                   13057: 	$unique=$perlvar{'lonReceipt'};
                   13058:     }
                   13059:     return unpack("%32C*",$unique);
                   13060: }
                   13061: 
                   13062: sub recprefix {
                   13063:     my $fucourseid=shift;
                   13064:     my $prefix;
1.835     albertel 13065:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13066: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13067: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13068:     } else {
                   13069: 	$prefix=$perlvar{'lonHostID'};
                   13070:     }
                   13071:     return unpack("%32C*",$prefix);
                   13072: }
                   13073: 
1.76      www      13074: sub ireceipt {
1.474     albertel 13075:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13076: 
                   13077:     my $return =&recprefix($fucourseid).'-';
                   13078: 
                   13079:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13080: 	$env{'request.state'} eq 'construct') {
                   13081: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13082: 	return $return;
                   13083:     }
                   13084: 
1.76      www      13085:     my $cuname=unpack("%32C*",$funame);
                   13086:     my $cudom=unpack("%32C*",$fudom);
                   13087:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13088:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13089:     my $cunique=&recunique($fucourseid);
1.474     albertel 13090:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13091:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13092: 
1.790     albertel 13093: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13094: 			       
                   13095: 	$return.= ($cunique%$cuname+
                   13096: 		   $cunique%$cudom+
                   13097: 		   $cusymb%$cuname+
                   13098: 		   $cusymb%$cudom+
                   13099: 		   $cucourseid%$cuname+
                   13100: 		   $cucourseid%$cudom+
                   13101: 		   $cpart%$cuname+
                   13102: 		   $cpart%$cudom);
                   13103:     } else {
                   13104: 	$return.= ($cunique%$cuname+
                   13105: 		   $cunique%$cudom+
                   13106: 		   $cusymb%$cuname+
                   13107: 		   $cusymb%$cudom+
                   13108: 		   $cucourseid%$cuname+
                   13109: 		   $cucourseid%$cudom);
                   13110:     }
                   13111:     return $return;
1.76      www      13112: }
                   13113: 
                   13114: sub receipt {
1.474     albertel 13115:     my ($part)=@_;
1.790     albertel 13116:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13117:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13118: }
1.260     ng       13119: 
1.790     albertel 13120: sub whichuser {
                   13121:     my ($passedsymb)=@_;
                   13122:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13123:     if (defined($env{'form.grade_symb'})) {
                   13124: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13125: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13126: 	if (!$allowed &&
                   13127: 	    exists($env{'request.course.sec'}) &&
                   13128: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13129: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13130: 			      '/'.$env{'request.course.sec'});
                   13131: 	}
                   13132: 	if ($allowed) {
                   13133: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13134: 	    $courseid=$tmp_courseid;
                   13135: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13136: 	    ($name)=&get_env_multiple('form.grade_username');
                   13137: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13138: 	}
                   13139:     }
                   13140:     if (!$passedsymb) {
                   13141: 	$symb=&symbread();
                   13142:     } else {
                   13143: 	$symb=$passedsymb;
                   13144:     }
                   13145:     $courseid=$env{'request.course.id'};
                   13146:     $domain=$env{'user.domain'};
                   13147:     $name=$env{'user.name'};
                   13148:     if ($name eq 'public' && $domain eq 'public') {
                   13149: 	if (!defined($env{'form.username'})) {
                   13150: 	    $env{'form.username'}.=time.rand(10000000);
                   13151: 	}
                   13152: 	$name.=$env{'form.username'};
                   13153:     }
                   13154:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13155: 
                   13156: }
                   13157: 
1.36      albertel 13158: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13159: # returns either the contents of the file or 
                   13160: # -1 if the file doesn't exist
1.481     raeburn  13161: #
                   13162: # if the target is a file that was uploaded via DOCS, 
                   13163: # a check will be made to see if a current copy exists on the local server,
                   13164: # if it does this will be served, otherwise a copy will be retrieved from
                   13165: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13166: # the local server.   
1.472     albertel 13167: 
1.36      albertel 13168: sub getfile {
1.538     albertel 13169:     my ($file) = @_;
1.609     banghart 13170:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13171:     &repcopy($file);
                   13172:     return &readfile($file);
                   13173: }
                   13174: 
                   13175: sub repcopy_userfile {
                   13176:     my ($file)=@_;
1.1142    raeburn  13177:     my $londocroot = $perlvar{'lonDocRoot'};
                   13178:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13179:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13180:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13181: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13182:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13183:     if (-e "$file") {
1.828     www      13184: # we already have a local copy, check it out
1.538     albertel 13185: 	my @fileinfo = stat($file);
1.828     www      13186: 	my $rtncode;
                   13187: 	my $info;
1.538     albertel 13188: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13189: 	if ($lwpresp ne 'ok') {
1.828     www      13190: # there is no such file anymore, even though we had a local copy
1.482     albertel 13191: 	    if ($rtncode eq '404') {
1.538     albertel 13192: 		unlink($file);
1.482     albertel 13193: 	    }
                   13194: 	    return -1;
                   13195: 	}
                   13196: 	if ($info < $fileinfo[9]) {
1.828     www      13197: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13198: 	    return 'ok';
1.828     www      13199: 	} else {
                   13200: # the file is outdated, get rid of it
                   13201: 	    unlink($file);
1.482     albertel 13202: 	}
1.828     www      13203:     }
                   13204: # one way or the other, at this point, we don't have the file
                   13205: # construct the correct path for the file
                   13206:     my @parts = ($cdom,$cnum); 
                   13207:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13208: 	push @parts, split(/\//,$1);
                   13209:     }
                   13210:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13211:     foreach my $part (@parts) {
                   13212: 	$path .= '/'.$part;
                   13213: 	if (!-e $path) {
                   13214: 	    mkdir($path,0770);
1.482     albertel 13215: 	}
                   13216:     }
1.828     www      13217: # now the path exists for sure
                   13218: # get a user agent
                   13219:     my $ua=new LWP::UserAgent;
                   13220:     my $transferfile=$file.'.in.transfer';
                   13221: # FIXME: this should flock
                   13222:     if (-e $transferfile) { return 'ok'; }
                   13223:     my $request;
                   13224:     $uri=~s/^\///;
1.980     raeburn  13225:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13226:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13227:     my $protocol = $protocol{$homeserver};
                   13228:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13229:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13230:     my $response=$ua->request($request,$transferfile);
                   13231: # did it work?
                   13232:     if ($response->is_error()) {
                   13233: 	unlink($transferfile);
                   13234: 	&logthis("Userfile repcopy failed for $uri");
                   13235: 	return -1;
                   13236:     }
                   13237: # worked, rename the transfer file
                   13238:     rename($transferfile,$file);
1.607     raeburn  13239:     return 'ok';
1.481     raeburn  13240: }
                   13241: 
1.517     albertel 13242: sub tokenwrapper {
                   13243:     my $uri=shift;
1.980     raeburn  13244:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13245:     $uri=~s|^/||;
1.620     albertel 13246:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13247:     my $token=$1;
1.552     albertel 13248:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13249:     if ($udom && $uname && $file) {
                   13250: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13251:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13252:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13253:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13254:         my $protocol = $protocol{$homeserver};
                   13255:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13256:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13257:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13258:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13259:     } else {
                   13260:         return '/adm/notfound.html';
                   13261:     }
                   13262: }
                   13263: 
1.828     www      13264: # call with reqtype HEAD: get last modification time
                   13265: # call with reqtype GET: get the file contents
                   13266: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13267: #
1.481     raeburn  13268: sub getuploaded {
                   13269:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13270:     $uri=~s/^\///;
1.980     raeburn  13271:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13272:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13273:     my $protocol = $protocol{$homeserver};
                   13274:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13275:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13276:     my $ua=new LWP::UserAgent;
                   13277:     my $request=new HTTP::Request($reqtype,$uri);
                   13278:     my $response=$ua->request($request);
                   13279:     $$rtncode = $response->code;
1.482     albertel 13280:     if (! $response->is_success()) {
                   13281: 	return 'failed';
                   13282:     }      
                   13283:     if ($reqtype eq 'HEAD') {
1.486     www      13284: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13285:     } elsif ($reqtype eq 'GET') {
                   13286: 	$$info = $response->content;
1.472     albertel 13287:     }
1.482     albertel 13288:     return 'ok';
1.36      albertel 13289: }
                   13290: 
1.481     raeburn  13291: sub readfile {
                   13292:     my $file = shift;
                   13293:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13294:     my $fh;
1.1172.2.96  raeburn  13295:     open($fh,"<",$file);
1.481     raeburn  13296:     my $a='';
1.800     albertel 13297:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13298:     return $a;
                   13299: }
                   13300: 
1.36      albertel 13301: sub filelocation {
1.590     banghart 13302:     my ($dir,$file) = @_;
                   13303:     my $location;
                   13304:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13305: 
                   13306:     if ($file =~ m-^/adm/-) {
                   13307: 	$file=~s-^/adm/wrapper/-/-;
                   13308: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13309:     }
1.882     albertel 13310: 
1.1139    www      13311:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13312:         $location = $file;
1.609     banghart 13313:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13314:         my ($udom,$uname,$filename)=
1.811     albertel 13315:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13316:         my $home=&homeserver($uname,$udom);
                   13317:         my $is_me=0;
                   13318:         my @ids=&current_machine_ids();
                   13319:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13320:         if ($is_me) {
1.1117    foxr     13321:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13322:         } else {
                   13323:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13324:   	      $udom.'/'.$uname.'/'.$filename;
                   13325:         }
1.882     albertel 13326:     } elsif ($file =~ m-^/adm/-) {
                   13327: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13328:     } else {
                   13329:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13330:         $file=~s:^/(res|priv)/:/:;
                   13331:         my $space=$1;
1.590     banghart 13332:         if ( !( $file =~ m:^/:) ) {
                   13333:             $location = $dir. '/'.$file;
                   13334:         } else {
1.1142    raeburn  13335:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13336:         }
1.59      albertel 13337:     }
1.590     banghart 13338:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13339:     while ($location=~m{/\.\./}) {
                   13340: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13341: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13342: 	} else {
                   13343: 	    $location=~ s{/\.\./}{/}g;
                   13344: 	}
                   13345:     } #remove dir/..
1.590     banghart 13346:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13347:     return $location;
1.46      www      13348: }
1.36      albertel 13349: 
1.46      www      13350: sub hreflocation {
                   13351:     my ($dir,$file)=@_;
1.980     raeburn  13352:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13353: 	$file=filelocation($dir,$file);
1.700     albertel 13354:     } elsif ($file=~m-^/adm/-) {
                   13355: 	$file=~s-^/adm/wrapper/-/-;
                   13356: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13357:     }
                   13358:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13359: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13360:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13361: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13362: 	        {/uploaded/$1/$2/}x;
1.46      www      13363:     }
1.913     albertel 13364:     if ($file=~ m{^/userfiles/}) {
                   13365: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13366:     }
1.462     albertel 13367:     return $file;
1.465     albertel 13368: }
                   13369: 
1.1139    www      13370: 
                   13371: 
                   13372: 
                   13373: 
1.465     albertel 13374: sub current_machine_domains {
1.853     albertel 13375:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13376: }
                   13377: 
                   13378: sub machine_domains {
                   13379:     my ($hostname) = @_;
1.465     albertel 13380:     my @domains;
1.838     albertel 13381:     my %hostname = &all_hostnames();
1.465     albertel 13382:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13383: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13384: 	if ($hostname eq $name) {
1.844     albertel 13385: 	    push(@domains,&host_domain($id));
1.465     albertel 13386: 	}
                   13387:     }
                   13388:     return @domains;
                   13389: }
                   13390: 
                   13391: sub current_machine_ids {
1.853     albertel 13392:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13393: }
                   13394: 
                   13395: sub machine_ids {
                   13396:     my ($hostname) = @_;
                   13397:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13398:     my @ids;
1.888     albertel 13399:     my %name_to_host = &all_names();
1.889     albertel 13400:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13401: 	return @{ $name_to_host{$hostname} };
                   13402:     }
                   13403:     return;
1.31      www      13404: }
                   13405: 
1.824     raeburn  13406: sub additional_machine_domains {
                   13407:     my @domains;
1.1172.2.96  raeburn  13408:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13409:     while( my $line = <$fh>) {
                   13410:         $line =~ s/\s//g;
                   13411:         push(@domains,$line);
                   13412:     }
                   13413:     return @domains;
                   13414: }
                   13415: 
                   13416: sub default_login_domain {
                   13417:     my $domain = $perlvar{'lonDefDomain'};
                   13418:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13419:     foreach my $posdom (&current_machine_domains(),
                   13420:                         &additional_machine_domains()) {
                   13421:         if (lc($posdom) eq lc($testdomain)) {
                   13422:             $domain=$posdom;
                   13423:             last;
                   13424:         }
                   13425:     }
                   13426:     return $domain;
                   13427: }
                   13428: 
1.1172.2.106  raeburn  13429: sub shared_institution {
                   13430:     my ($dom) = @_;
                   13431:     my $same_intdom;
                   13432:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13433:     if ($hostintdom ne '') {
                   13434:         my %iphost = &get_iphost();
                   13435:         my $primary_id = &domain($dom,'primary');
                   13436:         my $primary_ip = &get_host_ip($primary_id);
                   13437:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13438:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13439:                 my $intdom = &internet_dom($id);
                   13440:                 if ($intdom eq $hostintdom) {
                   13441:                     $same_intdom = 1;
                   13442:                     last;
                   13443:                 }
                   13444:             }
                   13445:         }
                   13446:     }
                   13447:     return $same_intdom;
                   13448: }
                   13449: 
1.1172.2.118.  .3(raebu 13450:20): sub uses_sts {
                   13451:20):     my ($ignore_cache) = @_;
                   13452:20):     my $lonhost = $perlvar{'lonHostID'};
                   13453:20):     my $hostname = &hostname($lonhost);
                   13454:20):     my $sts_on;
                   13455:20):     if ($protocol{$lonhost} eq 'https') {
                   13456:20):         my $cachetime = 12*3600;
                   13457:20):         if (!$ignore_cache) {
                   13458:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13459:20):             if (defined($cached)) {
                   13460:20):                 return $sts_on;
                   13461:20):             }
                   13462:20):         }
          .4(raebu 13463:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13464:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13465:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13466:20):         my $response=$ua->request($request);
          .3(raebu 13467:20):         if ($response->is_success) {
                   13468:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13469:20):             if ($has_sts eq '') {
                   13470:20):                 $sts_on = 0;
                   13471:20):             } else {
                   13472:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13473:20):                     my $maxage = $1;
                   13474:20):                     if ($maxage) {
                   13475:20):                         $sts_on = 1;
                   13476:20):                     } else {
                   13477:20):                         $sts_on = 0;
                   13478:20):                     }
                   13479:20):                 } else {
                   13480:20):                     $sts_on = 0;
                   13481:20):                 }
                   13482:20):             }
                   13483:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13484:20):         }
                   13485:20):     }
                   13486:20):     return;
                   13487:20): }
                   13488:20): 
1.31      www      13489: # ------------------------------------------------------------- Declutters URLs
                   13490: 
                   13491: sub declutter {
                   13492:     my $thisfn=shift;
1.569     albertel 13493:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13494:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13495:         $thisfn=~s{^/home/httpd/html}{};
                   13496:     }
1.31      www      13497:     $thisfn=~s/^\///;
1.697     albertel 13498:     $thisfn=~s|^adm/wrapper/||;
                   13499:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13500:     $thisfn=~s/^res\///;
1.1172    bisitz   13501:     $thisfn=~s/^priv\///;
1.1032    raeburn  13502:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13503:         $thisfn=~s/\?.+$//;
                   13504:     }
1.268     www      13505:     return $thisfn;
                   13506: }
                   13507: 
                   13508: # ------------------------------------------------------------- Clutter up URLs
                   13509: 
                   13510: sub clutter {
                   13511:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13512:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13513: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13514:        $thisfn='/res'.$thisfn; 
                   13515:     }
1.1031    raeburn  13516:     if ($thisfn !~m|^/adm|) {
                   13517: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13518: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13519: 	} else {
                   13520: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13521: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13522: 	    if ($embstyle eq 'ssi'
                   13523: 		|| ($embstyle eq 'hdn')
                   13524: 		|| ($embstyle eq 'rat')
                   13525: 		|| ($embstyle eq 'prv')
                   13526: 		|| ($embstyle eq 'ign')) {
                   13527: 		#do nothing with these
                   13528: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13529: 		|| ($embstyle eq 'emb')
                   13530: 		|| ($embstyle eq 'wrp')) {
                   13531: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13532: 	    } elsif ($embstyle eq 'unk'
                   13533: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13534: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13535: 	    } else {
1.718     www      13536: #		&logthis("Got a blank emb style");
1.695     albertel 13537: 	    }
1.694     albertel 13538: 	}
1.1172.2.118.  .1(raebu 13539:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13540:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13541:     }
1.31      www      13542:     return $thisfn;
1.12      www      13543: }
                   13544: 
1.787     albertel 13545: sub clutter_with_no_wrapper {
                   13546:     my $uri = &clutter(shift);
                   13547:     if ($uri =~ m-^/adm/-) {
                   13548: 	$uri =~ s-^/adm/wrapper/-/-;
                   13549: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13550:     }
                   13551:     return $uri;
                   13552: }
                   13553: 
1.557     albertel 13554: sub freeze_escape {
                   13555:     my ($value)=@_;
                   13556:     if (ref($value)) {
                   13557: 	$value=&nfreeze($value);
                   13558: 	return '__FROZEN__'.&escape($value);
                   13559:     }
                   13560:     return &escape($value);
                   13561: }
                   13562: 
1.11      www      13563: 
1.557     albertel 13564: sub thaw_unescape {
                   13565:     my ($value)=@_;
                   13566:     if ($value =~ /^__FROZEN__/) {
                   13567: 	substr($value,0,10,undef);
                   13568: 	$value=&unescape($value);
                   13569: 	return &thaw($value);
                   13570:     }
                   13571:     return &unescape($value);
                   13572: }
                   13573: 
1.436     albertel 13574: sub correct_line_ends {
                   13575:     my ($result)=@_;
                   13576:     $$result =~s/\r\n/\n/mg;
                   13577:     $$result =~s/\r/\n/mg;
1.415     albertel 13578: }
1.1       albertel 13579: # ================================================================ Main Program
                   13580: 
1.184     www      13581: sub goodbye {
1.204     albertel 13582:    &logthis("Starting Shut down");
1.443     albertel 13583: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13584:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13585: #converted
1.599     albertel 13586: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13587:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13588: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13589: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13590: #1.1 only
1.870     albertel 13591: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13592: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13593: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13594: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13595:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13596:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13597:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13598:    &flushcourselogs();
                   13599:    &logthis("Shutting down");
                   13600: }
                   13601: 
1.852     albertel 13602: sub get_dns {
1.1172.2.17  raeburn  13603:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13604:     if (!$ignore_cache) {
                   13605: 	my ($content,$cached)=
                   13606: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13607: 	if ($cached) {
1.1172.2.17  raeburn  13608: 	    &$func($content,$hashref);
1.869     albertel 13609: 	    return;
                   13610: 	}
                   13611:     }
                   13612: 
                   13613:     my %alldns;
1.1172.2.96  raeburn  13614:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13615:         foreach my $dns (<$config>) {
                   13616: 	    next if ($dns !~ /^\^(\S*)/x);
                   13617:             my $line = $1;
                   13618:             my ($host,$protocol) = split(/:/,$line);
                   13619:             if ($protocol ne 'https') {
                   13620:                 $protocol = 'http';
                   13621:             }
                   13622: 	    $alldns{$host} = $protocol;
1.979     raeburn  13623:         }
1.1172.2.96  raeburn  13624:         close($config);
1.869     albertel 13625:     }
                   13626:     while (%alldns) {
1.1172.2.52  raeburn  13627: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13628: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13629:         $ua->timeout(30);
1.979     raeburn  13630: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13631: 	my $response=$ua->request($request);
1.979     raeburn  13632:         delete($alldns{$dns});
1.852     albertel 13633: 	next if ($response->is_error());
                   13634: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13635:         unless ($nocache) {
1.1172.2.23  raeburn  13636: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13637:         }
                   13638: 	&$func(\@content,$hashref);
1.869     albertel 13639: 	return;
1.852     albertel 13640:     }
1.871     albertel 13641:     my $which = (split('/',$url))[3];
                   13642:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13643:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13644:         my @content = <$config>;
                   13645:         &$func(\@content,$hashref);
                   13646:     }
1.1172.2.17  raeburn  13647:     return;
                   13648: }
                   13649: 
                   13650: # ------------------------------------------------------Get DNS checksums file
                   13651: sub parse_dns_checksums_tab {
                   13652:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13653:     my $lonhost = $perlvar{'lonHostID'};
                   13654:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13655:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13656:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13657:     my $webconfdir = '/etc/httpd/conf';
                   13658:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13659:         $webconfdir = '/etc/apache2';
                   13660:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13661:         if ($1 >= 10) {
                   13662:             $webconfdir = '/etc/apache2';
                   13663:         }
                   13664:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13665:         if ($1 >= 10.0) {
                   13666:             $webconfdir = '/etc/apache2';
                   13667:         }
                   13668:     }
1.1172.2.17  raeburn  13669:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13670:     my (%chksum,%revnum);
                   13671:     if (ref($lines) eq 'ARRAY') {
                   13672:         chomp(@{$lines});
1.1172.2.34  raeburn  13673:         my $version = shift(@{$lines});
                   13674:         if ($version eq $release) {
1.1172.2.17  raeburn  13675:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13676:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13677:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13678:                     if ($webconfdir eq '/etc/apache2') {
                   13679:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13680:                     }
                   13681:                 }
1.1172.2.34  raeburn  13682:                 $chksum{$file} = $shasum;
                   13683:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13684:             }
                   13685:             if (ref($hashref) eq 'HASH') {
                   13686:                 %{$hashref} = (
                   13687:                                 sums     => \%chksum,
                   13688:                                 versions => \%revnum,
                   13689:                               );
                   13690:             }
                   13691:         }
                   13692:     }
1.869     albertel 13693:     return;
1.852     albertel 13694: }
1.1172.2.17  raeburn  13695: 
                   13696: sub fetch_dns_checksums {
                   13697:     my %checksums;
1.1172.2.34  raeburn  13698:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13699:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13700:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13701:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13702:              \%checksums);
                   13703:     return \%checksums;
                   13704: }
                   13705: 
1.327     albertel 13706: # ------------------------------------------------------------ Read domain file
                   13707: {
1.852     albertel 13708:     my $loaded;
1.846     albertel 13709:     my %domain;
                   13710: 
1.852     albertel 13711:     sub parse_domain_tab {
                   13712: 	my ($lines) = @_;
                   13713: 	foreach my $line (@$lines) {
                   13714: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13715: 
1.846     albertel 13716: 	    chomp($line);
1.852     albertel 13717: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13718: 	    my %this_domain;
                   13719: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13720: 			       'lang_def', 'city', 'longi', 'lati',
                   13721: 			       'primary') {
                   13722: 		$this_domain{$field} = shift(@elements);
                   13723: 	    }
                   13724: 	    $domain{$name} = \%this_domain;
1.852     albertel 13725: 	}
                   13726:     }
1.864     albertel 13727: 
                   13728:     sub reset_domain_info {
                   13729: 	undef($loaded);
                   13730: 	undef(%domain);
                   13731:     }
                   13732: 
1.852     albertel 13733:     sub load_domain_tab {
1.1172.2.70  raeburn  13734: 	my ($ignore_cache,$nocache) = @_;
                   13735: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13736: 	my $fh;
1.1172.2.96  raeburn  13737: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13738: 	    my @lines = <$fh>;
                   13739: 	    &parse_domain_tab(\@lines);
1.448     albertel 13740: 	}
1.852     albertel 13741: 	close($fh);
                   13742: 	$loaded = 1;
1.327     albertel 13743:     }
1.846     albertel 13744: 
                   13745:     sub domain {
1.852     albertel 13746: 	&load_domain_tab() if (!$loaded);
                   13747: 
1.846     albertel 13748: 	my ($name,$what) = @_;
                   13749: 	return if ( !exists($domain{$name}) );
                   13750: 
                   13751: 	if (!$what) {
                   13752: 	    return $domain{$name}{'description'};
                   13753: 	}
                   13754: 	return $domain{$name}{$what};
                   13755:     }
1.974     raeburn  13756: 
                   13757:     sub domain_info {
                   13758:         &load_domain_tab() if (!$loaded);
                   13759:         return %domain;
                   13760:     }
                   13761: 
1.327     albertel 13762: }
                   13763: 
                   13764: 
1.1       albertel 13765: # ------------------------------------------------------------- Read hosts file
                   13766: {
1.838     albertel 13767:     my %hostname;
1.844     albertel 13768:     my %hostdom;
1.845     albertel 13769:     my %libserv;
1.852     albertel 13770:     my $loaded;
1.888     albertel 13771:     my %name_to_host;
1.1074    raeburn  13772:     my %internetdom;
1.1107    raeburn  13773:     my %LC_dns_serv;
1.852     albertel 13774: 
                   13775:     sub parse_hosts_tab {
                   13776: 	my ($file) = @_;
                   13777: 	foreach my $configline (@$file) {
                   13778: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13779:             chomp($configline);
                   13780: 	    if ($configline =~ /^\^/) {
                   13781:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13782:                     $LC_dns_serv{$1} = 1;
                   13783:                 }
                   13784:                 next;
                   13785:             }
1.1074    raeburn  13786: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13787: 	    $name=~s/\s//g;
                   13788: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13789:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13790:                     my $curr = $hostname{$id};
                   13791:                     my $skip;
                   13792:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13793:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13794:                             $skip = 1;
                   13795:                         } else {
                   13796:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13797:                         }
                   13798:                     }
                   13799:                     unless ($skip) {
                   13800:                         push(@{$name_to_host{$name}},$id);
                   13801:                     }
                   13802:                 } else {
                   13803:                     push(@{$name_to_host{$name}},$id);
                   13804:                 }
1.852     albertel 13805: 		$hostname{$id}=$name;
                   13806: 		$hostdom{$id}=$domain;
                   13807: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13808:                 if (defined($protocol)) {
                   13809:                     if ($protocol eq 'https') {
                   13810:                         $protocol{$id} = $protocol;
                   13811:                     } else {
                   13812:                         $protocol{$id} = 'http'; 
                   13813:                     }
1.968     raeburn  13814:                 } else {
1.969     raeburn  13815:                     $protocol{$id} = 'http';
1.968     raeburn  13816:                 }
1.1074    raeburn  13817:                 if (defined($intdom)) {
                   13818:                     $internetdom{$id} = $intdom;
                   13819:                 }
1.852     albertel 13820: 	    }
                   13821: 	}
                   13822:     }
1.864     albertel 13823:     
                   13824:     sub reset_hosts_info {
1.897     albertel 13825: 	&purge_remembered();
1.864     albertel 13826: 	&reset_domain_info();
                   13827: 	&reset_hosts_ip_info();
1.892     albertel 13828: 	undef(%name_to_host);
1.864     albertel 13829: 	undef(%hostname);
                   13830: 	undef(%hostdom);
                   13831: 	undef(%libserv);
                   13832: 	undef($loaded);
                   13833:     }
1.1       albertel 13834: 
1.852     albertel 13835:     sub load_hosts_tab {
1.1172.2.70  raeburn  13836: 	my ($ignore_cache,$nocache) = @_;
                   13837: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13838: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13839: 	my @config = <$config>;
                   13840: 	&parse_hosts_tab(\@config);
                   13841: 	close($config);
                   13842: 	$loaded=1;
1.1       albertel 13843:     }
1.852     albertel 13844: 
1.838     albertel 13845:     sub hostname {
1.852     albertel 13846: 	&load_hosts_tab() if (!$loaded);
                   13847: 
1.838     albertel 13848: 	my ($lonid) = @_;
                   13849: 	return $hostname{$lonid};
                   13850:     }
1.845     albertel 13851: 
1.838     albertel 13852:     sub all_hostnames {
1.852     albertel 13853: 	&load_hosts_tab() if (!$loaded);
                   13854: 
1.838     albertel 13855: 	return %hostname;
                   13856:     }
1.845     albertel 13857: 
1.888     albertel 13858:     sub all_names {
1.1172.2.70  raeburn  13859:         my ($ignore_cache,$nocache) = @_;
                   13860: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13861: 
                   13862: 	return %name_to_host;
                   13863:     }
                   13864: 
1.974     raeburn  13865:     sub all_host_domain {
                   13866:         &load_hosts_tab() if (!$loaded);
                   13867:         return %hostdom;
                   13868:     }
                   13869: 
1.845     albertel 13870:     sub is_library {
1.852     albertel 13871: 	&load_hosts_tab() if (!$loaded);
                   13872: 
1.845     albertel 13873: 	return exists($libserv{$_[0]});
                   13874:     }
                   13875: 
                   13876:     sub all_library {
1.852     albertel 13877: 	&load_hosts_tab() if (!$loaded);
                   13878: 
1.845     albertel 13879: 	return %libserv;
                   13880:     }
                   13881: 
1.1062    droeschl 13882:     sub unique_library {
                   13883: 	#2x reverse removes all hostnames that appear more than once
                   13884:         my %unique = reverse &all_library();
                   13885:         return reverse %unique;
                   13886:     }
                   13887: 
1.841     albertel 13888:     sub get_servers {
1.852     albertel 13889: 	&load_hosts_tab() if (!$loaded);
                   13890: 
1.841     albertel 13891: 	my ($domain,$type) = @_;
                   13892: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13893: 	                                          : %hostname;
                   13894: 	my %result;
1.842     albertel 13895: 	if (ref($domain) eq 'ARRAY') {
                   13896: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13897: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13898: 		    $result{$host} = $hostname;
                   13899: 		}
                   13900: 	    }
                   13901: 	} else {
                   13902: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13903: 		if ($hostdom{$host} eq $domain) {
                   13904: 		    $result{$host} = $hostname;
                   13905: 		}
1.841     albertel 13906: 	    }
                   13907: 	}
                   13908: 	return %result;
                   13909:     }
1.845     albertel 13910: 
1.1062    droeschl 13911:     sub get_unique_servers {
                   13912:         my %unique = reverse &get_servers(@_);
                   13913: 	return reverse %unique;
                   13914:     }
                   13915: 
1.844     albertel 13916:     sub host_domain {
1.852     albertel 13917: 	&load_hosts_tab() if (!$loaded);
                   13918: 
1.844     albertel 13919: 	my ($lonid) = @_;
                   13920: 	return $hostdom{$lonid};
                   13921:     }
                   13922: 
1.841     albertel 13923:     sub all_domains {
1.852     albertel 13924: 	&load_hosts_tab() if (!$loaded);
                   13925: 
1.841     albertel 13926: 	my %seen;
                   13927: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13928: 	return @uniq;
                   13929:     }
1.1074    raeburn  13930: 
                   13931:     sub internet_dom {
                   13932:         &load_hosts_tab() if (!$loaded);
                   13933: 
                   13934:         my ($lonid) = @_;
                   13935:         return $internetdom{$lonid};
                   13936:     }
1.1107    raeburn  13937: 
                   13938:     sub is_LC_dns {
                   13939:         &load_hosts_tab() if (!$loaded);
                   13940: 
                   13941:         my ($hostname) = @_;
                   13942:         return exists($LC_dns_serv{$hostname});
                   13943:     }
                   13944: 
1.1       albertel 13945: }
                   13946: 
1.847     albertel 13947: { 
                   13948:     my %iphost;
1.856     albertel 13949:     my %name_to_ip;
                   13950:     my %lonid_to_ip;
1.869     albertel 13951: 
1.847     albertel 13952:     sub get_hosts_from_ip {
                   13953: 	my ($ip) = @_;
                   13954: 	my %iphosts = &get_iphost();
                   13955: 	if (ref($iphosts{$ip})) {
                   13956: 	    return @{$iphosts{$ip}};
                   13957: 	}
                   13958: 	return;
1.839     albertel 13959:     }
1.864     albertel 13960:     
                   13961:     sub reset_hosts_ip_info {
                   13962: 	undef(%iphost);
                   13963: 	undef(%name_to_ip);
                   13964: 	undef(%lonid_to_ip);
                   13965:     }
1.856     albertel 13966: 
                   13967:     sub get_host_ip {
                   13968: 	my ($lonid) = @_;
                   13969: 	if (exists($lonid_to_ip{$lonid})) {
                   13970: 	    return $lonid_to_ip{$lonid};
                   13971: 	}
                   13972: 	my $name=&hostname($lonid);
                   13973:    	my $ip = gethostbyname($name);
                   13974: 	return if (!$ip || length($ip) ne 4);
                   13975: 	$ip=inet_ntoa($ip);
                   13976: 	$name_to_ip{$name}   = $ip;
                   13977: 	$lonid_to_ip{$lonid} = $ip;
                   13978: 	return $ip;
                   13979:     }
1.847     albertel 13980:     
                   13981:     sub get_iphost {
1.1172.2.70  raeburn  13982: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13983: 
1.869     albertel 13984: 	if (!$ignore_cache) {
                   13985: 	    if (%iphost) {
                   13986: 		return %iphost;
                   13987: 	    }
                   13988: 	    my ($ip_info,$cached)=
                   13989: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13990: 	    if ($cached) {
                   13991: 		%iphost      = %{$ip_info->[0]};
                   13992: 		%name_to_ip  = %{$ip_info->[1]};
                   13993: 		%lonid_to_ip = %{$ip_info->[2]};
                   13994: 		return %iphost;
                   13995: 	    }
                   13996: 	}
1.894     albertel 13997: 
                   13998: 	# get yesterday's info for fallback
                   13999: 	my %old_name_to_ip;
                   14000: 	my ($ip_info,$cached)=
                   14001: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14002: 	if ($cached) {
                   14003: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14004: 	}
                   14005: 
1.1172.2.70  raeburn  14006: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14007: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14008: 	    my $ip;
                   14009: 	    if (!exists($name_to_ip{$name})) {
                   14010: 		$ip = gethostbyname($name);
                   14011: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14012: 		    if (defined($old_name_to_ip{$name})) {
                   14013: 			$ip = $old_name_to_ip{$name};
                   14014: 			&logthis("Can't find $name defaulting to old $ip");
                   14015: 		    } else {
                   14016: 			&logthis("Name $name no IP found");
                   14017: 			next;
                   14018: 		    }
                   14019: 		} else {
                   14020: 		    $ip=inet_ntoa($ip);
1.847     albertel 14021: 		}
                   14022: 		$name_to_ip{$name} = $ip;
                   14023: 	    } else {
                   14024: 		$ip = $name_to_ip{$name};
1.653     albertel 14025: 	    }
1.888     albertel 14026: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14027: 		$lonid_to_ip{$id} = $ip;
                   14028: 	    }
                   14029: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14030: 	}
1.1172.2.70  raeburn  14031:         unless ($nocache) {
                   14032: 	    &do_cache_new('iphost','iphost',
                   14033: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14034: 		          48*60*60);
                   14035:         }
1.869     albertel 14036: 
1.847     albertel 14037: 	return %iphost;
1.598     albertel 14038:     }
                   14039: 
1.992     raeburn  14040:     #
                   14041:     #  Given a DNS returns the loncapa host name for that DNS 
                   14042:     # 
                   14043:     sub host_from_dns {
                   14044:         my ($dns) = @_;
                   14045:         my @hosts;
                   14046:         my $ip;
                   14047: 
1.993     raeburn  14048:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14049:             $ip = $name_to_ip{$dns};
                   14050:         }
                   14051:         if (!$ip) {
                   14052:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14053:             if (length($ip) == 4) { 
                   14054: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14055:             }
                   14056:         }
                   14057:         if ($ip) {
                   14058: 	    @hosts = get_hosts_from_ip($ip);
                   14059: 	    return $hosts[0];
                   14060:         }
                   14061:         return undef;
1.986     foxr     14062:     }
1.992     raeburn  14063: 
1.1074    raeburn  14064:     sub get_internet_names {
                   14065:         my ($lonid) = @_;
                   14066:         return if ($lonid eq '');
                   14067:         my ($idnref,$cached)=
                   14068:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14069:         if ($cached) {
                   14070:             return $idnref;
                   14071:         }
                   14072:         my $ip = &get_host_ip($lonid);
                   14073:         my @hosts = &get_hosts_from_ip($ip);
                   14074:         my %iphost = &get_iphost();
                   14075:         my (@idns,%seen);
                   14076:         foreach my $id (@hosts) {
                   14077:             my $dom = &host_domain($id);
                   14078:             my $prim_id = &domain($dom,'primary');
                   14079:             my $prim_ip = &get_host_ip($prim_id);
                   14080:             next if ($seen{$prim_ip});
                   14081:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14082:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14083:                     my $intdom = &internet_dom($id);
                   14084:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14085:                         push(@idns,$intdom);
                   14086:                     }
                   14087:                 }
                   14088:             }
                   14089:             $seen{$prim_ip} = 1;
                   14090:         }
1.1172.2.23  raeburn  14091:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14092:     }
                   14093: 
1.986     foxr     14094: }
                   14095: 
1.1079    raeburn  14096: sub all_loncaparevs {
1.1172.2.39  raeburn  14097:     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  14098: }
                   14099: 
1.1172.2.27  raeburn  14100: # ------------------------------------------------------- Read loncaparev table
                   14101: {
                   14102:     sub load_loncaparevs {
                   14103:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14104:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14105:                 while (my $configline=<$config>) {
                   14106:                     chomp($configline);
                   14107:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14108:                     $loncaparevs{$hostid}=$loncaparev;
                   14109:                 }
                   14110:                 close($config);
                   14111:             }
                   14112:         }
                   14113:     }
                   14114: }
                   14115: 
                   14116: # ----------------------------------------------------- Read serverhostID table
                   14117: {
                   14118:     sub load_serverhomeIDs {
                   14119:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14120:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14121:                 while (my $configline=<$config>) {
                   14122:                     chomp($configline);
                   14123:                     my ($name,$id)=split(/:/,$configline);
                   14124:                     $serverhomeIDs{$name}=$id;
                   14125:                 }
                   14126:                 close($config);
                   14127:             }
                   14128:         }
                   14129:     }
                   14130: }
                   14131: 
                   14132: 
1.862     albertel 14133: BEGIN {
                   14134: 
                   14135: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14136:     unless ($readit) {
                   14137: {
                   14138:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14139:     %perlvar = (%perlvar,%{$configvars});
                   14140: }
                   14141: 
                   14142: 
1.1       albertel 14143: # ------------------------------------------------------ Read spare server file
                   14144: {
1.1172.2.96  raeburn  14145:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14146: 
                   14147:     while (my $configline=<$config>) {
                   14148:        chomp($configline);
1.284     matthew  14149:        if ($configline) {
1.784     albertel 14150: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14151: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14152: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14153:        }
                   14154:     }
1.448     albertel 14155:     close($config);
1.1       albertel 14156: }
1.11      www      14157: # ------------------------------------------------------------ Read permissions
                   14158: {
1.1172.2.96  raeburn  14159:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14160: 
                   14161:     while (my $configline=<$config>) {
1.448     albertel 14162: 	chomp($configline);
                   14163: 	if ($configline) {
                   14164: 	    my ($role,$perm)=split(/ /,$configline);
                   14165: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14166: 	}
1.11      www      14167:     }
1.448     albertel 14168:     close($config);
1.11      www      14169: }
                   14170: 
                   14171: # -------------------------------------------- Read plain texts for permissions
                   14172: {
1.1172.2.96  raeburn  14173:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14174: 
                   14175:     while (my $configline=<$config>) {
1.448     albertel 14176: 	chomp($configline);
                   14177: 	if ($configline) {
1.742     raeburn  14178: 	    my ($short,@plain)=split(/:/,$configline);
                   14179:             %{$prp{$short}} = ();
                   14180: 	    if (@plain > 0) {
                   14181:                 $prp{$short}{'std'} = $plain[0];
                   14182:                 for (my $i=1; $i<@plain; $i++) {
                   14183:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14184:                 }
                   14185:             }
1.448     albertel 14186: 	}
1.135     www      14187:     }
1.448     albertel 14188:     close($config);
1.135     www      14189: }
                   14190: 
                   14191: # ---------------------------------------------------------- Read package table
                   14192: {
1.1172.2.96  raeburn  14193:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14194: 
                   14195:     while (my $configline=<$config>) {
1.483     albertel 14196: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14197: 	chomp($configline);
                   14198: 	my ($short,$plain)=split(/:/,$configline);
                   14199: 	my ($pack,$name)=split(/\&/,$short);
                   14200: 	if ($plain ne '') {
                   14201: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14202: 	    $packagetab{$short}=$plain; 
                   14203: 	}
1.11      www      14204:     }
1.448     albertel 14205:     close($config);
1.329     matthew  14206: }
                   14207: 
1.1172.2.27  raeburn  14208: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14209: 
1.1172.2.27  raeburn  14210: &load_loncaparevs();
                   14211: 
                   14212: # ------------------------------------------------------- Read serverhostID table
                   14213: 
                   14214: &load_serverhomeIDs();
1.1074    raeburn  14215: 
1.1172.2.27  raeburn  14216: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14217: {
                   14218:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14219:     if (-e $file) {
                   14220:         my $parser = HTML::LCParser->new($file);
                   14221:         while (my $token = $parser->get_token()) {
                   14222:             if ($token->[0] eq 'S') {
                   14223:                 my $item = $token->[1];
                   14224:                 my $name = $token->[2]{'name'};
                   14225:                 my $value = $token->[2]{'value'};
                   14226:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14227:                     my $release = $parser->get_text();
                   14228:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14229:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14230:                 }
                   14231:             }
                   14232:         }
                   14233:     }
1.1073    raeburn  14234: }
                   14235: 
1.1138    raeburn  14236: # ---------------------------------------------------------- Read managers table
                   14237: {
                   14238:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14239:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14240:             while (my $configline=<$config>) {
                   14241:                 chomp($configline);
                   14242:                 next if ($configline =~ /^\#/);
                   14243:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14244:                     $managerstab{$configline} = 1;
                   14245:                 }
                   14246:             }
                   14247:             close($config);
                   14248:         }
                   14249:     }
                   14250: }
                   14251: 
1.329     matthew  14252: # ------------- set up temporary directory
                   14253: {
1.1117    foxr     14254:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14255: 
1.11      www      14256: }
                   14257: 
1.1172.2.104  raeburn  14258: # ------------- set default texengine (domain default overrides this)
                   14259: {
                   14260:     $deftex = LONCAPA::texengine();
                   14261: }
                   14262: 
1.1172.2.114  raeburn  14263: # ------------- set default minimum length for passwords for internal auth users
                   14264: {
                   14265:     $passwdmin = LONCAPA::passwd_min();
                   14266: }
                   14267: 
1.794     albertel 14268: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14269: 				'compress_threshold'=> 20_000,
                   14270:  			        });
1.185     www      14271: 
1.281     www      14272: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14273: $dumpcount=0;
1.958     www      14274: $locknum=0;
1.22      www      14275: 
1.163     harris41 14276: &logtouch();
1.672     albertel 14277: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14278: $readit=1;
1.564     albertel 14279:     {
                   14280: 	use integer;
                   14281: 	my $test=(2**32)+1;
1.568     albertel 14282: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14283: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14284:     }
1.195     www      14285: }
1.1       albertel 14286: }
1.179     www      14287: 
1.1       albertel 14288: 1;
1.191     harris41 14289: __END__
                   14290: 
1.243     albertel 14291: =pod
                   14292: 
1.191     harris41 14293: =head1 NAME
                   14294: 
1.243     albertel 14295: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14296: 
                   14297: =head1 SYNOPSIS
                   14298: 
1.243     albertel 14299: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14300: 
                   14301:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14302: 
1.243     albertel 14303: Common parameters:
                   14304: 
                   14305: =over 4
                   14306: 
                   14307: =item *
                   14308: 
                   14309: $uname : an internal username (if $cname expecting a course Id specifically)
                   14310: 
                   14311: =item *
                   14312: 
                   14313: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14314: 
                   14315: =item *
                   14316: 
                   14317: $symb : a resource instance identifier
                   14318: 
                   14319: =item *
                   14320: 
                   14321: $namespace : the name of a .db file that contains the data needed or
                   14322: being set.
                   14323: 
                   14324: =back
                   14325: 
1.394     bowersj2 14326: =head1 OVERVIEW
1.191     harris41 14327: 
1.394     bowersj2 14328: lonnet provides subroutines which interact with the
                   14329: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14330: about classes, users, and resources.
1.243     albertel 14331: 
                   14332: For many of these objects you can also use this to store data about
                   14333: them or modify them in various ways.
1.191     harris41 14334: 
1.394     bowersj2 14335: =head2 Symbs
1.191     harris41 14336: 
1.394     bowersj2 14337: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14338: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14339: map, the resource number of the resource in the map, and the URL of
                   14340: the resource itself. The latter is somewhat redundant, but might help
                   14341: if maps change.
                   14342: 
                   14343: An example is
                   14344: 
                   14345:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14346: 
                   14347: The respective map entry is
                   14348: 
                   14349:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14350:   title="Problem 2">
                   14351:  </resource>
                   14352: 
                   14353: Symbs are used by the random number generator, as well as to store and
                   14354: restore data specific to a certain instance of for example a problem.
                   14355: 
                   14356: =head2 Storing And Retrieving Data
                   14357: 
                   14358: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14359: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14360: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14361: is is the non-critical message twin of cstore. These functions are for
                   14362: handlers to store a perl hash to a user's permanent data space in an
                   14363: easy manner, and to retrieve it again on another call. It is expected
                   14364: that a handler would use this once at the beginning to retrieve data,
                   14365: and then again once at the end to send only the new data back.
                   14366: 
                   14367: The data is stored in the user's data directory on the user's
                   14368: homeserver under the ID of the course.
                   14369: 
                   14370: The hash that is returned by restore will have all of the previous
                   14371: value for all of the elements of the hash.
                   14372: 
                   14373: Example:
                   14374: 
                   14375:  #creating a hash
                   14376:  my %hash;
                   14377:  $hash{'foo'}='bar';
                   14378: 
                   14379:  #storing it
                   14380:  &Apache::lonnet::cstore(\%hash);
                   14381: 
                   14382:  #changing a value
                   14383:  $hash{'foo'}='notbar';
                   14384: 
                   14385:  #adding a new value
                   14386:  $hash{'bar'}='foo';
                   14387:  &Apache::lonnet::cstore(\%hash);
                   14388: 
                   14389:  #retrieving the hash
                   14390:  my %history=&Apache::lonnet::restore();
                   14391: 
                   14392:  #print the hash
                   14393:  foreach my $key (sort(keys(%history))) {
                   14394:    print("\%history{$key} = $history{$key}");
                   14395:  }
                   14396: 
                   14397: Will print out:
1.191     harris41 14398: 
1.394     bowersj2 14399:  %history{1:foo} = bar
                   14400:  %history{1:keys} = foo:timestamp
                   14401:  %history{1:timestamp} = 990455579
                   14402:  %history{2:bar} = foo
                   14403:  %history{2:foo} = notbar
                   14404:  %history{2:keys} = foo:bar:timestamp
                   14405:  %history{2:timestamp} = 990455580
                   14406:  %history{bar} = foo
                   14407:  %history{foo} = notbar
                   14408:  %history{timestamp} = 990455580
                   14409:  %history{version} = 2
                   14410: 
                   14411: Note that the special hash entries C<keys>, C<version> and
                   14412: C<timestamp> were added to the hash. C<version> will be equal to the
                   14413: total number of versions of the data that have been stored. The
                   14414: C<timestamp> attribute will be the UNIX time the hash was
                   14415: stored. C<keys> is available in every historical section to list which
                   14416: keys were added or changed at a specific historical revision of a
                   14417: hash.
                   14418: 
                   14419: B<Warning>: do not store the hash that restore returns directly. This
                   14420: will cause a mess since it will restore the historical keys as if the
                   14421: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14422: 
1.394     bowersj2 14423: Calling convention:
1.191     harris41 14424: 
1.1172.2.27  raeburn  14425:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14426:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14427: 
1.394     bowersj2 14428: For more detailed information, see lonnet specific documentation.
1.191     harris41 14429: 
1.394     bowersj2 14430: =head1 RETURN MESSAGES
1.191     harris41 14431: 
1.394     bowersj2 14432: =over 4
1.191     harris41 14433: 
1.394     bowersj2 14434: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14435: 
1.394     bowersj2 14436: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14437: when the connection is brought back up
1.191     harris41 14438: 
1.394     bowersj2 14439: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14440: for later delivery
1.191     harris41 14441: 
1.967     bisitz   14442: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14443: 
1.394     bowersj2 14444: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14445: that was requested
1.191     harris41 14446: 
1.243     albertel 14447: =back
1.191     harris41 14448: 
1.243     albertel 14449: =head1 PUBLIC SUBROUTINES
1.191     harris41 14450: 
1.243     albertel 14451: =head2 Session Environment Functions
1.191     harris41 14452: 
1.243     albertel 14453: =over 4
1.191     harris41 14454: 
1.394     bowersj2 14455: =item * 
                   14456: X<appenv()>
1.949     raeburn  14457: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14458: the user envirnoment file, and will be restored for each access this
1.620     albertel 14459: user makes during this session, also modifies the %env for the current
1.949     raeburn  14460: process. Optional rolesarrayref - if defined contains a reference to an array
                   14461: of roles which are exempt from the restriction on modifying user.role entries 
                   14462: in the user's environment.db and in %env.    
1.191     harris41 14463: 
                   14464: =item *
1.394     bowersj2 14465: X<delenv()>
1.987     raeburn  14466: B<delenv($delthis,$regexp)>: removes all items from the session
                   14467: environment file that begin with $delthis. If the 
                   14468: optional second arg - $regexp - is true, $delthis is treated as a 
                   14469: regular expression, otherwise \Q$delthis\E is used. 
                   14470: The values are also deleted from the current processes %env.
1.191     harris41 14471: 
1.795     albertel 14472: =item * get_env_multiple($name) 
                   14473: 
                   14474: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14475: values may be defined and end up as an array ref.
                   14476: 
                   14477: returns an array of values
                   14478: 
1.243     albertel 14479: =back
                   14480: 
                   14481: =head2 User Information
1.191     harris41 14482: 
1.243     albertel 14483: =over 4
1.191     harris41 14484: 
                   14485: =item *
1.394     bowersj2 14486: X<queryauthenticate()>
                   14487: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14488: authentication scheme
                   14489: 
                   14490: =item *
1.394     bowersj2 14491: X<authenticate()>
1.1073    raeburn  14492: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14493: authenticate user from domain's lib servers (first use the current
                   14494: one). C<$upass> should be the users password.
1.1073    raeburn  14495: $checkdefauth is optional (value is 1 if a check should be made to
                   14496:    authenticate user using default authentication method, and allow
                   14497:    account creation if username does not have account in the domain).
                   14498: $clientcancheckhost is optional (value is 1 if checking whether the
                   14499:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14500: 
                   14501: =item *
1.394     bowersj2 14502: X<homeserver()>
                   14503: B<homeserver($uname,$udom)>: find the server which has
                   14504: the user's directory and files (there must be only one), this caches
                   14505: the answer, and also caches if there is a borken connection.
1.191     harris41 14506: 
                   14507: =item *
1.394     bowersj2 14508: X<idget()>
                   14509: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14510: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14511: username, and only 1 username per ID in a specific domain) (returns
                   14512: hash: id=>name,id=>name)
1.191     harris41 14513: 
                   14514: =item *
1.394     bowersj2 14515: X<idrget()>
                   14516: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14517: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14518: 
                   14519: =item *
1.394     bowersj2 14520: X<idput()>
                   14521: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14522: 
                   14523: =item *
1.394     bowersj2 14524: X<rolesinit()>
1.1169    droeschl 14525: B<rolesinit($udom,$username)>: get user privileges.
                   14526: returns user role, first access and timer interval hashes
1.243     albertel 14527: 
                   14528: =item *
1.1171    droeschl 14529: X<privileged()>
                   14530: B<privileged($username,$domain)>: returns a true if user has a
                   14531: privileged and active role (i.e. su or dc), false otherwise.
                   14532: 
                   14533: =item *
1.551     albertel 14534: X<getsection()>
                   14535: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14536: course $cname, return section name/number or '' for "not in course"
                   14537: and '-1' for "no section"
                   14538: 
                   14539: =item *
1.394     bowersj2 14540: X<userenvironment()>
                   14541: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14542: passed in @what from the requested user's environment, returns a hash
                   14543: 
1.858     raeburn  14544: =item * 
                   14545: X<userlog_query()>
1.859     albertel 14546: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14547: activity.log file. %filters defines filters applied when parsing the
                   14548: log file. These can be start or end timestamps, or the type of action
                   14549: - log to look for Login or Logout events, check for Checkin or
                   14550: Checkout, role for role selection. The response is in the form
                   14551: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14552: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14553: 
1.243     albertel 14554: =back
                   14555: 
                   14556: =head2 User Roles
                   14557: 
                   14558: =over 4
                   14559: 
                   14560: =item *
                   14561: 
1.1172.2.65  raeburn  14562: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14563: returns codes for allowed actions.
                   14564: 
                   14565: The first argument is required, all others are optional.
                   14566: 
                   14567: $priv is the privilege being checked.
                   14568: $uri contains additional information about what is being checked for access (e.g.,
                   14569: URL, course ID etc.).
                   14570: $symb is the unique resource instance identifier in a course; if needed,
                   14571: but not provided, it will be retrieved via a call to &symbread().
                   14572: $role is the role for which a priv is being checked (only used if priv is evb).
                   14573: $clientip is the user's IP address (only used when checking for access to portfolio
                   14574: files).
                   14575: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14576: prevents recursive calls to &allowed.
                   14577: 
1.243     albertel 14578:  F: full access
                   14579:  U,I,K: authentication modes (cxx only)
                   14580:  '': forbidden
                   14581:  1: user needs to choose course
                   14582:  2: browse allowed
1.766     albertel 14583:  A: passphrase authentication needed
1.1172.2.65  raeburn  14584:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14585: 
                   14586: =item *
                   14587: 
1.1172.2.13  raeburn  14588: constructaccess($url,$setpriv) : check for access to construction space URL
                   14589: 
                   14590: See if the owner domain and name in the URL match those in the
                   14591: expected environment.  If so, return three element list
                   14592: ($ownername,$ownerdomain,$ownerhome).
                   14593: 
                   14594: Otherwise return the null string.
                   14595: 
                   14596: If second argument 'setpriv' is true, it assigns the privileges,
                   14597: and returns the same three element list, unless the owner has
                   14598: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14599: in which case the null string is returned.
                   14600: 
                   14601: =item *
                   14602: 
1.1172.2.84  raeburn  14603: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14604: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14605: for system, domain, and course level. $uname and $udom are optional (current
                   14606: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14607: 
                   14608: =item *
                   14609: 
1.988     raeburn  14610: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14611: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14612: $type is Course (default) or Community.
1.988     raeburn  14613: If $forcedefault evaluates to true, text returned will be default 
                   14614: text for $type. Otherwise, if this is a course, the text returned 
                   14615: will be a custom name for the role (if defined in the course's 
                   14616: environment).  If no custom name is defined the default is returned.
                   14617:    
1.832     raeburn  14618: =item *
                   14619: 
1.1172.2.23  raeburn  14620: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14621: All arguments are optional. Returns a hash of a roles, either for
                   14622: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14623: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14624: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14625: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14626: For each key, value is set to colon-separated start and end times for
                   14627: the role.  If no username and domain are specified, will default to
1.934     raeburn  14628: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14629: of role statuses (active, future or previous), roles 
                   14630: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14631: to restrict the list of roles reported. If no array ref is 
                   14632: provided for types, will default to return only active roles.
1.834     albertel 14633: 
1.1172.2.13  raeburn  14634: =item *
                   14635: 
                   14636: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14637: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14638: 
                   14639: Additional optional arguments are: $type (if role checking is to be restricted
                   14640: to certain user status types -- previous (expired roles), active (currently
                   14641: available roles) or future (roles available in the future), and
                   14642: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14643: have active Domain Coordinator role in course's domain or in additional
                   14644: domains (specified in 'Domains to check for privileged users' in course
                   14645: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14646: 
                   14647: =item *
                   14648: 
                   14649: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14650: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14651: $possdomains and $possroles are optional array refs -- to domains to check and
                   14652: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14653: users' roles.db to check for a dc or su role in any domain. This can be
                   14654: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14655: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14656: this then allows &privileged_by_domain() to be used, which caches the identity
                   14657: of privileged users, eliminating the need for repeated calls to &dump().
                   14658: 
                   14659: =item *
                   14660: 
                   14661: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14662: where the outer hash keys are domains specified in the $possdomains array ref,
                   14663: next inner hash keys are privileged roles specified in the $roles array ref,
                   14664: and the innermost hash contains key = value pairs for username:domain = end:start
                   14665: for active or future "privileged" users with that role in that domain. To avoid
                   14666: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14667: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14668: 
1.243     albertel 14669: =back
                   14670: 
                   14671: =head2 User Modification
                   14672: 
                   14673: =over 4
                   14674: 
                   14675: =item *
                   14676: 
1.957     raeburn  14677: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14678: user for the level given by URL.  Optional start and end dates (leave empty
                   14679: string or zero for "no date")
1.191     harris41 14680: 
                   14681: =item *
                   14682: 
1.243     albertel 14683: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14684: change a users, password, possible return values are: ok,
                   14685: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14686: refused
1.191     harris41 14687: 
                   14688: =item *
                   14689: 
1.243     albertel 14690: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14691: 
                   14692: =item *
                   14693: 
1.1058    raeburn  14694: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14695:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14696: 
                   14697: will update user information (firstname,middlename,lastname,generation,
                   14698: permanentemail), and if forceid is true, student/employee ID also.
                   14699: A user's institutional affiliation(s) can also be updated.
                   14700: User information fields will not be overwritten with empty entries 
                   14701: unless the field is included in the $candelete array reference.
                   14702: This array is included when a single user is modified via "Manage Users",
                   14703: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14704: 
                   14705: =item *
                   14706: 
1.286     matthew  14707: modifystudent
                   14708: 
1.957     raeburn  14709: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14710: The course id is resolved based on the current user's environment.  
                   14711: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14712: associated with a course.
                   14713: 
1.297     matthew  14714: This call is essentially a wrapper for lonnet::modifyuser and
                   14715: lonnet::modify_student_enrollment
1.286     matthew  14716: 
                   14717: Inputs: 
                   14718: 
                   14719: =over 4
                   14720: 
1.957     raeburn  14721: =item B<$udom> Student's loncapa domain
1.286     matthew  14722: 
1.957     raeburn  14723: =item B<$uname> Student's loncapa login name
1.286     matthew  14724: 
1.964     bisitz   14725: =item B<$uid> Student/Employee ID
1.286     matthew  14726: 
1.957     raeburn  14727: =item B<$umode> Student's authentication mode
1.286     matthew  14728: 
1.957     raeburn  14729: =item B<$upass> Student's password
1.286     matthew  14730: 
1.957     raeburn  14731: =item B<$first> Student's first name
1.286     matthew  14732: 
1.957     raeburn  14733: =item B<$middle> Student's middle name
1.286     matthew  14734: 
1.957     raeburn  14735: =item B<$last> Student's last name
1.286     matthew  14736: 
1.957     raeburn  14737: =item B<$gene> Student's generation
1.286     matthew  14738: 
1.957     raeburn  14739: =item B<$usec> Student's section in course
1.286     matthew  14740: 
                   14741: =item B<$end> Unix time of the roles expiration
                   14742: 
                   14743: =item B<$start> Unix time of the roles start date
                   14744: 
                   14745: =item B<$forceid> If defined, allow $uid to be changed
                   14746: 
                   14747: =item B<$desiredhome> server to use as home server for student
                   14748: 
1.957     raeburn  14749: =item B<$email> Student's permanent e-mail address
                   14750: 
                   14751: =item B<$type> Type of enrollment (auto or manual)
                   14752: 
1.963     raeburn  14753: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14754: 
                   14755: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14756: 
1.963     raeburn  14757: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14758: 
1.963     raeburn  14759: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14760: 
1.1172.2.19  raeburn  14761: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14762: 
                   14763: =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  14764: 
1.286     matthew  14765: =back
1.297     matthew  14766: 
                   14767: =item *
                   14768: 
                   14769: modify_student_enrollment
                   14770: 
1.1172.2.31  raeburn  14771: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14772: 'role.request.course' must be defined for this function to proceed.
                   14773: 
                   14774: Inputs:
                   14775: 
                   14776: =over 4
                   14777: 
1.1172.2.31  raeburn  14778: =item $udom, student's domain
1.297     matthew  14779: 
1.1172.2.31  raeburn  14780: =item $uname, student's name
1.297     matthew  14781: 
1.1172.2.31  raeburn  14782: =item $uid, student's user id
1.297     matthew  14783: 
1.1172.2.31  raeburn  14784: =item $first, student's first name
1.297     matthew  14785: 
                   14786: =item $middle
                   14787: 
                   14788: =item $last
                   14789: 
                   14790: =item $gene
                   14791: 
                   14792: =item $usec
                   14793: 
                   14794: =item $end
                   14795: 
                   14796: =item $start
                   14797: 
1.957     raeburn  14798: =item $type
                   14799: 
                   14800: =item $locktype
                   14801: 
                   14802: =item $cid
                   14803: 
                   14804: =item $selfenroll
                   14805: 
                   14806: =item $context
                   14807: 
1.1172.2.19  raeburn  14808: =item $credits, number of credits student will earn from this class
                   14809: 
1.1172.2.76  raeburn  14810: =item $instsec, institutional course section code for student
                   14811: 
1.297     matthew  14812: =back
                   14813: 
1.191     harris41 14814: 
                   14815: =item *
                   14816: 
1.243     albertel 14817: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14818: custom role; give a custom role to a user for the level given by URL.  Specify
                   14819: name and domain of role author, and role name
1.191     harris41 14820: 
                   14821: =item *
                   14822: 
1.243     albertel 14823: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14824: 
                   14825: =item *
                   14826: 
1.243     albertel 14827: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14828: 
                   14829: =back
                   14830: 
                   14831: =head2 Course Infomation
                   14832: 
                   14833: =over 4
1.191     harris41 14834: 
                   14835: =item *
                   14836: 
1.1118    foxr     14837: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14838: specified course id, including all environment settings for the
                   14839: course, the description of the course will be in the hash under the
                   14840: key 'description'
1.191     harris41 14841: 
1.1118    foxr     14842: $options is an optional parameter that if supplied is a hash reference that controls
                   14843: what how this function works.  It has the following key/values:
                   14844: 
                   14845: =over 4
                   14846: 
                   14847: =item freshen_cache
                   14848: 
                   14849: If defined, and the environment cache for the course is valid, it is 
                   14850: returned in the returned hash.
                   14851: 
                   14852: =item one_time
                   14853: 
                   14854: If defined, the last cache time is set to _now_
                   14855: 
                   14856: =item user
                   14857: 
                   14858: If defined, the supplied username is used instead of the current user.
                   14859: 
                   14860: 
                   14861: =back
                   14862: 
1.191     harris41 14863: =item *
                   14864: 
1.624     albertel 14865: resdata($name,$domain,$type,@which) : request for current parameter
                   14866: setting for a specific $type, where $type is either 'course' or 'user',
                   14867: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14868: answers for 10 minutes.
1.243     albertel 14869: 
1.877     foxr     14870: =item *
                   14871: 
                   14872: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14873: data base, returning a hash that is keyed by the resource name and has
                   14874: values that are the resource value.  I believe that the timestamps and
                   14875: versions are also returned.
                   14876: 
1.1172.2.31  raeburn  14877: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14878: supplemental content area. This routine caches the number of files for
                   14879: 10 minutes.
                   14880: 
1.243     albertel 14881: =back
                   14882: 
                   14883: =head2 Course Modification
                   14884: 
                   14885: =over 4
1.191     harris41 14886: 
                   14887: =item *
                   14888: 
1.243     albertel 14889: writecoursepref($courseid,%prefs) : write preferences (environment
                   14890: database) for a course
1.191     harris41 14891: 
                   14892: =item *
                   14893: 
1.1011    raeburn  14894: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14895: 
                   14896: =item *
                   14897: 
1.1038    raeburn  14898: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14899: 
1.1167    droeschl 14900: =item *
                   14901: 
                   14902: is_course($courseid), is_course($cdom, $cnum)
                   14903: 
                   14904: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14905: two component version $cdom, $cnum. It checks if the specified course exists.
                   14906: 
                   14907: Returns:
                   14908:     undef if the course doesn't exist, otherwise
                   14909:     in scalar context the combined courseid.
                   14910:     in list context the two components of the course identifier, domain and 
                   14911:     courseid.    
                   14912: 
1.243     albertel 14913: =back
                   14914: 
1.1172.2.109  raeburn  14915: =head2 Bubblesheet Configuration
                   14916: 
                   14917: =over 4
                   14918: 
                   14919: =item *
                   14920: 
                   14921: get_scantron_config($which)
                   14922: 
                   14923: $which - the name of the configuration to parse from the file.
                   14924: 
                   14925: Parses and returns the bubblesheet configuration line selected as a
                   14926: hash of configuration file fields.
                   14927: 
                   14928: 
                   14929: Returns:
                   14930:     If the named configuration is not in the file, an empty
                   14931:     hash is returned.
                   14932: 
                   14933:     a hash with the fields
                   14934:       name         - internal name for the this configuration setup
                   14935:       description  - text to display to operator that describes this config
                   14936:       CODElocation - if 0 or the string 'none'
                   14937:                           - no CODE exists for this config
                   14938:                      if -1 || the string 'letter'
                   14939:                           - a CODE exists for this config and is
                   14940:                             a string of letters
                   14941:                      Unsupported value (but planned for future support)
                   14942:                           if a positive integer
                   14943:                                - The CODE exists as the first n items from
                   14944:                                  the question section of the form
                   14945:                           if the string 'number'
                   14946:                                - The CODE exists for this config and is
                   14947:                                  a string of numbers
                   14948:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14949:                      the CODE starts
                   14950:       CODElength  - length of the CODE
                   14951:       IDstart     - column where the student/employee ID starts
                   14952:       IDlength    - length of the student/employee ID info
                   14953:       Qstart      - column where the information from the bubbled
                   14954:                     'questions' start
                   14955:       Qlength     - number of columns comprising a single bubble line from
                   14956:                     the sheet. (usually either 1 or 10)
                   14957:       Qon         - either a single character representing the character used
                   14958:                     to signal a bubble was chosen in the positional setup, or
                   14959:                     the string 'letter' if the letter of the chosen bubble is
                   14960:                     in the final, or 'number' if a number representing the
                   14961:                     chosen bubble is in the file (1->A 0->J)
                   14962:       Qoff        - the character used to represent that a bubble was
                   14963:                     left blank
                   14964:       PaperID     - if the scanning process generates a unique number for each
                   14965:                     sheet scanned the column that this ID number starts in
                   14966:       PaperIDlength - number of columns that comprise the unique ID number
                   14967:                       for the sheet of paper
                   14968:       FirstName   - column that the first name starts in
                   14969:       FirstNameLength - number of columns that the first name spans
                   14970:       LastName    - column that the last name starts in
                   14971:       LastNameLength - number of columns that the last name spans
                   14972:       BubblesPerRow - number of bubbles available in each row used to
                   14973:                       bubble an answer. (If not specified, 10 assumed).
                   14974: 
                   14975: 
                   14976: =item *
                   14977: 
                   14978: get_scantronformat_file($cdom)
                   14979: 
                   14980: $cdom - the course's domain (optional); if not supplied, uses
                   14981: domain for current $env{'request.course.id'}.
                   14982: 
                   14983: Returns an array containing lines from the scantron format file for
                   14984: the domain of the course.
                   14985: 
                   14986: If a url for a custom.tab file is listed in domain's configuration.db,
                   14987: lines are from this file.
                   14988: 
                   14989: Otherwise, if a default.tab has been published in RES space by the
                   14990: domainconfig user, lines are from this file.
                   14991: 
                   14992: Otherwise, fall back to getting lines from the legacy file on the
                   14993: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14994: 
                   14995: =back
                   14996: 
1.243     albertel 14997: =head2 Resource Subroutines
                   14998: 
                   14999: =over 4
1.191     harris41 15000: 
                   15001: =item *
                   15002: 
1.243     albertel 15003: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15004: 
                   15005: =item *
                   15006: 
1.243     albertel 15007: repcopy($filename) : subscribes to the requested file, and attempts to
                   15008: replicate from the owning library server, Might return
1.607     raeburn  15009: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15010: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15011: resource. Expects the local filesystem pathname
                   15012: (/home/httpd/html/res/....)
                   15013: 
                   15014: =back
                   15015: 
                   15016: =head2 Resource Information
                   15017: 
                   15018: =over 4
1.191     harris41 15019: 
                   15020: =item *
                   15021: 
1.1172.2.28  raeburn  15022: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15023: and returns the value of a variety of different possible values,
                   15024: $varname should be a request string, and the other parameters can be
                   15025: used to specify who and what one is asking about. Ordinarily, $cid 
                   15026: does not need to be specified, as it is retrived from 
                   15027: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15028: within lonuserstate::loadmap() when initializing a course, before
                   15029: $env{'request.course.id'} has been set, so it needs to be provided
                   15030: in that one case.
1.243     albertel 15031: 
                   15032: Possible values for $varname are environment.lastname (or other item
                   15033: from the envirnment hash), user.name (or someother aspect about the
                   15034: user), resource.0.maxtries (or some other part and parameter of a
                   15035: resource)
1.204     albertel 15036: 
                   15037: =item *
                   15038: 
1.243     albertel 15039: directcondval($number) : get current value of a condition; reads from a state
                   15040: string
1.204     albertel 15041: 
                   15042: =item *
                   15043: 
1.243     albertel 15044: condval($condidx) : value of condition index based on state
1.204     albertel 15045: 
                   15046: =item *
                   15047: 
1.243     albertel 15048: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15049: resource's metadata, $what should be either a specific key, or either
                   15050: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15051: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15052: 
                   15053: this function automatically caches all requests
1.191     harris41 15054: 
                   15055: =item *
                   15056: 
1.243     albertel 15057: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15058: network of library servers; returns file handle of where SQL and regex results
                   15059: will be stored for query
1.191     harris41 15060: 
                   15061: =item *
                   15062: 
1.1172.2.66  raeburn  15063: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15064: return symbolic list entry (all arguments optional).
                   15065: 
                   15066: Args: filename is the filename (including path) for the file for which a symb
                   15067: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15068: to check access status if more than one resource was found in the bighash
                   15069: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15070: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15071: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15072: cause possible symbs to be checked to determine if they are subject to content
                   15073: blocking, if so they will not be included as possible symbs; possibles is a
                   15074: ref to a hash, which, as a side effect, will be populated with all possible
                   15075: symbs (content blocking not tested).
                   15076: 
1.243     albertel 15077: returns the data handle
1.191     harris41 15078: 
                   15079: =item *
                   15080: 
1.1172.2.17  raeburn  15081: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15082: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15083: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15084: on failure, user must be in a course, as it assumes the existence of
                   15085: the course initial hash, and uses $env('request.course.id'}.  The third
                   15086: arg is an optional reference to a scalar.  If this arg is passed in the
                   15087: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15088: encrypted; otherwise it will be null.
1.243     albertel 15089: 
1.191     harris41 15090: =item *
                   15091: 
1.243     albertel 15092: symbclean($symb) : removes versions numbers from a symb, returns the
                   15093: cleaned symb
1.191     harris41 15094: 
                   15095: =item *
                   15096: 
1.243     albertel 15097: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15098: course map, user must be in a course for it to work.
1.191     harris41 15099: 
                   15100: =item *
                   15101: 
1.243     albertel 15102: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15103: 
                   15104: =item *
                   15105: 
1.243     albertel 15106: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15107: a random seed, all arguments are optional, if they aren't sent it uses the
                   15108: environment to derive them. Note: if symb isn't sent and it can't get one
                   15109: from &symbread it will use the current time as its return value
1.191     harris41 15110: 
                   15111: =item *
                   15112: 
1.243     albertel 15113: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15114: unfakeable, receipt
1.191     harris41 15115: 
                   15116: =item *
                   15117: 
1.620     albertel 15118: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15119: 
                   15120: =item *
                   15121: 
1.243     albertel 15122: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15123: 
                   15124: =item *
                   15125: 
1.243     albertel 15126: 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 15127: 
                   15128: =item *
                   15129: 
1.243     albertel 15130: 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 15131: 
                   15132: =item *
                   15133: 
1.243     albertel 15134: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15135: 
                   15136: =item *
                   15137: 
1.243     albertel 15138: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15139: forcing spreadsheet to reevaluate the resource scores next time.
                   15140: 
1.1172.2.13  raeburn  15141: =item *
                   15142: 
                   15143: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15144: when viewing in course context.
                   15145: 
                   15146:  input: six args -- filename (decluttered), course number, course domain,
                   15147:                     url, symb (if registered) and group (if this is a
                   15148:                     group item -- e.g., bulletin board, group page etc.).
                   15149: 
                   15150:  output: array of five scalars --
                   15151:          $cfile -- url for file editing if editable on current server
                   15152:          $home -- homeserver of resource (i.e., for author if published,
                   15153:                                           or course if uploaded.).
                   15154:          $switchserver --  1 if server switch will be needed.
                   15155:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15156:          $forceview -- 1 if icon/link should be to go to view mode
                   15157: 
                   15158: =item *
                   15159: 
                   15160: is_course_upload($file,$cnum,$cdom)
                   15161: 
                   15162: Used in course context to determine if current file was uploaded to
                   15163: the course (i.e., would be found in /userfiles/docs on the course's
                   15164: homeserver.
                   15165: 
                   15166:   input: 3 args -- filename (decluttered), course number and course domain.
                   15167:   output: boolean -- 1 if file was uploaded.
                   15168: 
1.243     albertel 15169: =back
                   15170: 
                   15171: =head2 Storing/Retreiving Data
                   15172: 
                   15173: =over 4
1.191     harris41 15174: 
                   15175: =item *
                   15176: 
1.1172.2.64  raeburn  15177: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15178: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15179: the remaining args aren't required and if they aren't passed or are '' they will
                   15180: be derived from the env (with the exception of $laststore, which is an
                   15181: optional arg used when a user's submission is stored in grading).
                   15182: $laststore is $version=$timestamp, where $version is the most recent version
                   15183: number retrieved for the corresponding $symb in the $namespace db file, and
                   15184: $timestamp is the timestamp for that transaction (UNIX time).
                   15185: $laststore is currently only passed when cstore() is called by
                   15186: structuretags::finalize_storage().
1.191     harris41 15187: 
                   15188: =item *
                   15189: 
1.1172.2.64  raeburn  15190: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15191: but uses critical subroutine
1.191     harris41 15192: 
                   15193: =item *
                   15194: 
1.243     albertel 15195: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15196: all args are optional
1.191     harris41 15197: 
                   15198: =item *
                   15199: 
1.717     albertel 15200: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15201: dumps the complete (or key matching regexp) namespace into a hash
                   15202: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15203: normally &store()ed into
                   15204: 
                   15205: $range should be either an integer '100' (give me the first 100
                   15206:                                            matching records)
                   15207:               or be  two integers sperated by a - with no spaces
                   15208:                  '30-50' (give me the 30th through the 50th matching
                   15209:                           records)
                   15210: 
                   15211: 
                   15212: =item *
                   15213: 
1.1172.2.59  raeburn  15214: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15215: replaces a &store() version of data with a replacement set of data
                   15216: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15217: reference. If $tolog is true, the transaction is logged in the courselog
                   15218: with an action=PUTSTORE.
1.717     albertel 15219: 
                   15220: =item *
                   15221: 
1.243     albertel 15222: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15223: works very similar to store/cstore, but all data is stored in a
                   15224: temporary location and can be reset using tmpreset, $storehash should
                   15225: be a hash reference, returns nothing on success
1.191     harris41 15226: 
                   15227: =item *
                   15228: 
1.243     albertel 15229: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15230: similar to restore, but all data is stored in a temporary location and
                   15231: can be reset using tmpreset. Returns a hash of values on success,
                   15232: error string otherwise.
1.191     harris41 15233: 
                   15234: =item *
                   15235: 
1.243     albertel 15236: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15237: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15238: 
                   15239: =item *
                   15240: 
1.243     albertel 15241: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15242: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15243: 
                   15244: =item *
                   15245: 
1.243     albertel 15246: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15247: namesp ($udom and $uname are optional)
1.191     harris41 15248: 
                   15249: =item *
                   15250: 
1.702     albertel 15251: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15252: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15253: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15254: 
1.702     albertel 15255: $range should be either an integer '100' (give me the first 100
                   15256:                                            matching records)
                   15257:               or be  two integers sperated by a - with no spaces
                   15258:                  '30-50' (give me the 30th through the 50th matching
                   15259:                           records)
1.449     matthew  15260: =item *
                   15261: 
                   15262: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15263: $store can be a scalar, an array reference, or if the amount to be 
                   15264: incremented is > 1, a hash reference.
                   15265: 
                   15266: ($udom and $uname are optional)
1.191     harris41 15267: 
                   15268: =item *
                   15269: 
1.243     albertel 15270: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15271: ($udom and $uname are optional)
1.191     harris41 15272: 
                   15273: =item *
                   15274: 
1.243     albertel 15275: cput($namespace,$storehash,$udom,$uname) : critical put
                   15276: ($udom and $uname are optional)
1.191     harris41 15277: 
                   15278: =item *
                   15279: 
1.748     albertel 15280: newput($namespace,$storehash,$udom,$uname) :
                   15281: 
                   15282: Attempts to store the items in the $storehash, but only if they don't
                   15283: currently exist, if this succeeds you can be certain that you have 
                   15284: successfully created a new key value pair in the $namespace db.
                   15285: 
                   15286: 
                   15287: Args:
                   15288:  $namespace: name of database to store values to
                   15289:  $storehash: hashref to store to the db
                   15290:  $udom: (optional) domain of user containing the db
                   15291:  $uname: (optional) name of user caontaining the db
                   15292: 
                   15293: Returns:
                   15294:  'ok' -> succeeded in storing all keys of $storehash
                   15295:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15296:                         least <key> already existed in the db (other
                   15297:                         requested keys may also already exist)
1.967     bisitz   15298:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15299:  'con_lost' -> unable to contact request server
                   15300:  'refused' -> action was not allowed by remote machine
                   15301: 
                   15302: 
                   15303: =item *
                   15304: 
1.243     albertel 15305: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15306: reference filled in from namesp (encrypts the return communication)
                   15307: ($udom and $uname are optional)
1.191     harris41 15308: 
                   15309: =item *
                   15310: 
1.243     albertel 15311: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15312: critical subroutine
                   15313: 
1.806     raeburn  15314: =item *
                   15315: 
1.860     raeburn  15316: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15317: array reference filled in from namespace found in domain level on either
                   15318: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15319: 
                   15320: =item *
                   15321: 
1.860     raeburn  15322: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15323: domain level either on specified domain server ($uhome) or primary domain 
                   15324: server ($udom and $uhome are optional)
1.806     raeburn  15325: 
1.943     raeburn  15326: =item * 
                   15327: 
1.1172.2.35  raeburn  15328: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15329: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15330: the target domain.
                   15331: 
                   15332: May also include additional key => value pairs for the following groups:
                   15333: 
                   15334: =over
                   15335: 
                   15336: =item
                   15337: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15338: 
                   15339: =over
                   15340: 
                   15341: =item defaultquota, authorquota
                   15342: 
                   15343: =back
                   15344: 
                   15345: =item
                   15346: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15347: portfolio for users).
                   15348: 
                   15349: =over
                   15350: 
                   15351: =item
                   15352: aboutme, blog, webdav, portfolio
                   15353: 
                   15354: =back
                   15355: 
                   15356: =item
                   15357: requestcourses: ability to request courses, and how requests are processed.
                   15358: 
                   15359: =over
                   15360: 
                   15361: =item
1.1172.2.37  raeburn  15362: official, unofficial, community, textbook
1.1172.2.35  raeburn  15363: 
                   15364: =back
                   15365: 
                   15366: =item
                   15367: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15368: 
                   15369: =over
                   15370: 
                   15371: =item
1.1172.2.44  raeburn  15372: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15373: 
                   15374: =back
                   15375: 
                   15376: =item
                   15377: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15378: for course's uploaded content.
                   15379: 
                   15380: =over
                   15381: 
                   15382: =item
1.1172.2.68  raeburn  15383: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15384: communityquota, textbookquota
1.1172.2.35  raeburn  15385: 
                   15386: =back
                   15387: 
                   15388: =item
                   15389: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15390: on your servers.
                   15391: 
                   15392: =over
                   15393: 
                   15394: =item
                   15395: remotesessions, hostedsessions
                   15396: 
                   15397: =back
                   15398: 
                   15399: =back
                   15400: 
                   15401: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15402: utility to create a configuration.db file on a domain's primary library server
                   15403: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15404: -- corresponding values are authentication type (internal, krb4, krb5,
                   15405: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15406: will be available. Values are retrieved from cache (if current), unless the
                   15407: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15408: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15409: 
                   15410: Typical usage:
1.943     raeburn  15411: 
1.1172.2.35  raeburn  15412: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15413: 
1.243     albertel 15414: =back
                   15415: 
                   15416: =head2 Network Status Functions
                   15417: 
                   15418: =over 4
1.191     harris41 15419: 
                   15420: =item *
                   15421: 
1.1137    raeburn  15422: dirlist() : return directory list based on URI (first arg).
                   15423: 
                   15424: Inputs: 1 required, 5 optional.
                   15425: 
                   15426: =over
                   15427: 
                   15428: =item 
                   15429: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15430: 
                   15431: =item
                   15432: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15433: 
                   15434: =item
                   15435: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15436: 
                   15437: =item
                   15438: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15439: 
                   15440: =item
                   15441: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15442: 
                   15443: =item 
                   15444: $alternateRoot - path to prepend in place of path from $uri.
                   15445: 
                   15446: =back
                   15447: 
                   15448: Returns: Array of up to two items.
                   15449: 
                   15450: =over
                   15451: 
                   15452: a reference to an array of files/subdirectories
                   15453: 
                   15454: =over
                   15455: 
                   15456: Each element in the array of files/subdirectories is a & separated list of
                   15457: item name and the result of running stat on the item.  If dirlist was requested
                   15458: for a file instead of a directory, the item name will be ''. For a directory 
                   15459: listing, if the item is a metadata file, the element will end &N&M 
                   15460: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15461: default copyright set (1).  
                   15462: 
                   15463: =back
                   15464: 
                   15465: a scalar containing error condition (if encountered).
                   15466: 
                   15467: =over
                   15468: 
                   15469: =item 
                   15470: no_host (no homeserver identified for $username:$domain).
                   15471: 
                   15472: =item 
                   15473: no_such_host (server contacted for listing not identified as valid host).
                   15474: 
                   15475: =item 
                   15476: con_lost (connection to remote server failed).
                   15477: 
                   15478: =item 
                   15479: refused (invalid $username:$domain received on lond side).
                   15480: 
                   15481: =item 
                   15482: no_such_dir (directory at specified path on lond side does not exist). 
                   15483: 
                   15484: =item 
                   15485: empty (directory at specified path on lond side is empty).
                   15486: 
                   15487: =over
                   15488: 
                   15489: This is currently not encountered because the &ls3, &ls2, 
                   15490: &ls (_handler) routines on the lond side do not filter out
                   15491: . and .. from a directory listing. 
                   15492: 
                   15493: =back
                   15494: 
                   15495: =back
                   15496: 
                   15497: =back
1.191     harris41 15498: 
                   15499: =item *
                   15500: 
1.243     albertel 15501: spareserver() : find server with least workload from spare.tab
                   15502: 
1.986     foxr     15503: 
                   15504: =item *
                   15505: 
                   15506: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15507: if there is no corresponding loncapa host.
                   15508: 
1.243     albertel 15509: =back
                   15510: 
1.986     foxr     15511: 
1.243     albertel 15512: =head2 Apache Request
                   15513: 
                   15514: =over 4
1.191     harris41 15515: 
                   15516: =item *
                   15517: 
1.243     albertel 15518: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15519: localhost, posts hash
                   15520: 
                   15521: =back
                   15522: 
                   15523: =head2 Data to String to Data
                   15524: 
                   15525: =over 4
1.191     harris41 15526: 
                   15527: =item *
                   15528: 
1.243     albertel 15529: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15530: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15531: 
                   15532: =item *
                   15533: 
1.243     albertel 15534: hashref2str($hashref) : convert a hashref into a string complete with
                   15535: escaping and '=' and '&' separators, supports elements that are
                   15536: arrayrefs and hashrefs
1.191     harris41 15537: 
                   15538: =item *
                   15539: 
1.243     albertel 15540: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15541: with escaping and '&' separators, supports elements that are arrayrefs
                   15542: and hashrefs
1.191     harris41 15543: 
                   15544: =item *
                   15545: 
1.243     albertel 15546: str2hash($string) : convert string to hash using unescaping and
                   15547: splitting on '=' and '&', supports elements that are arrayrefs and
                   15548: hashrefs
1.191     harris41 15549: 
                   15550: =item *
                   15551: 
1.243     albertel 15552: str2array($string) : convert string to hash using unescaping and
                   15553: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15554: 
                   15555: =back
                   15556: 
                   15557: =head2 Logging Routines
                   15558: 
                   15559: 
                   15560: These routines allow one to make log messages in the lonnet.log and
                   15561: lonnet.perm logfiles.
1.191     harris41 15562: 
1.1119    foxr     15563: =over 4
                   15564: 
1.191     harris41 15565: =item *
                   15566: 
1.243     albertel 15567: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15568: 
                   15569: =item *
                   15570: 
1.243     albertel 15571: logthis() : append message to the normal lonnet.log file, it gets
                   15572: preiodically rolled over and deleted.
1.191     harris41 15573: 
                   15574: =item *
                   15575: 
1.243     albertel 15576: logperm() : append a permanent message to lonnet.perm.log, this log
                   15577: file never gets deleted by any automated portion of the system, only
                   15578: messages of critical importance should go in here.
                   15579: 
1.1119    foxr     15580: 
1.243     albertel 15581: =back
                   15582: 
                   15583: =head2 General File Helper Routines
                   15584: 
                   15585: =over 4
1.191     harris41 15586: 
                   15587: =item *
                   15588: 
1.481     raeburn  15589: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15590: (a) files in /uploaded
                   15591:   (i) If a local copy of the file exists - 
                   15592:       compares modification date of local copy with last-modified date for 
                   15593:       definitive version stored on home server for course. If local copy is 
                   15594:       stale, requests a new version from the home server and stores it. 
                   15595:       If the original has been removed from the home server, then local copy 
                   15596:       is unlinked.
                   15597:   (ii) If local copy does not exist -
                   15598:       requests the file from the home server and stores it. 
                   15599:   
                   15600:   If $caller is 'uploadrep':  
                   15601:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15602:     for request for files originally uploaded via DOCS. 
                   15603:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15604:   
                   15605:   Otherwise:
                   15606:      This indicates a call from the content generation phase of the request.
                   15607:      -  returns the entire contents of the file or -1.
                   15608:      
                   15609: (b) files in /res
                   15610:    - returns the entire contents of a file or -1; 
                   15611:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15612: 
1.712     albertel 15613: 
                   15614: =item *
                   15615: 
                   15616: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15617:                   reference
                   15618: 
                   15619: returns either a stat() list of data about the file or an empty list
                   15620: if the file doesn't exist or couldn't find out about it (connection
                   15621: problems or user unknown)
                   15622: 
1.191     harris41 15623: =item *
                   15624: 
1.243     albertel 15625: filelocation($dir,$file) : returns file system location of a file
                   15626: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15627: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15628: and a file of ../bob will become /a/bob)
1.191     harris41 15629: 
                   15630: =item *
                   15631: 
                   15632: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15633: filelocation except for hrefs
                   15634: 
                   15635: =item *
                   15636: 
1.1172.2.49  raeburn  15637: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15638: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15639: 
1.243     albertel 15640: =back
                   15641: 
1.608     albertel 15642: =head2 Usererfile file routines (/uploaded*)
                   15643: 
                   15644: =over 4
                   15645: 
                   15646: =item *
                   15647: 
                   15648: userfileupload(): main rotine for putting a file in a user or course's
                   15649:                   filespace, arguments are,
                   15650: 
1.620     albertel 15651:  formname - required - this is the name of the element in $env where the
1.608     albertel 15652:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15653:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15654:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15655:  context - if coursedoc, store the file in the course of the active role
                   15656:              of the current user; 
                   15657:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15658:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15659:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15660:          if undefined, it will be placed in "unknown"
                   15661: 
                   15662:  (This routine calls clean_filename() to remove any dangerous
                   15663:  characters from the filename, and then calls finuserfileupload() to
                   15664:  complete the transaction)
                   15665: 
                   15666:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15667:  and /adm/notfound.html if unsuccessful
                   15668: 
                   15669: =item *
                   15670: 
                   15671: clean_filename(): routine for cleaing a filename up for storage in
                   15672:                  userfile space, argument is:
                   15673: 
                   15674:  filename - proposed filename
                   15675: 
                   15676: returns: the new clean filename
                   15677: 
                   15678: =item *
                   15679: 
1.1090    raeburn  15680: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15681: userspace, probably shouldn't be called directly
                   15682: 
                   15683:   docuname: username or courseid of destination for the file
                   15684:   docudom: domain of user/course of destination for the file
                   15685:   formname: same as for userfileupload()
1.1090    raeburn  15686:   fname: filename (including subdirectories) for the file
                   15687:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15688:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15689:   allfiles: reference to hash used to store objects found by parser
                   15690:   codebase: reference to hash used for codebases of java objects found by parser
                   15691:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15692:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15693:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15694:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15695:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15696:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15697:   mimetype: reference to scalar to accommodate mime type determined
                   15698:             from File::MMagic if $parser = parse.
1.608     albertel 15699: 
                   15700:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15701:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15702:  was 'overwrite').
                   15703:  
1.608     albertel 15704: 
                   15705: =item *
                   15706: 
                   15707: renameuserfile(): renames an existing userfile to a new name
                   15708: 
                   15709:   Args:
                   15710:    docuname: username or courseid of destination for the file
                   15711:    docudom: domain of user/course of destination for the file
                   15712:    old: current file name (including any subdirs under userfiles)
                   15713:    new: desired file name (including any subdirs under userfiles)
                   15714: 
                   15715: =item *
                   15716: 
                   15717: mkdiruserfile(): creates a directory is a userfiles dir
                   15718: 
                   15719:   Args:
                   15720:    docuname: username or courseid of destination for the file
                   15721:    docudom: domain of user/course of destination for the file
                   15722:    dir: dir to create (including any subdirs under userfiles)
                   15723: 
                   15724: =item *
                   15725: 
                   15726: removeuserfile(): removes a file that exists in userfiles
                   15727: 
                   15728:   Args:
                   15729:    docuname: username or courseid of destination for the file
                   15730:    docudom: domain of user/course of destination for the file
                   15731:    fname: filname to delete (including any subdirs under userfiles)
                   15732: 
                   15733: =item *
                   15734: 
                   15735: removeuploadedurl(): convience function for removeuserfile()
                   15736: 
                   15737:   Args:
                   15738:    url:  a full /uploaded/... url to delete
                   15739: 
1.747     albertel 15740: =item * 
                   15741: 
                   15742: get_portfile_permissions():
                   15743:   Args:
                   15744:     domain: domain of user or course contain the portfolio files
                   15745:     user: name of user or num of course contain the portfolio files
                   15746:   Returns:
                   15747:     hashref of a dump of the proper file_permissions.db
                   15748:    
                   15749: 
                   15750: =item * 
                   15751: 
                   15752: get_access_controls():
                   15753: 
                   15754: Args:
                   15755:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15756:   group: (optional) the group you want the files associated with
                   15757:   file: (optional) the file you want access info on
                   15758: 
                   15759: Returns:
1.749     raeburn  15760:     a hash (keys are file names) of hashes containing
                   15761:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15762:         values are XML containing access control settings (see below) 
1.747     albertel 15763: 
                   15764: Internal notes:
                   15765: 
1.749     raeburn  15766:  access controls are stored in file_permissions.db as key=value pairs.
                   15767:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15768:         where scope -> public,guest,course,group,domains or users.
                   15769:               end -> UNIX time for end of access (0 -> no end date)
                   15770:               start -> UNIX time for start of access
                   15771: 
                   15772:     value -> XML description of access control
                   15773:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15774:             <start></start>
                   15775:             <end></end>
                   15776: 
                   15777:             <password></password>  for scope type = guest
                   15778: 
                   15779:             <domain></domain>     for scope type = course or group
                   15780:             <number></number>
                   15781:             <roles id="">
                   15782:              <role></role>
                   15783:              <access></access>
                   15784:              <section></section>
                   15785:              <group></group>
                   15786:             </roles>
                   15787: 
                   15788:             <dom></dom>         for scope type = domains
                   15789: 
                   15790:             <users>             for scope type = users
                   15791:              <user>
                   15792:               <uname></uname>
                   15793:               <udom></udom>
                   15794:              </user>
                   15795:             </users>
                   15796:            </scope> 
                   15797:               
                   15798:  Access data is also aggregated for each file in an additional key=value pair:
                   15799:  key -> path to file/file_name\0accesscontrol 
                   15800:  value -> reference to hash
                   15801:           hash contains key = value pairs
                   15802:           where key = uniqueID:scope_end_start
                   15803:                 value = UNIX time record was last updated
                   15804: 
                   15805:           Used to improve speed of look-ups of access controls for each file.  
                   15806:  
                   15807:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15808: 
1.1172.2.13  raeburn  15809: =item *
                   15810: 
1.749     raeburn  15811: modify_access_controls():
                   15812: 
                   15813: Modifies access controls for a portfolio file
                   15814: Args
                   15815: 1. file name
                   15816: 2. reference to hash of required changes,
                   15817: 3. domain
                   15818: 4. username
                   15819:   where domain,username are the domain of the portfolio owner 
                   15820:   (either a user or a course) 
                   15821: 
                   15822: Returns:
                   15823: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15824: 2. result of deletions ('ok' or 'error', with error message).
                   15825: 3. reference to hash of any new or updated access controls.
                   15826: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15827:    key = integer (inbound ID)
1.1172.2.13  raeburn  15828:    value = uniqueID
                   15829: 
                   15830: =item *
                   15831: 
                   15832: get_timebased_id():
                   15833: 
                   15834: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15835: course via the Course Editor (e.g., folders, composite pages,
                   15836: group bulletin boards).
                   15837: 
                   15838: Args: (first three required; six others optional)
                   15839: 
                   15840: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15841:    docssequence, or name of group
                   15842: 
                   15843: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15844:    e.g., num, boardids
                   15845: 
                   15846: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15847:    file will be named nohist_namespace.db
                   15848: 
                   15849: 4. cdom: domain of course; default is current course domain from %env
                   15850: 
                   15851: 5. cnum: course number; default is current course number from %env
                   15852: 
                   15853: 6. idtype: set to concat if an additional digit is to be appended to the
                   15854:    unix timestamp to form the suffix, if the plain timestamp is already
                   15855:    in use.  Default is to not do this, but simply increment the unix
                   15856:    timestamp by 1 until a unique key is obtained.
                   15857: 
                   15858: 7. who: holder of locking key; defaults to user:domain for user.
                   15859: 
                   15860: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15861:    retrying); default is 3.
                   15862: 
                   15863: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15864: 
                   15865: Returns:
                   15866: 
                   15867: 1. suffix obtained (numeric)
                   15868: 
                   15869: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15870: 
                   15871: 3. error: contains (localized) error message if an error occurred.
                   15872: 
1.747     albertel 15873: 
1.608     albertel 15874: =back
                   15875: 
1.243     albertel 15876: =head2 HTTP Helper Routines
                   15877: 
                   15878: =over 4
                   15879: 
1.191     harris41 15880: =item *
                   15881: 
                   15882: escape() : unpack non-word characters into CGI-compatible hex codes
                   15883: 
                   15884: =item *
                   15885: 
                   15886: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15887: 
1.243     albertel 15888: =back
                   15889: 
                   15890: =head1 PRIVATE SUBROUTINES
                   15891: 
                   15892: =head2 Underlying communication routines (Shouldn't call)
                   15893: 
                   15894: =over 4
                   15895: 
                   15896: =item *
                   15897: 
                   15898: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15899: 
                   15900: =item *
                   15901: 
                   15902: reply() : uses subreply to send a message to remote machine, logs all failures
                   15903: 
                   15904: =item *
                   15905: 
                   15906: critical() : passes a critical message to another server; if cannot
                   15907: get through then place message in connection buffer directory and
                   15908: returns con_delayed, if incapable of saving message, returns
                   15909: con_failed
                   15910: 
                   15911: =item *
                   15912: 
                   15913: reconlonc() : tries to reconnect lonc client processes.
                   15914: 
                   15915: =back
                   15916: 
                   15917: =head2 Resource Access Logging
                   15918: 
                   15919: =over 4
                   15920: 
                   15921: =item *
                   15922: 
                   15923: flushcourselogs() : flush (save) buffer logs and access logs
                   15924: 
                   15925: =item *
                   15926: 
                   15927: courselog($what) : save message for course in hash
                   15928: 
                   15929: =item *
                   15930: 
                   15931: courseacclog($what) : save message for course using &courselog().  Perform
                   15932: special processing for specific resource types (problems, exams, quizzes, etc).
                   15933: 
1.191     harris41 15934: =item *
                   15935: 
                   15936: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15937: as a PerlChildExitHandler
1.243     albertel 15938: 
                   15939: =back
                   15940: 
                   15941: =head2 Other
                   15942: 
                   15943: =over 4
                   15944: 
                   15945: =item *
                   15946: 
                   15947: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15948: 
                   15949: =back
                   15950: 
                   15951: =cut
1.877     foxr     15952: 

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